import {activePass} from './access.mjs'; // Firestore storage for the m.ai API (firebase-admin). firestore.rules deny every client; only this server reads and writes. // accounts/{uid} {sid, plan, created, cancel_at, cancel_reason, the account's Razorpay subscription, and // next_sid, next_plan, next_start, next_kind} the one that starts when it ends // orders/{orderId} {uid, plan, amount, status, created, payment, starts, ends} one-time payments (status created|paid|refunded) // usage/{uid} {session:{start,count}, week:{start,count}} chat tokens used per window // events/{eventId} {created} webhook deliveries already handled // Queries are equality on one field (uid) only, so no composite index is needed; each user has few orders. // Anything two requests could race on runs in a transaction (or a create, which fails if the document exists). import {createHash} from 'node:crypto'; import {usageWindow, passEnd} from './core.mjs'; export function storage(db, {session, week}) { const accounts=db.collection('accounts'), orders=db.collection('orders'), usage=db.collection('usage'), events=db.collection('events'); const data=s=>s.exists?{id:s.id,...s.data()}:null; const ordersOf=async(uid,t)=>{const q=orders.where('uid','==',uid);return (await (t?t.get(q):q.get())).docs.map(data);}; const windows=(d,now)=>({session:usageWindow(d?.session,session,now),week:usageWindow(d?.week,week,now)}); // Razorpay event ids are short and alphanumeric; anything else is hashed into a valid document id. const eventDoc=id=>events.doc(/^[A-Za-z0-9_-]{1,200}$/.test(id)?id:'sha256_'+createHash('sha256').update(id).digest('hex')); return { ping:()=>db.collection('health').doc('ping').get(), account:async uid=>data(await accounts.doc(uid).get()), // Sets the account's subscription id only if it is still `expected` (null: no account yet). False if it changed. replaceSid:(uid,expected,sid,fields={})=>db.runTransaction(async t=>{ const ref=accounts.doc(uid), now=(await t.get(ref)).data(); if((now?.sid??null)!==expected)return false; t.set(ref,{...now,...fields,sid}); return true; }), // Undoes a pending mark that is still `expected`: back to the previous account (as read before), or no account. restoreSid:(uid,expected,previous)=>db.runTransaction(async t=>{ const ref=accounts.doc(uid), now=(await t.get(ref)).data(); if(now?.sid!==expected)return false; if(previous){const {id,...fields}=previous;t.set(ref,fields);}else t.delete(ref); return true; }), setCancelAt:(uid,at,reason)=>accounts.doc(uid).update({cancel_at:at,...(reason?{cancel_reason:reason}:{})}), // The next subscription (a plan switch or a resubscription), set only if the current next is still `expected`. setNext:(uid,expected,fields)=>db.runTransaction(async t=>{ const ref=accounts.doc(uid), now=(await t.get(ref)).data(); if(!now||(now.next_sid??null)!==expected)return false; t.set(ref,{...now,...fields}); return true; }), clearNext:(uid,expected)=>db.runTransaction(async t=>{ const ref=accounts.doc(uid), now=(await t.get(ref)).data(); if(!now||now.next_sid!==expected)return false; t.set(ref,{...now,next_sid:null,next_plan:null,next_start:null,next_kind:null}); return true; }), // The current period is over and the next subscription took over: it becomes the account's subscription. promote:(uid,sid,next)=>db.runTransaction(async t=>{ const ref=accounts.doc(uid), now=(await t.get(ref)).data(); if(!now||now.sid!==sid||now.next_sid!==next)return false; t.set(ref,{...now,sid:next,plan:now.next_plan,created:Date.now(),cancel_at:null,cancel_reason:null,next_sid:null,next_plan:null,next_start:null,next_kind:null}); return true; }), order:async id=>data(await orders.doc(id).get()), ordersOf, addOrder:({id,...o})=>orders.doc(id).create(o), pass:async(uid,now=Date.now())=>(await ordersOf(uid)).filter(o=>activePass(o,now)).sort((a,b)=>b.ends-a.ends)[0]||null, // Settles an order exactly once. A new pass starts when the buyer's latest paid one ends (or now). markPaid:(id,payment,period,now=Date.now())=>db.runTransaction(async t=>{ const ref=orders.doc(id), o=data(await t.get(ref)); if(!o||o.status==='paid')return o; const starts=Math.max(now,...(await ordersOf(o.uid,t)).filter(x=>x.status==='paid').map(x=>x.ends)); const paid={status:'paid',payment:payment||null,starts,ends:passEnd(starts,period)}; t.update(ref,paid); return {...o,...paid}; }), // A fully refunded pass stops granting access; the order is kept, marked refunded, for the records. markRefunded:(id,now=Date.now())=>db.runTransaction(async t=>{ const ref=orders.doc(id), o=data(await t.get(ref)); if(!o||o.status!=='paid')return false; t.update(ref,{status:'refunded',refunded:now}); return true; }), // Account deletion: the chat usage record goes; payment records stay (no personal details, kept for tax law). forget:uid=>usage.doc(uid).delete(), usage:async(uid,now=Date.now())=>windows((await usage.doc(uid).get()).data(),now), // Adds one reply's tokens to both windows, after the reply (a window starts with its first reply). The limits are // checked before the reply; one reply at a time per account, so a reply can pass a limit by at most itself. charge:(uid,tokens,now=Date.now())=>db.runTransaction(async t=>{ const ref=usage.doc(uid), w=windows((await t.get(ref)).data(),now); const next={session:{start:w.session.start??now,count:w.session.count+tokens},week:{start:w.week.start??now,count:w.week.count+tokens}}; t.set(ref,next); return next; }), eventDone:async id=>(await eventDoc(id).get()).exists, // Mark complete only after idempotent processing succeeds. True for first completion; false for a repeated (or parallel) delivery. claimEvent:async(id,now=Date.now())=>{ try{await eventDoc(id).create({created:now});return true;} catch(e){if(e.code===6)return false;throw e;} // 6 = ALREADY_EXISTS }, }; }