From 3b949b907f8ad08c470f6a38baf5972356e87786 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:22:03 +0530 Subject: [PATCH 01/14] Add linked sample data for the public society demo --- apps/web/src/lib/demo/data.test.ts | 48 +++++++++++ apps/web/src/lib/demo/data.ts | 126 +++++++++++++++++++++++++++++ 2 files changed, 174 insertions(+) create mode 100644 apps/web/src/lib/demo/data.test.ts create mode 100644 apps/web/src/lib/demo/data.ts diff --git a/apps/web/src/lib/demo/data.test.ts b/apps/web/src/lib/demo/data.test.ts new file mode 100644 index 0000000..298aeaa --- /dev/null +++ b/apps/web/src/lib/demo/data.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import * as s from '@opensociety/shared' +import { createDemoData } from './data' + +describe('demo society', () => { + it('populates every dashboard collection with valid contracts', () => { + const d = createDemoData() + const collections = [ + [d.apartments, s.apartmentSchema], [d.users, s.userSchema], [d.guards, s.guardSchema], + [d.duty, s.guardDutySessionSchema], [d.devices, s.guardDeviceSchema], [d.visitors, s.visitorEntrySchema], + [d.preApprovals, s.visitorPreApprovalSchema], [d.notices, s.noticeSchema], [d.tickets, s.ticketSchema], + [d.houseHelp, s.houseHelpSchema], [d.reviews, s.houseHelpReviewSchema], [d.assignments, s.houseHelpAssignmentSchema], + [d.vehicles, s.vehicleSchema], [d.accounts, s.accountSchema], [d.bills, s.maintenanceBillSchema], + [d.payments, s.paymentSchema], [d.vendors, s.vendorSchema], [d.expenses, s.expenseSchema], + ] as const + for (const [rows, schema] of collections) { + expect(rows.length).toBeGreaterThan(0) + for (const row of rows) expect(schema.safeParse(row).success, JSON.stringify(row)).toBe(true) + } + expect(s.societyConfigSchema.safeParse(d.society).success).toBe(true) + expect(s.billConfigSchema.safeParse(d.billConfig).success).toBe(true) + expect(d.attendance.length).toBeGreaterThan(0) + expect(d.parking.some(p => p.isVisitor && p.occupiedByEntryId)).toBe(true) + }) + + it('links records and reconciles bill balances to payments', () => { + const d = createDemoData() + const apartmentIds = new Set(d.apartments.map(a => a.id)) + for (const row of [...d.bills, ...d.visitors, ...d.vehicles, ...d.tickets, ...d.assignments]) { + expect(apartmentIds.has(row.apartmentId)).toBe(true) + } + for (const bill of d.bills) { + const paid = d.payments.filter(p => p.billId === bill.id).reduce((sum, p) => sum + p.amount, 0) + expect(bill.paidAmount).toBe(paid) + expect(bill.status).toBe(s.billStatusFor(bill.totalAmount, paid)) + } + }) + + it('refreshes dates for each visit and never shares mutable records', () => { + const now = new Date('2030-01-01T12:00:00Z') + const a = createDemoData(now) + const b = createDemoData(now) + a.apartments[0].tower = 'Changed' + expect(b.apartments[0].tower).toBe('A') + expect(b.bills.some(bill => bill.periodMonth === '2030-01')).toBe(true) + expect(b.preApprovals.every(p => new Date(p.validUntil!).getTime() > now.getTime())).toBe(true) + }) +}) diff --git a/apps/web/src/lib/demo/data.ts b/apps/web/src/lib/demo/data.ts new file mode 100644 index 0000000..ecb9e5d --- /dev/null +++ b/apps/web/src/lib/demo/data.ts @@ -0,0 +1,126 @@ +import * as s from '@opensociety/shared' +import type { HouseHelpRow, ParkingSlotRow } from '../api' + +export const demoId = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}` +export const DEMO_ADMIN = demoId(100) + +export function createDemoData(now = new Date()) { + const at = (days = 0, hours = 0) => new Date(now.getTime() + days * 86400000 + hours * 3600000).toISOString() + const stamp = { createdAt: at(-60), updatedAt: at() } + const apartments: s.Apartment[] = Array.from({ length: 12 }, (_, i) => ({ + id: demoId(i + 1), tower: i < 6 ? 'A' : 'B', apartmentNo: `${Math.floor(i % 6 / 2) + 1}0${i % 2 + 1}`, + floor: Math.floor(i % 6 / 2) + 1, bhkType: i < 6 ? '2BHK' : '3BHK', isActive: true, ...stamp, + })) + const names = ['Demo Admin', 'Priya Sharma', 'Arjun Rao', 'Meera Shah', 'Kabir Das', 'Nisha Patel', 'Ravi Kumar', 'Asha Iyer'] + const users: s.User[] = names.map((name, i) => ({ + id: demoId(100 + i), clerkId: `demo_${i}`, name, email: `resident${i}@example.com`, phone: null, + role: i === 0 ? 'ADMIN' : i === 7 ? 'STAFF' : 'RESIDENT', status: i === 5 || i === 6 ? 'PENDING' : 'APPROVED', isActive: true, ...stamp, + })) + const guards: s.Guard[] = ['Ramesh Singh', 'Suresh Kumar', 'Anita Devi'].map((name, i) => ({ + id: demoId(200 + i), name, userId: null, phone: null, employeeCode: `G-00${i + 1}`, isActive: true, ...stamp, + })) + const duty: s.GuardDutySession[] = Array.from({ length: 9 }, (_, i) => ({ + id: demoId(220 + i), guardId: guards[i % 3].id, guardName: guards[i % 3].name, + clockInAt: at(-Math.floor(i / 3), -4), clockOutAt: i < 2 ? null : at(-Math.floor(i / 3), -1), + clockInLat: null, clockInLng: null, clockOutLat: null, clockOutLng: null, createdAt: at(-Math.floor(i / 3), -4), + })) + const devices: s.GuardDevice[] = guards.map((g, i) => ({ + id: demoId(240 + i), guardId: g.id, deviceId: `demo-gate-${i}`, model: 'Demo gate phone', boundAt: at(-10), lastActiveAt: at(0, -1), revokedAt: null, + })) + const visitors: s.VisitorEntry[] = Array.from({ length: 24 }, (_, i) => ({ + id: demoId(300 + i), clientId: null, apartmentId: apartments[i % 12].id, preApprovalId: null, + visitorName: ['Aarav Mehta', 'Grocery delivery', 'Diya Kapoor', 'Lift technician'][i % 4], visitorPhone: null, + type: (['GUEST', 'DELIVERY', 'GUEST', 'SERVICE'] as const)[i % 4], + status: i === 0 ? 'PENDING' : i === 1 ? 'APPROVED' : i === 2 ? 'ENTERED' : 'EXITED', + purpose: ['Family visit', 'Weekly groceries', 'Evening visit', 'Scheduled service'][i % 4], + vehicleNumber: i % 2 ? null : `DEMO${1000 + i}`, photoUrl: null, approvedBy: i ? DEMO_ADMIN : null, deniedReason: null, + checkInBy: i > 1 ? guards[i % 3].id : null, checkOutBy: i > 2 ? guards[i % 3].id : null, + checkInAt: i > 1 ? at(-Math.floor(i / 3), -2) : null, checkOutAt: i > 2 ? at(-Math.floor(i / 3), -1) : null, + createdAt: at(-Math.floor(i / 3), -3), updatedAt: at(-Math.floor(i / 3), -1), + })) + const preApprovals: s.VisitorPreApproval[] = ['Weekend guest', 'Morning newspaper', 'Appliance service'].map((visitorName, i) => ({ + id: demoId(350 + i), apartmentId: apartments[i].id, createdBy: users[i + 1].id, visitorName, visitorPhone: null, + approvalType: i === 1 ? 'ALWAYS' : 'ONE_TIME', code: `DEMO0${i + 1}`, validFrom: at(-1), validUntil: at(7), maxUses: i === 1 ? null : 1, useCount: 0, isActive: true, createdAt: at(-1), + })) + const notices: s.Notice[] = [ + ['Water tank cleaning', 'Water supply will pause tomorrow from 10 AM to noon. Please store enough water beforehand.', 'MAINTENANCE', 'HIGH'], + ['Community potluck this weekend', 'Meet your neighbours in the clubhouse at 6 PM. Bring a favourite dish and join the games.', 'EVENT', 'NORMAL'], + ['Monthly maintenance bills are ready', 'You can view your maintenance bill and payment history in the app.', 'BILLING', 'NORMAL'], + ['Gate entry reminder', 'Please pre-approve your guests to help the gate team welcome them quickly.', 'SECURITY', 'NORMAL'], + ].map(([title, body, category, priority], i) => s.noticeSchema.parse({ + id: demoId(400 + i), title, body, category, priority, attachmentUrl: null, attachmentName: null, + publishedBy: DEMO_ADMIN, publishedAt: at(-i), expiresAt: at(14), readCount: 3, read: true, ...stamp, + })) + const tickets: s.Ticket[] = ['Kitchen tap leaking', 'Lobby light flickering', 'Garden bench repair', 'Staircase cleaning'].map((title, i) => ({ + id: demoId(450 + i), apartmentId: apartments[i].id, raisedBy: users[i + 1].id, title, + description: `${title}. Please arrange a visit from the maintenance team.`, category: (['PLUMBING', 'ELECTRICAL', 'CARPENTRY', 'HOUSEKEEPING'] as const)[i], + priority: i === 0 ? 'HIGH' : 'NORMAL', status: (['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'] as const)[i], + assignedTo: i ? users[7].id : null, resolutionNote: i > 1 ? 'Work completed and checked with the resident.' : null, + resolvedAt: i > 1 ? at(-1) : null, createdAt: at(-5), updatedAt: at(-1), + })) + const houseHelp: HouseHelpRow[] = ['Lakshmi Devi', 'Sunita Rao', 'Mohan Kumar'].map((name, i) => ({ + id: demoId(500 + i), name, type: (['MAID', 'COOK', 'DRIVER'] as const)[i], phone: null, photoUrl: null, + idProofType: null, idProofNumber: null, idProofUrl: null, isActive: true, registeredBy: DEMO_ADMIN, + ratingAvg: 4.5, reviewCount: 2, trustScore: 75, idVerified: i !== 2, backgroundCheck: i === 2 ? 'PENDING' : 'CLEARED', + incidentCount: 0, verificationLevel: i === 2 ? 'UNVERIFIED' : 'VERIFIED', ...stamp, + })) + const reviews: s.HouseHelpReview[] = houseHelp.flatMap((h, i) => [4, 5].map((rating, j) => ({ + id: demoId(520 + i * 2 + j), houseHelpId: h.id, rating, comment: j ? 'Reliable and punctual.' : 'Helpful and thorough.', createdAt: at(-j - 1), + }))) + const assignments: s.HouseHelpAssignment[] = houseHelp.map((h, i) => ({ id: demoId(540 + i), houseHelpId: h.id, apartmentId: apartments[i].id, assignedBy: DEMO_ADMIN, createdAt: at(-30) })) + const attendance: (s.HouseHelpAttendanceRow & { id: string })[] = Array.from({ length: 21 }, (_, i) => ({ + id: demoId(550 + i), houseHelpId: houseHelp[i % 3].id, helpName: houseHelp[i % 3].name, type: houseHelp[i % 3].type, + apartment: `${apartments[i % 3].tower}-${apartments[i % 3].apartmentNo}`, checkInAt: at(-Math.floor(i / 3), -3), checkOutAt: i === 0 ? null : at(-Math.floor(i / 3), -1), + })) + const vehicles: s.Vehicle[] = apartments.slice(0, 6).map((a, i) => ({ + id: demoId(600 + i), apartmentId: a.id, registeredBy: DEMO_ADMIN, registrationNumber: `DEMO${2000 + i}`, + type: i % 2 ? 'SCOOTER' : 'CAR', make: i % 2 ? 'City scooter' : 'Family car', color: i % 2 ? 'Blue' : 'White', isActive: true, ...stamp, + })) + const parking: ParkingSlotRow[] = Array.from({ length: 10 }, (_, i) => ({ + id: demoId(650 + i), slotNumber: i > 6 ? `V-${i - 6}` : `P-${i + 1}`, type: i > 6 ? 'OPEN' : 'COVERED', + apartmentId: i < 6 ? apartments[i].id : null, apartment: i < 6 ? `${apartments[i].tower}-${apartments[i].apartmentNo}` : null, + isTemporary: false, assignedUntil: null, assignedBy: i < 6 ? DEMO_ADMIN : null, assignedAt: i < 6 ? at(-30) : null, + isVisitor: i > 6, occupiedByEntryId: i === 7 ? visitors[2].id : null, occupiedAt: i === 7 ? visitors[2].checkInAt : null, + notes: null, isActive: true, ...stamp, + })) + const accounts: s.Account[] = s.DEFAULT_CHART_OF_ACCOUNTS.map((a, i, all) => ({ + id: demoId(700 + i), code: a.code, name: a.name, type: a.type, parentId: a.parentCode ? demoId(700 + all.findIndex(p => p.code === a.parentCode)) : null, + isGroup: a.isGroup ?? false, isMutual: a.isMutual ?? null, isActive: true, createdAt: at(-90), + })) + const bills: s.MaintenanceBill[] = [] + const payments: s.Payment[] = [] + for (let month = 0; month < 3; month++) { + const issued = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - month, 1)).toISOString() + const period = issued.slice(0, 7) + apartments.forEach((a, i) => { + const id = demoId(800 + month * 12 + i) + const paid = (month === 0 && i % 3 === 0) || (month === 1 && i === 0) ? 0 : month === 0 && i % 3 === 1 ? 200000 : 450000 + bills.push({ + id, apartmentId: a.id, apartment: `${a.tower}-${a.apartmentNo}`, type: 'MONTHLY', title: `Maintenance ${period}`, + periodMonth: period, subtotal: 450000, taxAmount: 0, totalAmount: 450000, paidAmount: paid, status: s.billStatusFor(450000, paid), + dueDate: s.dueDateForPeriod(period, 10), issuedAt: issued, createdBy: DEMO_ADMIN, createdAt: issued, updatedAt: issued, + lineItems: [{ id: demoId(900 + month * 12 + i), billId: id, description: 'Monthly maintenance', amount: 450000, taxRatePct: 0, taxAmount: 0, createdAt: issued }], + }) + if (paid) payments.push({ id: demoId(1000 + month * 12 + i), billId: id, apartmentId: a.id, amount: paid, + method: i % 2 ? 'UPI' : 'BANK_TRANSFER', reference: `DEMO-PAY-${month}-${i}`, notes: null, paidAt: issued, + recordedBy: DEMO_ADMIN, createdAt: issued }) + }) + } + const vendors: s.Vendor[] = ['Green Garden Services', 'Bright Lift Care', 'Community Security'].map((name, i) => ({ + id: demoId(1100 + i), name, category: ['Gardening', 'Repairs', 'Security'][i], pan: null, gstin: null, contact: null, bankAccount: null, isActive: true, createdAt: at(-40), + })) + const expenses: (s.Expense & { tdsSection?: s.TdsSection })[] = vendors.map((v, i) => ({ + id: demoId(1150 + i), vendorId: v.id, vendor: v.name, accountId: accounts.find(a => a.code === ['5000', '5040', '5010'][i])!.id, + account: ['Housekeeping', 'Repairs & Maintenance', 'Security'][i], amount: [800000, 1200000, 1800000][i], taxAmount: 0, + status: i === 1 ? 'PAYABLE' : 'PAID', description: ['Garden upkeep', 'Lift maintenance', 'Gate staffing'][i], billRef: `DEMO-INV-${i + 1}`, + method: i === 1 ? null : 'BANK_TRANSFER', paidAt: i === 1 ? null : at(-3), attachmentUrl: null, recordedBy: DEMO_ADMIN, + createdAt: at(-5), tdsAmount: [16000, 24000, 36000][i], tdsSection: 'SEC_194C', + })) + return { + society: { id: demoId(1200), name: 'Green Valley Demo Society', address: '12 Sample Garden Road', city: 'Bengaluru', state: 'Karnataka', pincode: '560001', gstin: null, ...stamp } satisfies s.SocietyConfig, + billConfig: { id: demoId(1201), dueDayOfMonth: 10, lineItems: [{ description: 'Monthly maintenance', amount: 450000, taxRatePct: 0 }], interestEnabled: true, interestRatePct: 18, gracePeriodDays: 15, updatedBy: DEMO_ADMIN, updatedAt: at() } satisfies s.BillConfig, + apartments, users, guards, duty, devices, visitors, preApprovals, notices, tickets, houseHelp, reviews, assignments, attendance, vehicles, parking, accounts, bills, payments, vendors, expenses, + } +} + +export type DemoData = ReturnType From 568e1be074d0d47fdb02d3b306a70233b72e4864 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:25:33 +0530 Subject: [PATCH 02/14] Share spreadsheet export writer with browser clients --- apps/api/src/lib/xlsx.ts | 169 +---------------------------------- packages/shared/src/index.ts | 1 + packages/shared/src/xlsx.ts | 168 ++++++++++++++++++++++++++++++++++ 3 files changed, 170 insertions(+), 168 deletions(-) create mode 100644 packages/shared/src/xlsx.ts diff --git a/apps/api/src/lib/xlsx.ts b/apps/api/src/lib/xlsx.ts index 50c4bbf..abc8e32 100644 --- a/apps/api/src/lib/xlsx.ts +++ b/apps/api/src/lib/xlsx.ts @@ -1,168 +1 @@ -// Dependency-free, Cloudflare-Workers-safe .xlsx writer (#99). Real OOXML -// SpreadsheetML zipped with STORED (uncompressed) entries, so no zip/deflate -// library is needed — just a CRC32. Not a general xlsx lib: inline strings, -// numbers, one style-free sheet per tab. Good enough for report exports. - -export type Cell = string | number | null | undefined -export type Sheet = { name: string; rows: Cell[][] } - -const enc = new TextEncoder() - -// ----- CRC32 (IEEE 802.3, poly 0xEDB88320) ----- -const CRC_TABLE = (() => { - const t = new Uint32Array(256) - for (let n = 0; n < 256; n++) { - let c = n - for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 - t[n] = c >>> 0 - } - return t -})() - -function crc32(bytes: Uint8Array): number { - let c = 0xffffffff - for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8) - return (c ^ 0xffffffff) >>> 0 -} - -function escapeXml(s: string): string { - return s.replace(/[<>&'"]/g, (ch) => ({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' })[ch]!) -} - -// 0-based column index -> spreadsheet letter (0 -> A, 26 -> AA). -function colLetter(i: number): string { - let s = '' - let n = i - do { - s = String.fromCharCode(65 + (n % 26)) + s - n = Math.floor(n / 26) - 1 - } while (n >= 0) - return s -} - -function sheetXml(rows: Cell[][]): string { - const body = rows - .map((row, r) => { - const cells = row - .map((val, c) => { - const ref = `${colLetter(c)}${r + 1}` - if (val === null || val === undefined || val === '') return `` - if (typeof val === 'number' && Number.isFinite(val)) return `${val}` - return `${escapeXml(String(val))}` - }) - .join('') - return `${cells}` - }) - .join('') - return `\n${body}` -} - -function contentTypesXml(n: number): string { - const overrides = Array.from( - { length: n }, - (_, i) => - ``, - ).join('') - return `\n${overrides}` -} - -function workbookXml(sheets: Sheet[]): string { - const els = sheets - .map((s, i) => ``) - .join('') - return `\n${els}` -} - -function workbookRelsXml(n: number): string { - const rels = Array.from( - { length: n }, - (_, i) => - ``, - ).join('') - return `\n${rels}` -} - -const ROOT_RELS = `\n` - -// ----- Minimal STORED zip ----- -type ZipFile = { name: string; data: Uint8Array } - -function u16(n: number): number[] { - return [n & 0xff, (n >>> 8) & 0xff] -} -function u32(n: number): number[] { - return [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, (n >>> 24) & 0xff] -} - -function zipStored(files: ZipFile[]): Uint8Array { - const chunks: number[] = [] - const central: number[] = [] - let offset = 0 - for (const f of files) { - const nameBytes = enc.encode(f.name) - const crc = crc32(f.data) - const size = f.data.length - // Local file header - const local = [ - ...u32(0x04034b50), - ...u16(20), - ...u16(0), - ...u16(0), // method 0 = stored - ...u16(0), - ...u16(0), // mod time/date - ...u32(crc), - ...u32(size), - ...u32(size), - ...u16(nameBytes.length), - ...u16(0), - ] - chunks.push(...local, ...nameBytes, ...f.data) - // Central directory record - central.push( - ...u32(0x02014b50), - ...u16(20), - ...u16(20), - ...u16(0), - ...u16(0), - ...u16(0), - ...u16(0), - ...u32(crc), - ...u32(size), - ...u32(size), - ...u16(nameBytes.length), - ...u16(0), - ...u16(0), - ...u16(0), - ...u16(0), - ...u32(0), - ...u32(offset), - ...Array.from(nameBytes), - ) - offset += local.length + nameBytes.length + size - } - const centralOffset = offset - const eocd = [ - ...u32(0x06054b50), - ...u16(0), - ...u16(0), - ...u16(files.length), - ...u16(files.length), - ...u32(central.length), - ...u32(centralOffset), - ...u16(0), - ] - return Uint8Array.from([...chunks, ...central, ...eocd]) -} - -// Build a real .xlsx workbook from one or more named sheets of cell rows. -export function buildXlsx(sheets: Sheet[]): Uint8Array { - const tabs = sheets.length ? sheets : [{ name: 'Sheet1', rows: [] }] - const files: ZipFile[] = [ - { name: '[Content_Types].xml', data: enc.encode(contentTypesXml(tabs.length)) }, - { name: '_rels/.rels', data: enc.encode(ROOT_RELS) }, - { name: 'xl/workbook.xml', data: enc.encode(workbookXml(tabs)) }, - { name: 'xl/_rels/workbook.xml.rels', data: enc.encode(workbookRelsXml(tabs.length)) }, - ...tabs.map((s, i) => ({ name: `xl/worksheets/sheet${i + 1}.xml`, data: enc.encode(sheetXml(s.rows)) })), - ] - return zipStored(files) -} +export { buildXlsx, type Cell, type Sheet } from '@opensociety/shared' diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index b63dfec..60862c3 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -28,3 +28,4 @@ export * from './expense' export * from './statements' export * from './export' export * from './i18n' +export * from './xlsx' diff --git a/packages/shared/src/xlsx.ts b/packages/shared/src/xlsx.ts new file mode 100644 index 0000000..50c4bbf --- /dev/null +++ b/packages/shared/src/xlsx.ts @@ -0,0 +1,168 @@ +// Dependency-free, Cloudflare-Workers-safe .xlsx writer (#99). Real OOXML +// SpreadsheetML zipped with STORED (uncompressed) entries, so no zip/deflate +// library is needed — just a CRC32. Not a general xlsx lib: inline strings, +// numbers, one style-free sheet per tab. Good enough for report exports. + +export type Cell = string | number | null | undefined +export type Sheet = { name: string; rows: Cell[][] } + +const enc = new TextEncoder() + +// ----- CRC32 (IEEE 802.3, poly 0xEDB88320) ----- +const CRC_TABLE = (() => { + const t = new Uint32Array(256) + for (let n = 0; n < 256; n++) { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + t[n] = c >>> 0 + } + return t +})() + +function crc32(bytes: Uint8Array): number { + let c = 0xffffffff + for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 +} + +function escapeXml(s: string): string { + return s.replace(/[<>&'"]/g, (ch) => ({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' })[ch]!) +} + +// 0-based column index -> spreadsheet letter (0 -> A, 26 -> AA). +function colLetter(i: number): string { + let s = '' + let n = i + do { + s = String.fromCharCode(65 + (n % 26)) + s + n = Math.floor(n / 26) - 1 + } while (n >= 0) + return s +} + +function sheetXml(rows: Cell[][]): string { + const body = rows + .map((row, r) => { + const cells = row + .map((val, c) => { + const ref = `${colLetter(c)}${r + 1}` + if (val === null || val === undefined || val === '') return `` + if (typeof val === 'number' && Number.isFinite(val)) return `${val}` + return `${escapeXml(String(val))}` + }) + .join('') + return `${cells}` + }) + .join('') + return `\n${body}` +} + +function contentTypesXml(n: number): string { + const overrides = Array.from( + { length: n }, + (_, i) => + ``, + ).join('') + return `\n${overrides}` +} + +function workbookXml(sheets: Sheet[]): string { + const els = sheets + .map((s, i) => ``) + .join('') + return `\n${els}` +} + +function workbookRelsXml(n: number): string { + const rels = Array.from( + { length: n }, + (_, i) => + ``, + ).join('') + return `\n${rels}` +} + +const ROOT_RELS = `\n` + +// ----- Minimal STORED zip ----- +type ZipFile = { name: string; data: Uint8Array } + +function u16(n: number): number[] { + return [n & 0xff, (n >>> 8) & 0xff] +} +function u32(n: number): number[] { + return [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, (n >>> 24) & 0xff] +} + +function zipStored(files: ZipFile[]): Uint8Array { + const chunks: number[] = [] + const central: number[] = [] + let offset = 0 + for (const f of files) { + const nameBytes = enc.encode(f.name) + const crc = crc32(f.data) + const size = f.data.length + // Local file header + const local = [ + ...u32(0x04034b50), + ...u16(20), + ...u16(0), + ...u16(0), // method 0 = stored + ...u16(0), + ...u16(0), // mod time/date + ...u32(crc), + ...u32(size), + ...u32(size), + ...u16(nameBytes.length), + ...u16(0), + ] + chunks.push(...local, ...nameBytes, ...f.data) + // Central directory record + central.push( + ...u32(0x02014b50), + ...u16(20), + ...u16(20), + ...u16(0), + ...u16(0), + ...u16(0), + ...u16(0), + ...u32(crc), + ...u32(size), + ...u32(size), + ...u16(nameBytes.length), + ...u16(0), + ...u16(0), + ...u16(0), + ...u16(0), + ...u32(0), + ...u32(offset), + ...Array.from(nameBytes), + ) + offset += local.length + nameBytes.length + size + } + const centralOffset = offset + const eocd = [ + ...u32(0x06054b50), + ...u16(0), + ...u16(0), + ...u16(files.length), + ...u16(files.length), + ...u32(central.length), + ...u32(centralOffset), + ...u16(0), + ] + return Uint8Array.from([...chunks, ...central, ...eocd]) +} + +// Build a real .xlsx workbook from one or more named sheets of cell rows. +export function buildXlsx(sheets: Sheet[]): Uint8Array { + const tabs = sheets.length ? sheets : [{ name: 'Sheet1', rows: [] }] + const files: ZipFile[] = [ + { name: '[Content_Types].xml', data: enc.encode(contentTypesXml(tabs.length)) }, + { name: '_rels/.rels', data: enc.encode(ROOT_RELS) }, + { name: 'xl/workbook.xml', data: enc.encode(workbookXml(tabs)) }, + { name: 'xl/_rels/workbook.xml.rels', data: enc.encode(workbookRelsXml(tabs.length)) }, + ...tabs.map((s, i) => ({ name: `xl/worksheets/sheet${i + 1}.xml`, data: enc.encode(sheetXml(s.rows)) })), + ] + return zipStored(files) +} From ab73895335876db9baa2b5ef60f674f216c8b6d4 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:34:01 +0530 Subject: [PATCH 03/14] Add interactive demo billing and reports --- apps/web/src/lib/demo/finance.test.ts | 57 ++++++++++ apps/web/src/lib/demo/finance.ts | 146 ++++++++++++++++++++++++++ apps/web/src/lib/demo/helpers.ts | 23 ++++ 3 files changed, 226 insertions(+) create mode 100644 apps/web/src/lib/demo/finance.test.ts create mode 100644 apps/web/src/lib/demo/finance.ts create mode 100644 apps/web/src/lib/demo/helpers.ts diff --git a/apps/web/src/lib/demo/finance.test.ts b/apps/web/src/lib/demo/finance.test.ts new file mode 100644 index 0000000..4a469a7 --- /dev/null +++ b/apps/web/src/lib/demo/finance.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { createDemoData } from './data' +import { demoFinance } from './finance' + +describe('demo finance', () => { + it('reconciles dues, statements, cash flow and the ledger after a payment', () => { + const f = demoFinance(createDemoData()) + const bill = f.listBills().find(b => b.status === 'ISSUED')! + const before = f.getFinanceReport() + f.recordPayment({ billId: bill.id, amount: 100000, method: 'UPI' }) + expect(f.getBill(bill.id).status).toBe('PARTIALLY_PAID') + expect(f.getFinanceReport().totalCollected).toBe(before.totalCollected + 100000) + expect(f.getFinanceReport().cashBankBalance).toBe(before.cashBankBalance + 100000) + const dues = f.listDues().find(a => a.apartmentId === bill.apartmentId)! + expect(f.getApartmentStatement(bill.apartmentId).closing).toBe(dues.outstanding) + expect(f.getTrialBalance().balanced).toBe(true) + expect(f.getBalanceSheet().balanced).toBe(true) + expect(f.getReceiptsPayments().closingBalance).toBe(f.getFinanceReport().cashBankBalance) + expect(() => f.recordPayment({ billId: bill.id, amount: bill.totalAmount, method: 'UPI' })).toThrow() + expect(() => f.cancelBill(bill.id)).toThrow() + }) + + it('generates monthly bills once and excludes cancellations from reports', () => { + const d = createDemoData(), f = demoFinance(d) + const input = { periodMonth: '2031-02', title: 'February maintenance', lineItems: [{ description: 'Maintenance', amount: 10000, taxRatePct: 18 }] } + expect(f.generateBills(input)).toEqual({ created: 12, skipped: 0 }) + expect(f.generateBills(input)).toEqual({ created: 0, skipped: 12 }) + const bill = f.listBills({ period: '2031-02' })[0], before = f.getFinanceReport() + expect(bill.totalAmount).toBe(11800) + f.cancelBill(bill.id) + expect(f.getFinanceReport().totalBilled).toBe(before.totalBilled - 11800) + expect(f.getTrialBalance().balanced).toBe(true) + expect(() => f.recordPayment({ billId: bill.id, amount: 100, method: 'CASH' })).toThrow() + }) + + it('honors date ranges and carries forward the opening balance', () => { + const d = createDemoData(new Date('2030-03-25T12:00:00Z')), f = demoFinance(d) + const id = d.apartments[0].id + const previous = f.getApartmentStatement(id, undefined, '2030-02-28') + const current = f.getApartmentStatement(id, '2030-03-01') + expect(current.opening).toBe(previous.closing) + expect(current.entries.every(e => e.date >= '2030-03-01')).toBe(true) + expect(f.getTrialBalance('2029-12-31').rows).toHaveLength(0) + expect(f.getAging('2030-03-25').total).toBe(f.listDues().reduce((n, a) => n + a.outstanding, 0)) + }) + + it('calculates overdue interest and prevents repeated charges in the same month', () => { + const f = demoFinance(createDemoData(new Date('2030-03-25T12:00:00Z'))) + const preview = f.getInterestPreview('2030-03-25') + expect(preview.rows.length).toBeGreaterThan(0) + expect(f.applyInterest('2030-03-25').created).toBe(preview.rows.length) + expect(f.applyInterest('2030-03-25').created).toBe(0) + expect(f.getTrialBalance().balanced).toBe(true) + f.updateBillConfig({ dueDayOfMonth: 10, lineItems: [], interestEnabled: false, interestRatePct: 18, gracePeriodDays: 15 }) + expect(f.getInterestPreview().rows).toEqual([]) + }) +}) diff --git a/apps/web/src/lib/demo/finance.ts b/apps/web/src/lib/demo/finance.ts new file mode 100644 index 0000000..00f030a --- /dev/null +++ b/apps/web/src/lib/demo/finance.ts @@ -0,0 +1,146 @@ +import * as s from '@opensociety/shared' +import { DEMO_ADMIN, type DemoData } from './data' +import { find, inRange, newRecord, nowIso, type DemoMethods } from './helpers' + +export function demoFinance(d: DemoData) { + const apartment = (id: string) => { const a = find(d.apartments, id); return `${a.tower}-${a.apartmentNo}` } + const paid = (id: string) => d.payments.filter(p => p.billId === id).reduce((sum, p) => sum + p.amount, 0) + const bills = () => d.bills.map(b => ({ ...b, paidAmount: paid(b.id), apartment: apartment(b.apartmentId) })) + const activeBills = () => bills().filter(b => b.status !== 'CANCELLED') + const account = (code: string) => d.accounts.find(a => a.code === code)!.id + const postingAccounts = { bank: account('1001'), cash: account('1010'), memberDuesReceivable: account('1100'), memberAdvances: account('2000'), gstOutputPayable: account('2200'), tdsPayable: account('2300'), vendorPayables: account('2100') } + const createBill = (body: s.CreateBill, periodMonth: string | null = null) => { + const input = s.createBillSchema.parse(body) + apartment(input.apartmentId) + const totals = s.computeBill(input.lineItems) + const record = newRecord() + const bill: s.MaintenanceBill = { ...record, apartmentId: input.apartmentId, title: input.title, periodMonth, + type: periodMonth ? 'MONTHLY' : 'ONE_TIME', subtotal: totals.subtotal, taxAmount: totals.taxAmount, totalAmount: totals.total, + status: 'ISSUED', dueDate: input.dueDate ?? null, issuedAt: nowIso(), createdBy: DEMO_ADMIN, + lineItems: totals.lines.map(l => ({ ...newRecord(), ...l, billId: record.id })), paidAmount: 0, apartment: apartment(input.apartmentId) } + d.bills.unshift(bill) + return bill + } + const journal = (): s.JournalDraft[] => [ + ...activeBills().map(b => s.postBillIssued({ billId: b.id, apartmentId: b.apartmentId, entryDate: b.issuedAt.slice(0, 10), period: b.periodMonth ?? b.issuedAt.slice(0, 7), + lines: (b.lineItems ?? []).map(l => ({ accountId: l.accountId ?? account('4000'), net: l.amount, tax: l.taxAmount })), accounts: postingAccounts })), + ...d.payments.map(p => s.postPaymentReceived({ paymentId: p.id, apartmentId: p.apartmentId, amount: p.amount, applied: p.amount, leftoverCredit: 0, method: p.method, + entryDate: p.paidAt.slice(0, 10), period: p.paidAt.slice(0, 7), accounts: postingAccounts })), + ...d.expenses.flatMap(e => { + const entry = s.postExpense({ expenseId: e.id, status: 'PAYABLE', expenseAccountId: e.accountId, amount: e.amount, taxAmount: e.taxAmount, + tds: e.tdsAmount ?? 0, vendorId: e.vendorId, entryDate: e.createdAt.slice(0, 10), period: e.createdAt.slice(0, 7), accounts: postingAccounts }) + return e.status === 'PAYABLE' ? [entry] : [entry, s.postExpenseSettlement({ expenseId: e.id, vendorId: e.vendorId, method: e.method ?? 'BANK_TRANSFER', + net: e.amount + e.taxAmount - (e.tdsAmount ?? 0), entryDate: (e.paidAt ?? e.createdAt).slice(0, 10), period: (e.paidAt ?? e.createdAt).slice(0, 7), accounts: postingAccounts })] + }), + ] + const balances = (from?: string, to?: string): s.AccountBalance[] => { + const entries = journal().filter(j => inRange(j.entryDate, from, to)) + return d.accounts.map(a => ({ ...a, debit: entries.flatMap(j => j.lines).filter(l => l.accountId === a.id).reduce((n, l) => n + l.debit, 0), + credit: entries.flatMap(j => j.lines).filter(l => l.accountId === a.id).reduce((n, l) => n + l.credit, 0) })) + } + const finance = { + listBills: (params?: { apartmentId?: string; status?: string; period?: string }) => bills().filter(b => (!params?.apartmentId || b.apartmentId === params.apartmentId) && (!params?.status || b.status === params.status) && (!params?.period || b.periodMonth === params.period)), + getBill: id => find(bills(), id), + createBill, + generateBills: body => { + const input = s.generateBillsSchema.parse(body) + let created = 0, skipped = 0 + for (const a of d.apartments.filter(a => a.isActive)) { + if (d.bills.some(b => b.apartmentId === a.id && b.periodMonth === input.periodMonth && b.type === 'MONTHLY')) { skipped++; continue } + createBill({ ...input, apartmentId: a.id }, input.periodMonth) + created++ + } + return { created, skipped } + }, + cancelBill: id => { + const bill = find(d.bills, id) + if (paid(id)) throw new Error('A bill with payments cannot be cancelled.') + bill.status = 'CANCELLED' + return bill + }, + recordPayment: body => { + const input = s.recordPaymentSchema.parse(body) + const bill = find(d.bills, input.billId) + if (bill.status === 'CANCELLED' || input.amount > bill.totalAmount - paid(bill.id)) throw new Error('Payment must not exceed the outstanding amount on an active bill.') + const payment: s.Payment = { ...newRecord(), ...input, apartmentId: bill.apartmentId, reference: input.reference ?? null, notes: input.notes ?? null, paidAt: input.paidAt ?? nowIso(), recordedBy: DEMO_ADMIN } + d.payments.unshift(payment) + bill.status = s.billStatusFor(bill.totalAmount, paid(bill.id)) + bill.updatedAt = nowIso() + return payment + }, + listPayments: params => d.payments.filter(p => (!params?.apartmentId || p.apartmentId === params.apartmentId) && (!params?.billId || p.billId === params.billId)), + listDues: () => d.apartments.map(a => { + const rows = activeBills().filter(b => b.apartmentId === a.id) + const billed = rows.reduce((n, b) => n + b.totalAmount, 0), paid = rows.reduce((n, b) => n + b.paidAmount, 0) + return { apartmentId: a.id, apartment: apartment(a.id), billed, paid, outstanding: billed - paid } + }), + getBillConfig: () => d.billConfig, + updateBillConfig: body => Object.assign(d.billConfig, s.updateBillConfigSchema.parse(body), { updatedAt: nowIso() }), + listAccounts: () => d.accounts, + initLedger: () => ({ inserted: 0, total: d.accounts.length }), + getTrialBalance: (toDate?: string) => ({ ...s.trialBalance(balances(undefined, toDate)), toDate: toDate ?? null }), + getIncomeExpenditure: (fromDate?: string, toDate?: string) => ({ ...s.incomeExpenditure(balances(fromDate, toDate)), fromDate: fromDate ?? null, toDate: toDate ?? null }), + getBalanceSheet: (toDate?: string) => ({ ...s.balanceSheet(balances(undefined, toDate), s.incomeExpenditure(balances(undefined, toDate)).surplus), toDate: toDate ?? null }), + getReceiptsPayments: (fromDate?: string, toDate?: string) => { + const entries = journal() + const opening = entries.filter(j => fromDate && j.entryDate < fromDate).flatMap(j => j.lines).filter(l => [postingAccounts.bank, postingAccounts.cash].includes(l.accountId)).reduce((n, l) => n + l.debit - l.credit, 0) + const lines = entries.filter(j => inRange(j.entryDate, fromDate, toDate)).flatMap((j, i) => j.lines.map(l => { + const a = find(d.accounts, l.accountId) + return { entryId: String(i), accountCode: a.code, accountName: a.name, debit: l.debit, credit: l.credit, isCashBank: ['1001', '1010'].includes(a.code) } + })) + return { ...s.receiptsAndPayments(lines, opening), fromDate: fromDate ?? null, toDate: toDate ?? null } + }, + getAging: (asOf = nowIso().slice(0, 10)) => { + const byApartment = d.apartments.map(a => { + const rows = activeBills().filter(b => b.apartmentId === a.id && b.issuedAt.slice(0, 10) <= asOf.slice(0, 10)) + const buckets = s.bucketAging(rows.map(b => ({ outstanding: b.totalAmount - d.payments.filter(p => p.billId === b.id && p.paidAt.slice(0, 10) <= asOf.slice(0, 10)).reduce((n, p) => n + p.amount, 0), dueDateMs: Date.parse(b.dueDate ?? b.issuedAt) })), Date.parse(asOf)) + return { apartmentId: a.id, apartment: apartment(a.id), buckets, outstanding: Object.values(buckets).reduce((n, v) => n + v, 0) } + }) + const buckets = { '0-30': 0, '31-60': 0, '61-90': 0, '90+': 0 } + for (const a of byApartment) for (const key of s.AGING_BUCKETS) buckets[key] += a.buckets[key] + return { asOf, byApartment, buckets, total: Object.values(buckets).reduce((n, v) => n + v, 0) } + }, + getApartmentStatement: (apartmentId: string, from?: string, to?: string) => { + const entries: s.StatementEntryInput[] = [ + ...activeBills().filter(b => b.apartmentId === apartmentId).map(b => ({ date: b.issuedAt, type: 'BILL' as const, description: b.title, debit: b.totalAmount, credit: 0, ref: b.id })), + ...d.payments.filter(p => p.apartmentId === apartmentId).map(p => ({ date: p.paidAt, type: 'PAYMENT' as const, description: `Payment (${p.method})`, debit: 0, credit: p.amount, ref: p.id })), + ] + const opening = entries.filter(e => from && e.date.slice(0, 10) < from).reduce((n, e) => n + e.debit - e.credit, 0) + return { ...s.buildStatement(entries.filter(e => inRange(e.date, from, to)), opening), apartmentId, apartment: apartment(apartmentId), from: from ?? null, to: to ?? null } + }, + getFinanceReport: () => { + const rows = activeBills() + const byMonth = [...new Set(rows.map(b => b.periodMonth ?? b.issuedAt.slice(0, 7)))].sort().map(period => { + const monthly = rows.filter(b => (b.periodMonth ?? b.issuedAt.slice(0, 7)) === period) + return { period, billed: monthly.reduce((n, b) => n + b.totalAmount, 0), collected: monthly.reduce((n, b) => n + b.paidAmount, 0) } + }) + const byMethod = [...new Set(d.payments.map(p => p.method))].map(method => ({ method, amount: d.payments.filter(p => p.method === method).reduce((n, p) => n + p.amount, 0) })) + return { byMonth, byMethod, totalBilled: rows.reduce((n, b) => n + b.totalAmount, 0), totalCollected: d.payments.reduce((n, p) => n + p.amount, 0), + cashBankBalance: balances().filter(a => ['1001', '1010'].includes(a.code)).reduce((n, a) => n + a.debit - a.credit, 0) } + }, + getInterestPreview: (asOf = nowIso()) => ({ enabled: d.billConfig.interestEnabled, ratePct: d.billConfig.interestRatePct, graceDays: d.billConfig.gracePeriodDays, asOf, + rows: d.billConfig.interestEnabled ? d.apartments.map(a => ({ apartmentId: a.id, apartment: apartment(a.id), interest: activeBills().filter(b => b.apartmentId === a.id && b.type === 'MONTHLY').reduce((n, b) => n + s.computeInterest(b.totalAmount - b.paidAmount, Date.parse(b.dueDate ?? b.issuedAt), Date.parse(asOf), d.billConfig.interestRatePct, d.billConfig.gracePeriodDays), 0) })).filter(r => r.interest > 0) : [] }), + } satisfies Partial + return { ...finance, + getCollectionAnalytics: () => { + const report = finance.getFinanceReport(), rows = activeBills() + const payers = s.analyzePayers(rows.filter(b => b.dueDate).map(b => ({ dueDateMs: Date.parse(b.dueDate!), total: b.totalAmount, paid: b.paidAmount, + lastPaidAtMs: d.payments.some(p => p.billId === b.id) ? Math.max(...d.payments.filter(p => p.billId === b.id).map(p => Date.parse(p.paidAt))) : null }))) + return { ...report, byMonth: report.byMonth.map(m => ({ ...m, ratePct: s.collectionRatePct(m.billed, m.collected) })), + byTower: [...new Set(d.apartments.map(a => a.tower))].map(tower => { const bs = rows.filter(b => find(d.apartments, b.apartmentId).tower === tower); return { tower, billed: bs.reduce((n, b) => n + b.totalAmount, 0), collected: bs.reduce((n, b) => n + b.paidAmount, 0) } }), + payers, overallRatePct: s.collectionRatePct(report.totalBilled, report.totalCollected), fullyPaidPct: s.collectionRatePct(rows.length, payers.fullyPaid) } + }, + applyInterest: asOf => { + const preview = finance.getInterestPreview(asOf), period = (asOf ?? nowIso()).slice(0, 7) + let created = 0, skipped = 0 + for (const row of preview.rows) { + const title = `${s.INTEREST_BILL_TITLE_PREFIX} ${period}` + if (d.bills.some(b => b.apartmentId === row.apartmentId && b.title === title)) { skipped++; continue } + createBill({ apartmentId: row.apartmentId, title, lineItems: [{ description: title, amount: row.interest, taxRatePct: 0, accountId: account('4100') }] }) + created++ + } + return { created, skipped, period } + }, + journal, + } satisfies Partial & { journal: () => s.JournalDraft[] } +} diff --git a/apps/web/src/lib/demo/helpers.ts b/apps/web/src/lib/demo/helpers.ts new file mode 100644 index 0000000..0ea9010 --- /dev/null +++ b/apps/web/src/lib/demo/helpers.ts @@ -0,0 +1,23 @@ +import type { apiClient } from '../api' + +export type DemoMethods = { + [K in keyof typeof apiClient]: (...args: Parameters<(typeof apiClient)[K]>) => + Awaited> | ReturnType<(typeof apiClient)[K]> +} + +export const nowIso = () => new Date().toISOString() +export const newRecord = () => ({ id: crypto.randomUUID(), createdAt: nowIso(), updatedAt: nowIso() }) +export function find(rows: T[], id: string): T { + const row = rows.find(r => r.id === id) + if (!row) throw new Error('This demo record no longer exists. Reset the demo to start again.') + return row +} +export function inRange(date: string, from?: string, to?: string) { + const day = date.slice(0, 10) + return (!from || day >= from.slice(0, 10)) && (!to || day <= to.slice(0, 10)) +} +export function groupCount(rows: T[], key: (row: T) => string) { + const counts = new Map() + for (const row of rows) counts.set(key(row), (counts.get(key(row)) ?? 0) + 1) + return [...counts].map(([label, count]) => ({ label, count })) +} From 44eb4af32bfe68fd2a72a52442cbe4641b413826 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:37:44 +0530 Subject: [PATCH 04/14] Generate demo downloads in the browser --- apps/web/package.json | 1 + apps/web/src/lib/demo/exports.test.ts | 32 +++++++++++++++++ apps/web/src/lib/demo/exports.ts | 50 +++++++++++++++++++++++++++ pnpm-lock.yaml | 3 ++ 4 files changed, 86 insertions(+) create mode 100644 apps/web/src/lib/demo/exports.test.ts create mode 100644 apps/web/src/lib/demo/exports.ts diff --git a/apps/web/package.json b/apps/web/package.json index 88ae555..aac444e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -29,6 +29,7 @@ "lucide-react": "^0.545.0", "react": "^19.2.0", "react-dom": "^19.2.0", + "pdf-lib": "^1.17.1", "react-qr-code": "^2.2.0", "tailwind-merge": "^3.0.1", "tailwindcss": "^4.1.18", diff --git a/apps/web/src/lib/demo/exports.test.ts b/apps/web/src/lib/demo/exports.test.ts new file mode 100644 index 0000000..121aafd --- /dev/null +++ b/apps/web/src/lib/demo/exports.test.ts @@ -0,0 +1,32 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PDFDocument } from 'pdf-lib' +import { createDemoData } from './data' +import { exportReport, exportTable } from './exports' + +afterEach(() => vi.restoreAllMocks()) + +describe('local demo exports', () => { + it('generates real PDF, Excel, CSV and Tally files without fetching', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Network forbidden')) + const blobs: Blob[] = [] + vi.spyOn(URL, 'createObjectURL').mockImplementation(blob => { blobs.push(blob as Blob); return 'blob:demo' }) + const d = createDemoData() + for (const format of ['pdf', 'xlsx', 'csv']) await exportReport(d, `/reports/trial-balance?format=${format}`) + const pdf = await PDFDocument.load(await blobs[0].arrayBuffer()) + expect(pdf.getPageCount()).toBeGreaterThan(0) + expect(new Uint8Array(await blobs[1].arrayBuffer()).slice(0, 4)).toEqual(new Uint8Array([80, 75, 3, 4])) + expect(await blobs[2].text()).toContain('Member Dues Receivable') + await exportReport(d, '/reports/tally-export') + expect(await blobs[3].text()).toContain(' { + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:demo') + for (const path of ['trial-balance', 'balance-sheet', 'income-expenditure', 'receipts-payments']) { + await expect(exportReport(createDemoData(), `/reports/${path}?format=csv`)).resolves.toBe('blob:demo') + } + await expect(exportReport(createDemoData(), '/webhooks')).rejects.toThrow() + await expect(exportTable({ name: 'Demo', rows: [] }, 'html')).rejects.toThrow() + }) +}) diff --git a/apps/web/src/lib/demo/exports.ts b/apps/web/src/lib/demo/exports.ts new file mode 100644 index 0000000..fad7c05 --- /dev/null +++ b/apps/web/src/lib/demo/exports.ts @@ -0,0 +1,50 @@ +import * as s from '@opensociety/shared' +import { PDFDocument, StandardFonts } from 'pdf-lib' +import type { DemoData } from './data' +import { demoFinance } from './finance' +import { find } from './helpers' + +export async function exportTable(table: s.Table, format: string) { + let blob: Blob + if (format === 'csv') blob = new Blob([s.tableToCsv(table.rows)], { type: 'text/csv;charset=utf-8' }) + else if (format === 'xlsx') blob = new Blob([new Uint8Array(s.buildXlsx([table]))], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) + else if (format === 'pdf') { + const pdf = await PDFDocument.create(), font = await pdf.embedFont(StandardFonts.Helvetica) + let page = pdf.addPage([842, 595]), y = 555 + const draw = (value: string) => { + // The built-in PDF font supports Latin text. Keep user-entered Unicode + // out of its encoder; the CSV and Excel exports preserve it in full. + const line = value.replace(/[^\x20-\x7e]/g, '?') + for (let offset = 0; offset < Math.max(1, line.length); offset += 120) { + if (y < 35) { page = pdf.addPage([842, 595]); y = 555 } + page.drawText(line.slice(offset, offset + 120), { x: 35, y, size: 10, font }); y -= 17 + } + } + draw('OpenSociety demo | Fictional sample data | Amounts in INR') + draw(table.name) + for (const row of table.rows) draw(row.map(cell => cell ?? '').join(' | ')) + blob = new Blob([new Uint8Array(await pdf.save())], { type: 'application/pdf' }) + } else throw new Error('Unsupported demo export format.') + return URL.createObjectURL(blob) +} + +export async function exportReport(d: DemoData, path: string) { + const url = new URL(path, 'https://demo.invalid'), f = demoFinance(d) + const from = url.searchParams.get('fromDate') ?? undefined, to = url.searchParams.get('toDate') ?? undefined + if (url.pathname === '/reports/tally-export') { + const vouchers: s.TallyVoucher[] = f.journal().map(j => ({ date: j.entryDate, type: j.sourceType === 'PAYMENT' ? 'Receipt' : 'Journal', + narration: `DEMO: ${j.narration}`, entries: j.lines.map(l => ({ ledger: find(d.accounts, l.accountId).name, debit: l.debit, credit: l.credit })) })) + const xml = s.buildTallyXml(vouchers, d.accounts.filter(a => !a.isGroup).map(a => ({ name: a.name, parent: s.tallyParentForType(a.type) }))) + return URL.createObjectURL(new Blob([xml], { type: 'application/xml' })) + } + let table: s.Table + switch (url.pathname) { + case '/reports/trial-balance': table = s.trialBalanceTable(f.getTrialBalance(to)); break + case '/reports/income-expenditure': table = s.incomeExpenditureTable(f.getIncomeExpenditure(from, to)); break + case '/reports/balance-sheet': table = s.balanceSheetTable(f.getBalanceSheet(to)); break + case '/reports/receipts-payments': table = s.receiptsPaymentsTable(f.getReceiptsPayments(from, to)); break + case '/bills/dues': table = s.duesTable(f.listDues()); break + default: throw new Error('This report is not available in the demo.') + } + return exportTable(table, url.searchParams.get('format') ?? 'pdf') +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4fc62ba..710900c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -257,6 +257,9 @@ importers: react-dom: specifier: ^19.2.0 version: 19.2.3(react@19.2.3) + pdf-lib: + specifier: ^1.17.1 + version: 1.17.1 react-qr-code: specifier: ^2.2.0 version: 2.2.0(react@19.2.3) From 05ff40fc5dd12dd5dd9ccc288ff7f88d60758ebf Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:41:11 +0530 Subject: [PATCH 05/14] Isolate demo interactions from the live API --- apps/web/src/lib/api.ts | 21 ++- apps/web/src/lib/demo/client.test.ts | 120 +++++++++++++++++ apps/web/src/lib/demo/client.ts | 186 +++++++++++++++++++++++++++ apps/web/src/lib/demo/mode.ts | 7 + 4 files changed, 333 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/lib/demo/client.test.ts create mode 100644 apps/web/src/lib/demo/client.ts create mode 100644 apps/web/src/lib/demo/mode.ts diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 86a8834..662e945 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -1,3 +1,4 @@ +import { isDemoBrowser } from './demo/mode' import type { Apartment, ApproveUser, @@ -234,7 +235,7 @@ async function api(path: string, init?: RequestInit): Promise { const json = (body: unknown) => JSON.stringify(body) -export const apiClient = { +const liveApiClient = { health: () => api<{ status: string }>('/health'), // Society @@ -497,3 +498,21 @@ export const apiClient = { return api(`/guards/duty${qs ? `?${qs}` : ''}`) }, } + +export type ApiClient = typeof liveApiClient + +// Resolve the transport before any credentials, uploads or network requests. +// Unknown demo actions fail inside the sandbox; they never fall back to live. +export const apiClient: ApiClient = new Proxy(liveApiClient, { + get(target, property: keyof ApiClient) { + return (...args: unknown[]) => { + if (isDemoBrowser()) { + return import('./demo/client').then(({ getDemoClient }) => { + const client = getDemoClient() + return Reflect.apply(client[property], client, args) + }) + } + return Reflect.apply(target[property], target, args) + } + }, +}) diff --git a/apps/web/src/lib/demo/client.test.ts b/apps/web/src/lib/demo/client.test.ts new file mode 100644 index 0000000..a12c538 --- /dev/null +++ b/apps/web/src/lib/demo/client.test.ts @@ -0,0 +1,120 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { apiClient, setAuthTokenGetter, type ApiClient } from '../api' +import { createDemoClient, resetDemoClient } from './client' +import { createDemoData } from './data' +import { isDemoPath } from './mode' + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); setAuthTokenGetter(null); resetDemoClient() }) + +describe('demo sandbox', () => { + it('serves every dashboard read without fetching or asking Clerk for credentials', async () => { + vi.stubGlobal('window', { location: { pathname: '/demo/reports' } }) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Live API must not be called')) + const token = vi.fn().mockResolvedValue('real-token'); setAuthTokenGetter(token) + const d = createDemoData() + const reads: [keyof ApiClient, unknown[]][] = [ + ['health', []], ['getSociety', []], ['listApartments', []], ['listUsers', []], ['listGuards', []], + ['listGuardDevices', [d.guards[0].id]], ['listActiveDuty', []], ['listDutySessions', []], + ['listVisitors', []], ['listPreApprovals', []], ['listNotices', []], ['listNoticeReads', [d.notices[0].id]], + ['listTickets', []], ['listHouseHelp', []], ['getHouseHelpReviews', [d.houseHelp[0].id]], + ['listHouseHelpAssignments', [d.houseHelp[0].id]], ['listHouseHelpEntries', []], + ['listVehicles', []], ['listVehicleGateLog', []], ['listParkingSlots', []], ['listParkingDirectory', []], ['listVisitorParking', []], + ['listBills', []], ['getBill', [d.bills[0].id]], ['listDues', []], ['listPayments', []], ['getBillConfig', []], + ['getFinanceReport', []], ['getCollectionAnalytics', []], ['getTrialBalance', []], ['getIncomeExpenditure', []], + ['getBalanceSheet', []], ['getReceiptsPayments', []], ['getAging', []], ['listAccounts', []], + ['listVendors', []], ['listExpenses', []], ['getTdsSummary', []], ['getInterestPreview', []], + ['getApartmentStatement', [d.apartments[0].id]], ['getVisitorTrends', []], ['getHouseHelpAnalytics', []], ['getMaintenanceAnalytics', []], + ] + for (const [method, args] of reads) { + const value = await Reflect.apply(apiClient[method], apiClient, args) + expect(value, method).toBeTruthy() + if (Array.isArray(value)) expect(value.length, method).toBeGreaterThan(0) + } + await apiClient.createNotice({ title: 'Demo notice', body: 'Only in this tab', category: 'GENERAL', priority: 'NORMAL' }) + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:demo') + const file = new File(['sample'], 'sample.txt', { type: 'text/plain' }) + const uploaded = await apiClient.uploadFile(file) + expect(await apiClient.fetchUploadObjectUrl(uploaded.url)).toBe('blob:demo') + await expect(apiClient.fetchUploadObjectUrl('/uploads/real-secret')).rejects.toThrow() + expect(await apiClient.invoiceObjectUrl(d.bills[0].id)).toBe('blob:demo') + expect(await apiClient.visitorTrendsPdfObjectUrl()).toBe('blob:demo') + expect(await apiClient.reportExportObjectUrl('/reports/trial-balance?format=csv')).toBe('blob:demo') + await expect(apiClient.reportExportObjectUrl('/uploads/real-secret')).rejects.toThrow() + expect(token).not.toHaveBeenCalled() + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('keeps visitors and cached results isolated and restores a fresh demo', async () => { + const d = createDemoData(), a = createDemoClient(d), b = createDemoClient(d) + const rows = await a.listApartments() + rows[0].tower = 'Cache mutation' + expect((await a.listApartments())[0].tower).toBe('A') + await a.updateApartment(d.apartments[0].id, { tower: 'Changed' }) + expect((await b.listApartments())[0].tower).toBe('A') + expect(d.apartments[0].tower).toBe('A') + vi.stubGlobal('window', { location: { pathname: '/demo' } }) + await apiClient.updateApartment(d.apartments[0].id, { tower: 'Changed' }) + resetDemoClient() + expect((await apiClient.listApartments())[0].tower).toBe('A') + }) + + it('updates visitor and ticket lifecycles, including linked parking and analytics', async () => { + const d = createDemoData(), c = createDemoClient(d) + const visitor = d.visitors[0] + await c.approveVisitor(visitor.id) + await expect(c.approveVisitor(visitor.id)).rejects.toThrow() + await c.checkInVisitor(visitor.id) + expect((await c.checkOutVisitor(visitor.id)).status).toBe('EXITED') + await c.checkOutVisitor(d.visitors[2].id) + expect((await c.listVisitorParking()).summary.occupied).toBe(0) + const pa = d.preApprovals[0] + await c.redeemPreApproval(pa.code) + await expect(c.redeemPreApproval(pa.code)).rejects.toThrow('exhausted') + const ticket = d.tickets[0], before = await c.getMaintenanceAnalytics() + await c.assignTicket(ticket.id, d.users[7].id) + await c.transitionTicket(ticket.id, 'start') + await c.transitionTicket(ticket.id, 'resolve', 'Replaced the washer') + expect((await c.getMaintenanceAnalytics()).pending).toBe(before.pending - 1) + await expect(c.transitionTicket(ticket.id, 'start')).rejects.toThrow() + }) + + it('supports household, resident and notice actions with filters', async () => { + const d = createDemoData(), c = createDemoClient(d) + await c.approveUser(d.users[5].id, { apartmentId: d.apartments[1].id, relation: 'TENANT', isPrimary: true }) + expect((await c.listUsers('PENDING')).map(u => u.id)).not.toContain(d.users[5].id) + const h = d.houseHelp[2] + await c.updateHouseHelpVerification(h.id, { idVerified: true, backgroundCheck: 'CLEARED' }) + expect((await c.listHouseHelp('DRIVER'))[0].verificationLevel).toBe('VERIFIED') + await c.assignHouseHelp(h.id, d.apartments[1].id) + await c.removeHouseHelpAssignment(h.id, d.apartments[1].id) + expect(await c.listHouseHelpAssignments(h.id)).toHaveLength(1) + await c.createHouseHelpReview(h.id, { rating: 5, comment: 'Good work' }) + expect((await c.getHouseHelpReviews(h.id)).summary.count).toBe(3) + await c.createNotice({ title: 'Picnic', body: 'Meet in the garden', category: 'EVENT', priority: 'NORMAL' }) + expect(await c.listNotices({ q: 'picnic', category: 'EVENT' })).toHaveLength(1) + expect(await c.listNotices({ q: 'picnic', category: 'SECURITY' })).toHaveLength(0) + expect(await c.listDutySessions({ from: '2000-01-01', to: '2000-01-02' })).toHaveLength(0) + }) + + it('settles expenses once and updates balanced statements', async () => { + const c = createDemoClient(), expense = (await c.listExpenses({ status: 'PAYABLE' }))[0] + const before = await c.getFinanceReport() + await c.payExpense(expense.id) + expect((await c.getFinanceReport()).cashBankBalance).toBe(before.cashBankBalance - expense.amount - expense.taxAmount + (expense.tdsAmount ?? 0)) + expect((await c.getTrialBalance()).balanced).toBe(true) + expect((await c.getBalanceSheet()).balanced).toBe(true) + await expect(c.payExpense(expense.id)).rejects.toThrow() + }) + + it('keeps the live client and its authentication outside demo routes', async () => { + expect(isDemoPath('/demo')).toBe(true) + expect(isDemoPath('/demo/billing')).toBe(true) + expect(isDemoPath('/demography')).toBe(false) + vi.stubGlobal('window', { location: { pathname: '/admin' } }) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ status: 'ok' }))) + const token = vi.fn().mockResolvedValue('real-token'); setAuthTokenGetter(token) + await apiClient.health() + expect(token).toHaveBeenCalledOnce() + expect(fetchSpy).toHaveBeenCalledWith(expect.stringContaining('/health'), expect.objectContaining({ headers: expect.objectContaining({ authorization: 'Bearer real-token' }) })) + }) +}) diff --git a/apps/web/src/lib/demo/client.ts b/apps/web/src/lib/demo/client.ts new file mode 100644 index 0000000..25d83c5 --- /dev/null +++ b/apps/web/src/lib/demo/client.ts @@ -0,0 +1,186 @@ +import * as s from '@opensociety/shared' +import { DEMO_ADMIN, createDemoData } from './data' +import { demoFinance } from './finance' +import { find, groupCount, inRange, newRecord, nowIso, type DemoMethods } from './helpers' +import type { apiClient } from '../api' + +export function createDemoClient(initial = createDemoData()) { + const d = structuredClone(initial) + const finance = demoFinance(d) + const files = new Map() + const apartment = (id: string) => { const a = find(d.apartments, id); return `${a.tower}-${a.apartmentNo}` } + const addApartment = (body: s.CreateApartment) => { + const input = s.createApartmentSchema.parse(body) + if (d.apartments.some(a => a.tower === input.tower && a.apartmentNo === input.apartmentNo)) throw new Error('This apartment already exists.') + const row = { ...newRecord(), floor: null, bhkType: null, isActive: true, ...input } + d.apartments.push(row) + return row + } + const visitorAction = (id: string, action: s.VisitorAction, reason?: string) => { + const row = find(d.visitors, id) + if (!s.canTransition(action, row.status)) throw new Error('This visitor action is no longer available.') + if (action === 'deny') s.denyVisitorSchema.parse({ reason }) + row.status = s.VISITOR_TRANSITIONS[action].to + row.updatedAt = nowIso() + if (action === 'approve') row.approvedBy = DEMO_ADMIN + if (action === 'deny') row.deniedReason = reason ?? null + if (action === 'checkin') { row.checkInAt = nowIso(); row.checkInBy = d.guards[0].id } + if (action === 'checkout') { + row.checkOutAt = nowIso(); row.checkOutBy = d.guards[0].id + for (const slot of d.parking.filter(p => p.occupiedByEntryId === id)) { slot.occupiedByEntryId = null; slot.occupiedAt = null } + } + return row + } + const helpRow = (id: string) => { + const h = find(d.houseHelp, id), ratings = s.summarizeRatings(d.reviews.filter(r => r.houseHelpId === id).map(r => r.rating)) + return { ...h, ratingAvg: ratings.average, reviewCount: ratings.count, verificationLevel: s.verificationLevel(h.idVerified, h.backgroundCheck), + trustScore: s.computeTrustScore({ ratingTrust: ratings.trustScore, idVerified: h.idVerified, backgroundCheck: h.backgroundCheck, incidentCount: h.incidentCount, tenureDays: Math.max(0, (Date.now() - Date.parse(h.createdAt)) / 86400000) }) } + } + const methods: DemoMethods = { + ...finance, + health: () => ({ status: 'ok' }), + getSociety: () => d.society, + updateSociety: body => Object.assign(d.society, s.updateSocietyConfigSchema.parse(body), { updatedAt: nowIso() }), + listApartments: () => d.apartments, + createApartment: addApartment, + createApartmentsBulk: body => { + const input = s.createApartmentsBulkSchema.parse(body) + const keys = new Set(d.apartments.map(a => `${a.tower}/${a.apartmentNo}`)) + for (const a of input.apartments) { const key = `${a.tower}/${a.apartmentNo}`; if (keys.has(key)) throw new Error(`Duplicate apartment: ${key}`); keys.add(key) } + const apartments = input.apartments.map(addApartment) + return { count: apartments.length, apartments } + }, + updateApartment: (id, body) => { + const row = find(d.apartments, id), input = s.updateApartmentSchema.parse(body) + if (d.apartments.some(a => a.id !== id && a.tower === (input.tower ?? row.tower) && a.apartmentNo === (input.apartmentNo ?? row.apartmentNo))) throw new Error('This apartment already exists.') + return Object.assign(row, input, { updatedAt: nowIso() }) + }, + listUsers: status => d.users.filter(u => !status || u.status === status), + approveUser: (id, body) => { const input = s.approveUserSchema.parse(body); find(d.apartments, input.apartmentId); return Object.assign(find(d.users, id), { status: 'APPROVED' as const, updatedAt: nowIso() }) }, + updateUserRole: (id, role) => Object.assign(find(d.users, id), { role: s.userRoleSchema.parse(role), updatedAt: nowIso() }), + listGuards: () => d.guards, + createGuard: body => { const row = { ...newRecord(), userId: null, phone: null, employeeCode: null, isActive: true, ...s.createGuardSchema.parse(body) }; d.guards.push(row); return row }, + updateGuard: (id, body) => Object.assign(find(d.guards, id), s.updateGuardSchema.parse(body), { updatedAt: nowIso() }), + listGuardDevices: id => d.devices.filter(x => x.guardId === id), + revokeGuardDevice: (id, deviceId) => { const device = find(d.devices.filter(x => x.guardId === id), deviceId); device.revokedAt = nowIso(); return device }, + listActiveDuty: () => d.duty.filter(x => !x.clockOutAt), + listDutySessions: params => d.duty.filter(x => (!params?.guardId || x.guardId === params.guardId) && inRange(x.clockInAt, params?.from, params?.to)), + listVisitors: status => d.visitors.filter(v => !status || v.status === status), + approveVisitor: id => visitorAction(id, 'approve'), + denyVisitor: (id, reason) => visitorAction(id, 'deny', reason), + checkInVisitor: id => visitorAction(id, 'checkin'), + checkOutVisitor: id => visitorAction(id, 'checkout'), + listPreApprovals: () => d.preApprovals, + createPreApproval: body => { + const input = s.createPreApprovalSchema.parse(body); find(d.apartments, input.apartmentId) + const row: s.VisitorPreApproval = { ...newRecord(), visitorPhone: null, validUntil: null, maxUses: null, ...input, createdBy: DEMO_ADMIN, + code: crypto.randomUUID().replaceAll('-', '').slice(0, 8).toUpperCase(), validFrom: nowIso(), useCount: 0, isActive: true } + d.preApprovals.unshift(row); return row + }, + revokePreApproval: id => Object.assign(find(d.preApprovals, id), { isActive: false }), + redeemPreApproval: code => { + const pa = d.preApprovals.find(p => p.code === code.trim().toUpperCase()) + if (!pa) throw new Error('Invalid demo visitor code.') + const error = s.preApprovalRedeemError({ ...pa, validUntilMs: pa.validUntil ? Date.parse(pa.validUntil) : null }, Date.now()) + if (error) throw new Error(error) + const row: s.VisitorEntry = { ...newRecord(), clientId: null, apartmentId: pa.apartmentId, preApprovalId: pa.id, visitorName: pa.visitorName, + visitorPhone: pa.visitorPhone, type: 'GUEST', status: 'ENTERED', purpose: 'Pre-approved visit', vehicleNumber: null, photoUrl: null, approvedBy: pa.createdBy, + deniedReason: null, checkInBy: d.guards[0].id, checkInAt: nowIso(), checkOutBy: null, checkOutAt: null } + pa.useCount++; d.visitors.unshift(row); return row + }, + listNotices: params => d.notices.filter(n => s.noticeMatchesQuery(n, params?.q ?? '') && (!params?.category || n.category === params.category) && inRange(n.publishedAt, params?.from, params?.to)), + createNotice: body => { const row = { ...newRecord(), attachmentUrl: null, attachmentName: null, expiresAt: null, ...s.createNoticeSchema.parse(body), publishedBy: DEMO_ADMIN, publishedAt: nowIso(), readCount: 0, read: true }; d.notices.unshift(row); return row }, + listNoticeReads: id => d.users.slice(1, 1 + (find(d.notices, id).readCount ?? 0)).map(u => ({ userId: u.id, name: u.name, readAt: nowIso() })), + uploadFile: file => { if (file.size > 5 * 1024 * 1024) throw new Error('Demo attachments must be smaller than 5 MB.'); const key = crypto.randomUUID(); files.set(`/uploads/${key}`, file); return { key, url: `/uploads/${key}` } }, + fetchUploadObjectUrl: path => { const file = files.get(path); if (!file) throw new Error('This attachment is no longer available. Attach it again in this demo.'); return URL.createObjectURL(file) }, + listTickets: status => d.tickets.filter(ticket => !status || ticket.status === status), + createTicket: body => { const input = s.createTicketSchema.parse(body); find(d.apartments, input.apartmentId); const row: s.Ticket = { ...newRecord(), ...input, raisedBy: DEMO_ADMIN, status: 'OPEN', assignedTo: null, resolutionNote: null, resolvedAt: null }; d.tickets.unshift(row); return row }, + transitionTicket: (id, action, resolutionNote) => { + const row = find(d.tickets, id) + if (!s.canTicketTransition(action, row.status)) throw new Error('This ticket action is no longer available.') + return Object.assign(row, { status: s.TICKET_TRANSITIONS[action].to, resolutionNote: resolutionNote ?? row.resolutionNote, resolvedAt: action === 'resolve' ? nowIso() : action === 'reopen' ? null : row.resolvedAt, updatedAt: nowIso() }) + }, + assignTicket: (id, assignedTo) => { find(d.users, assignedTo); return Object.assign(find(d.tickets, id), { assignedTo, updatedAt: nowIso() }) }, + listHouseHelp: type => d.houseHelp.filter(h => !type || h.type === type).map(h => helpRow(h.id)), + getHouseHelpReviews: id => { const reviews = d.reviews.filter(r => r.houseHelpId === id); return { reviews, summary: { ...s.summarizeRatings(reviews.map(r => r.rating)), trustScore: helpRow(id).trustScore } } }, + createHouseHelpReview: (id, body) => { find(d.houseHelp, id); const input = s.createHouseHelpReviewSchema.parse(body), row = { ...newRecord(), houseHelpId: id, comment: null, ...input }; d.reviews.unshift(row); return { ok: true, id: row.id, rating: row.rating } }, + updateHouseHelpVerification: (id, body) => Object.assign(find(d.houseHelp, id), s.updateVerificationSchema.parse(body), { updatedAt: nowIso() }), + createHouseHelp: body => { + const row = { ...newRecord(), phone: null, photoUrl: null, idProofType: null, idProofNumber: null, idProofUrl: null, isActive: true, registeredBy: DEMO_ADMIN, + ratingAvg: null, reviewCount: 0, trustScore: 0, idVerified: false, backgroundCheck: 'PENDING' as const, incidentCount: 0, verificationLevel: 'UNVERIFIED' as const, ...s.createHouseHelpSchema.parse(body) } + d.houseHelp.push(row); return row + }, + updateHouseHelp: (id, body) => Object.assign(find(d.houseHelp, id), s.updateHouseHelpSchema.parse(body), { updatedAt: nowIso() }), + listHouseHelpAssignments: id => d.assignments.filter(a => a.houseHelpId === id), + assignHouseHelp: (id, apartmentId) => { + find(d.houseHelp, id); find(d.apartments, apartmentId) + const existing = d.assignments.find(a => a.houseHelpId === id && a.apartmentId === apartmentId) + if (existing) return existing + const row = { ...newRecord(), houseHelpId: id, apartmentId, assignedBy: DEMO_ADMIN }; d.assignments.push(row); return row + }, + removeHouseHelpAssignment: (id, apartmentId) => { const row = d.assignments.find(a => a.houseHelpId === id && a.apartmentId === apartmentId); if (!row) throw new Error('Assignment not found.'); d.assignments.splice(d.assignments.indexOf(row), 1); return row }, + listHouseHelpEntries: params => d.attendance.filter(a => inRange(a.checkInAt, params?.from, params?.to)), + listVehicles: apartmentId => d.vehicles.filter(v => !apartmentId || v.apartmentId === apartmentId), + createVehicle: body => { const input = s.createVehicleSchema.parse(body); find(d.apartments, input.apartmentId); const row = { ...newRecord(), make: null, color: null, ...input, registrationNumber: s.normalizePlate(input.registrationNumber), registeredBy: DEMO_ADMIN, isActive: true }; if (d.vehicles.some(v => v.registrationNumber === row.registrationNumber)) throw new Error('Vehicle already registered.'); d.vehicles.push(row); return row }, + updateVehicle: (id, body) => { const input = s.updateVehicleSchema.parse(body); if (input.registrationNumber) input.registrationNumber = s.normalizePlate(input.registrationNumber); if (input.registrationNumber && d.vehicles.some(v => v.id !== id && v.registrationNumber === input.registrationNumber)) throw new Error('Vehicle already registered.'); return Object.assign(find(d.vehicles, id), input, { updatedAt: nowIso() }) }, + listVehicleGateLog: () => d.visitors.filter(v => v.vehicleNumber).map(v => ({ ...v, apartment: apartment(v.apartmentId), registered: d.vehicles.some(r => r.registrationNumber === v.vehicleNumber) })), + listParkingSlots: () => d.parking.map(p => ({ ...p, apartment: p.apartmentId ? apartment(p.apartmentId) : null })), + listParkingDirectory: () => d.parking.filter(p => p.isActive).map(p => ({ ...p, apartment: p.apartmentId ? apartment(p.apartmentId) : null })), + listVisitorParking: () => { + const slots = d.parking.filter(p => p.isVisitor && p.isActive).map(p => { const v = d.visitors.find(v => v.id === p.occupiedByEntryId); return { ...p, visitorName: v?.visitorName ?? null, vehicleNumber: v?.vehicleNumber ?? null } }) + const occupied = slots.filter(p => p.occupiedByEntryId).length + return { slots, summary: { total: slots.length, occupied, available: slots.length - occupied, isFull: slots.length > 0 && occupied === slots.length } } + }, + createParkingSlot: body => { + const input = s.createParkingSlotSchema.parse(body) + if (d.parking.some(p => p.slotNumber === input.slotNumber)) throw new Error('Slot already exists.') + const row = { ...newRecord(), ...input, apartmentId: null, apartment: null, isTemporary: false, assignedUntil: null, assignedBy: null, assignedAt: null, occupiedByEntryId: null, occupiedAt: null, notes: input.notes ?? null, isActive: true }; d.parking.push(row); return row + }, + updateParkingSlot: (id, body) => Object.assign(find(d.parking, id), s.updateParkingSlotSchema.parse(body), { updatedAt: nowIso() }), + assignParkingSlot: (id, body) => { const input = s.assignParkingSlotSchema.parse(body), row = find(d.parking, id); if (input.apartmentId) find(d.apartments, input.apartmentId); if (row.isVisitor) throw new Error('Visitor slots cannot be assigned to apartments.'); return Object.assign(row, input, { apartment: input.apartmentId ? apartment(input.apartmentId) : null, assignedBy: DEMO_ADMIN, assignedAt: nowIso() }) }, + deleteParkingSlot: id => { const row = find(d.parking, id); if (row.occupiedByEntryId || row.apartmentId) throw new Error('Release the slot before removing it.'); d.parking.splice(d.parking.indexOf(row), 1); return { ok: true } }, + listVendors: () => d.vendors, + createVendor: body => { const row = { ...newRecord(), category: null, pan: null, gstin: null, contact: null, bankAccount: null, isActive: true, ...s.createVendorSchema.parse(body) }; d.vendors.push(row); return row }, + updateVendor: (id, body) => Object.assign(find(d.vendors, id), s.updateVendorSchema.parse(body)), + listExpenses: params => d.expenses.filter(e => (!params?.accountId || e.accountId === params.accountId) && (!params?.vendorId || e.vendorId === params.vendorId) && (!params?.status || e.status === params.status) && inRange(e.createdAt, params?.from, params?.to)).map(e => ({ ...e, vendor: e.vendorId ? find(d.vendors, e.vendorId).name : null, account: find(d.accounts, e.accountId).name })), + createExpense: body => { + const input = s.createExpenseSchema.parse(body), account = find(d.accounts, input.accountId) + if (account.type !== 'EXPENSE' || account.isGroup) throw new Error('Choose an expense account.') + if (input.vendorId) find(d.vendors, input.vendorId) + const row = { ...newRecord(), vendorId: null, billRef: null, method: null, attachmentUrl: null, ...input, paidAt: input.status === 'PAID' ? input.paidAt ?? nowIso() : null, + recordedBy: DEMO_ADMIN, tdsAmount: input.tds ? s.computeTds(input.amount, input.tds.ratePct) : 0, tdsSection: input.tds?.section } + d.expenses.unshift(row); return row + }, + payExpense: (id, method) => { const row = find(d.expenses, id); if (row.status === 'PAID') throw new Error('This expense is already paid.'); return Object.assign(row, { status: 'PAID' as const, paidAt: nowIso(), method: s.paymentMethodSchema.parse(method ?? 'BANK_TRANSFER') }) }, + getTdsSummary: (from, to) => s.tdsSectionSchema.options.map(section => { const rows = d.expenses.filter(e => e.tdsSection === section && inRange(e.createdAt, from, to)); return { section, amount: rows.reduce((n, e) => n + (e.tdsAmount ?? 0), 0), count: rows.length } }).filter(r => r.count), + getVisitorTrends: (from, to) => { + const rows = d.visitors.filter(v => inRange(v.createdAt, from, to)), byDay = groupCount(rows, v => v.createdAt.slice(0, 10)).map(r => ({ date: r.label, count: r.count })).sort((a, b) => a.date.localeCompare(b.date)) + const byHour = s.fillHours(groupCount(rows, v => String(new Date(v.createdAt).getUTCHours())).map(r => ({ hour: Number(r.label), count: r.count }))) + return { from: from ?? byDay[0]?.date ?? nowIso().slice(0, 10), to: to ?? nowIso().slice(0, 10), total: rows.length, distinctDays: byDay.length, avgPerDay: s.averagePerDay(rows.length, byDay.length), peakHour: s.peakHour(byHour), byHour, byDay, byType: groupCount(rows, v => v.type).map(r => ({ type: r.label, count: r.count })) } + }, + getHouseHelpAnalytics: () => ({ totalActive: d.houseHelp.filter(h => h.isActive).length, totalAttendance: d.attendance.length, byType: groupCount(d.houseHelp.filter(h => h.isActive), h => h.type), attendanceByDow: s.fillDaysOfWeek(groupCount(d.attendance, a => String(new Date(a.checkInAt).getUTCDay())).map(r => ({ dow: Number(r.label), count: r.count }))) }), + getMaintenanceAnalytics: () => ({ total: d.tickets.length, pending: d.tickets.filter(ticket => ['OPEN', 'IN_PROGRESS'].includes(ticket.status)).length, avgResolutionHours: s.avgResolutionHours(d.tickets.map(ticket => ({ createdMs: Date.parse(ticket.createdAt), resolvedMs: ticket.resolvedAt ? Date.parse(ticket.resolvedAt) : null }))), byCategory: groupCount(d.tickets, ticket => ticket.category), byStatus: groupCount(d.tickets, ticket => ticket.status) }), + reportExportObjectUrl: async path => (await import('./exports')).exportReport(d, path), + visitorTrendsPdfObjectUrl: async (from, to) => { + const report = await methods.getVisitorTrends(from, to) + return (await import('./exports')).exportTable({ name: 'Demo visitor trends', rows: [['Date', 'Visitors'], ...report.byDay.map(r => [r.date, r.count])] }, 'pdf') + }, + invoiceObjectUrl: async id => { + const bill = finance.getBill(id) + return (await import('./exports')).exportTable({ name: `DEMO invoice: ${bill.apartment}`, rows: [[bill.title], ['Description', 'Amount (INR)'], ...(bill.lineItems ?? []).map(l => [l.description, (l.amount + l.taxAmount) / 100]), ['Total', bill.totalAmount / 100], ['Paid', bill.paidAmount! / 100]] }, 'pdf') + }, + } + // Clone responses like an HTTP boundary so query caches cannot mutate the store. + return new Proxy(methods, { get(target, property: keyof DemoMethods) { + const method = target[property] + if (typeof method !== 'function') throw new Error(`Unsupported demo action: ${String(property)}`) + return async (...args: unknown[]) => structuredClone(await Reflect.apply(method, target, args)) + } }) as typeof apiClient +} + +let client: ReturnType | undefined +export function getDemoClient() { + if (typeof window === 'undefined') throw new Error('The demo is only available in the browser.') + return client ??= createDemoClient() +} +export function resetDemoClient() { client = undefined } diff --git a/apps/web/src/lib/demo/mode.ts b/apps/web/src/lib/demo/mode.ts new file mode 100644 index 0000000..d7ce40c --- /dev/null +++ b/apps/web/src/lib/demo/mode.ts @@ -0,0 +1,7 @@ +export function isDemoPath(pathname: string) { + return pathname === '/demo' || pathname.startsWith('/demo/') +} + +export function isDemoBrowser() { + return typeof window !== 'undefined' && isDemoPath(window.location.pathname) +} From 7a49ac6c95d964526f860700edebf8ed0559acb9 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:49:52 +0530 Subject: [PATCH 06/14] Defer spreadsheet encoding until export --- apps/api/src/xlsx.test.ts | 14 +++++++++++++- packages/shared/src/xlsx.ts | 4 ++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/api/src/xlsx.test.ts b/apps/api/src/xlsx.test.ts index ca60f83..d08f7f2 100644 --- a/apps/api/src/xlsx.test.ts +++ b/apps/api/src/xlsx.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest' +import { describe, it, expect, vi } from 'vitest' import { buildXlsx } from './lib/xlsx' describe('buildXlsx (dependency-free .xlsx writer)', () => { @@ -39,4 +39,16 @@ describe('buildXlsx (dependency-free .xlsx writer)', () => { expect(buf.length).toBeGreaterThan(200) expect(buf).toBeInstanceOf(Uint8Array) }) + + it('allows shared contracts to load without a browser text encoder', async () => { + vi.stubGlobal('TextEncoder', undefined) + vi.resetModules() + try { + const shared = await import('@opensociety/shared') + expect(typeof shared.buildXlsx).toBe('function') + expect(shared.visitorStatusSchema.parse('PENDING')).toBe('PENDING') + } finally { + vi.unstubAllGlobals() + } + }) }) diff --git a/packages/shared/src/xlsx.ts b/packages/shared/src/xlsx.ts index 50c4bbf..1ba173f 100644 --- a/packages/shared/src/xlsx.ts +++ b/packages/shared/src/xlsx.ts @@ -6,8 +6,6 @@ export type Cell = string | number | null | undefined export type Sheet = { name: string; rows: Cell[][] } -const enc = new TextEncoder() - // ----- CRC32 (IEEE 802.3, poly 0xEDB88320) ----- const CRC_TABLE = (() => { const t = new Uint32Array(256) @@ -95,6 +93,7 @@ function u32(n: number): number[] { } function zipStored(files: ZipFile[]): Uint8Array { + const enc = new TextEncoder() const chunks: number[] = [] const central: number[] = [] let offset = 0 @@ -156,6 +155,7 @@ function zipStored(files: ZipFile[]): Uint8Array { // Build a real .xlsx workbook from one or more named sheets of cell rows. export function buildXlsx(sheets: Sheet[]): Uint8Array { + const enc = new TextEncoder() const tabs = sheets.length ? sheets : [{ name: 'Sheet1', rows: [] }] const files: ZipFile[] = [ { name: '[Content_Types].xml', data: enc.encode(contentTypesXml(tabs.length)) }, From 08e0061dcde5cd02eccc58292bb46d07c242b44b Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 03:50:39 +0530 Subject: [PATCH 07/14] Add a public no-signup society demo --- README.md | 4 ++ apps/web/src/lib/dashboard-path.ts | 7 +++ apps/web/src/routes/__root.tsx | 6 ++- apps/web/src/routes/admin.tsx | 19 ++++---- apps/web/src/routes/admin/index.tsx | 40 ++++++++++++---- apps/web/src/routes/admin/setup.tsx | 4 +- apps/web/src/routes/demo.tsx | 54 ++++++++++++++++++++++ apps/web/src/routes/demo/analytics.tsx | 9 ++++ apps/web/src/routes/demo/apartments.tsx | 9 ++++ apps/web/src/routes/demo/billing.tsx | 9 ++++ apps/web/src/routes/demo/duty.tsx | 9 ++++ apps/web/src/routes/demo/expenses.tsx | 9 ++++ apps/web/src/routes/demo/guards.tsx | 9 ++++ apps/web/src/routes/demo/house-help.tsx | 9 ++++ apps/web/src/routes/demo/index.tsx | 9 ++++ apps/web/src/routes/demo/notices.tsx | 9 ++++ apps/web/src/routes/demo/parking.tsx | 9 ++++ apps/web/src/routes/demo/pre-approvals.tsx | 9 ++++ apps/web/src/routes/demo/reports.tsx | 9 ++++ apps/web/src/routes/demo/residents.tsx | 9 ++++ apps/web/src/routes/demo/setup.tsx | 9 ++++ apps/web/src/routes/demo/society.tsx | 9 ++++ apps/web/src/routes/demo/tickets.tsx | 9 ++++ apps/web/src/routes/demo/vehicles.tsx | 9 ++++ apps/web/src/routes/demo/visitors.tsx | 9 ++++ apps/web/src/routes/index.tsx | 9 ++-- packages/shared/src/i18n.ts | 22 +++++++++ 27 files changed, 303 insertions(+), 24 deletions(-) create mode 100644 apps/web/src/lib/dashboard-path.ts create mode 100644 apps/web/src/routes/demo.tsx create mode 100644 apps/web/src/routes/demo/analytics.tsx create mode 100644 apps/web/src/routes/demo/apartments.tsx create mode 100644 apps/web/src/routes/demo/billing.tsx create mode 100644 apps/web/src/routes/demo/duty.tsx create mode 100644 apps/web/src/routes/demo/expenses.tsx create mode 100644 apps/web/src/routes/demo/guards.tsx create mode 100644 apps/web/src/routes/demo/house-help.tsx create mode 100644 apps/web/src/routes/demo/index.tsx create mode 100644 apps/web/src/routes/demo/notices.tsx create mode 100644 apps/web/src/routes/demo/parking.tsx create mode 100644 apps/web/src/routes/demo/pre-approvals.tsx create mode 100644 apps/web/src/routes/demo/reports.tsx create mode 100644 apps/web/src/routes/demo/residents.tsx create mode 100644 apps/web/src/routes/demo/setup.tsx create mode 100644 apps/web/src/routes/demo/society.tsx create mode 100644 apps/web/src/routes/demo/tickets.tsx create mode 100644 apps/web/src/routes/demo/vehicles.tsx create mode 100644 apps/web/src/routes/demo/visitors.tsx diff --git a/README.md b/README.md index a25bfe3..d716762 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,10 @@ Until Clerk sessions are wired into the web app, set `VITE_DEV_USER_ID` to a rea ## Admin dashboard +Visitors can open **`/demo`** or choose **Try the demo** on the home page to explore a populated sample society without signing up. The demo uses the same web dashboard, with fictional residents, visitors, staff, parking, notices, tickets, bills, payments and expenses. Edits and downloads run entirely in the browser; the demo never calls the society API or Clerk. Each tab has its own state, and **Reset demo** or a page refresh restores fresh sample data. No database, credentials or separate deployment is needed to run it alongside the web app. + +Demo actions use the shared validation and calculation helpers. Financial statements update with payments and expenses, and PDF, Excel, CSV and Tally downloads are generated locally. The demo covers the web dashboard; native mobile sessions still use the normal API and login. + The web app (`apps/web`) is a shadcn/ui dashboard with light + dark mode at `/admin`: - **Overview** — at-a-glance counts and a setup checklist diff --git a/apps/web/src/lib/dashboard-path.ts b/apps/web/src/lib/dashboard-path.ts new file mode 100644 index 0000000..4c6cbdf --- /dev/null +++ b/apps/web/src/lib/dashboard-path.ts @@ -0,0 +1,7 @@ +import { useLocation } from '@tanstack/react-router' +import { isDemoPath } from './demo/mode' + +export function useDashboardPath() { + const demo = useLocation({ select: location => isDemoPath(location.pathname) }) + return (path: string) => demo ? path.replace(/^\/admin(?=\/|$)/, '/demo') : path +} diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index b579c99..ca107ea 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import { HeadContent, Scripts, createRootRoute, useLocation } from '@tanstack/react-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' import { TanStackDevtools } from '@tanstack/react-devtools' import { QueryClientProvider } from '@tanstack/react-query' @@ -10,6 +10,7 @@ import { setAuthTokenGetter } from '../lib/api' import { ThemeProvider, themeInitScript } from '../lib/theme' import { I18nProvider } from '../lib/i18n' import appCss from '../styles.css?url' +import { isDemoPath } from '../lib/demo/mode' const CLERK_PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined @@ -27,6 +28,7 @@ function AuthBridge() { // Clerk is optional: without a publishable key the app runs on the dev // x-user-id fallback, mirroring the API's own conditional auth. function Providers({ children }: { children: React.ReactNode }) { + const publicPage = useLocation({ select: location => location.pathname === '/' || isDemoPath(location.pathname) }) const tree = ( @@ -34,7 +36,7 @@ function Providers({ children }: { children: React.ReactNode }) { ) - if (!CLERK_PUBLISHABLE_KEY) return tree + if (!CLERK_PUBLISHABLE_KEY || publicPage) return tree return ( diff --git a/apps/web/src/routes/admin.tsx b/apps/web/src/routes/admin.tsx index ff7ec97..6e4b950 100644 --- a/apps/web/src/routes/admin.tsx +++ b/apps/web/src/routes/admin.tsx @@ -28,6 +28,7 @@ import { ThemeToggle } from '@/components/theme-toggle' import { LanguageSwitcher } from '@/components/language-switcher' import { useT } from '@/lib/i18n' import { cn } from '@/lib/utils' +import { useDashboardPath } from '@/lib/dashboard-path' export const Route = createFileRoute('/admin')({ component: AdminLayout }) @@ -51,7 +52,9 @@ const NAV: { to: string; tKey: string; icon: LucideIcon }[] = [ { to: '/admin/notices', tKey: 'nav.notices', icon: Megaphone }, ] -function AdminLayout() { +export function AdminLayout() { + const dashboardPath = useDashboardPath() + const demo = dashboardPath('/admin') === '/demo' const health = useQuery({ queryKey: ['health'], queryFn: apiClient.health, retry: false }) const { t } = useT() @@ -59,16 +62,16 @@ function AdminLayout() {
- + {dashboardPath('/admin') === '/demo' ? ( + + + {t('demo.exploreTitle')} + + +

{t('demo.exploreDescription')}

+
+ {[ + ['/admin/visitors', 'demo.tryVisitor'], + ['/admin/tickets', 'demo.tryTicket'], + ['/admin/billing', 'demo.tryPayment'], + ['/admin/notices', 'demo.tryNotice'], + ].map(([path, label]) => ( + + ))} +
+
+
+ ) : {t('overview.gettingStarted')} @@ -115,32 +139,32 @@ function Overview() {

{t('overview.newHerePrefix')} {t('overview.newHereSuffix')}

{t('overview.step1Prefix')} - {t('nav.society')} + {t('nav.society')} {t('overview.step1Suffix')}

{t('overview.step2Prefix')} - {t('nav.apartments')} + {t('nav.apartments')} {t('overview.step2Suffix')}

{t('overview.step3Prefix')} - {t('nav.residents')} + {t('nav.residents')} {t('overview.step3Suffix')}

{t('overview.step4Prefix')} - {t('nav.guards')} + {t('nav.guards')} {t('overview.step4Suffix')}

-
+
}
) } diff --git a/apps/web/src/routes/admin/setup.tsx b/apps/web/src/routes/admin/setup.tsx index bb53c26..943b8a0 100644 --- a/apps/web/src/routes/admin/setup.tsx +++ b/apps/web/src/routes/admin/setup.tsx @@ -5,6 +5,7 @@ import type { CreateApartment, UpdateSocietyConfig } from '@opensociety/shared' import { apiClient } from '../../lib/api' import { useT } from '@/lib/i18n' +import { useDashboardPath } from '@/lib/dashboard-path' import { parseBulk } from '../../lib/apartments-csv' import { EMPTY_SOCIETY, @@ -72,6 +73,7 @@ function Stepper({ current }: { current: number }) { } function SetupWizard() { + const dashboardPath = useDashboardPath() const { t } = useT() const navigate = useNavigate() const [step, setStep] = useState(0) @@ -90,7 +92,7 @@ function SetupWizard() { await apiClient.createApartmentsBulk({ apartments: apartments as CreateApartment[] }) } }, - onSuccess: () => navigate({ to: '/admin' }), + onSuccess: () => navigate({ to: dashboardPath('/admin') }), }) return ( diff --git a/apps/web/src/routes/demo.tsx b/apps/web/src/routes/demo.tsx new file mode 100644 index 0000000..f84d7d9 --- /dev/null +++ b/apps/web/src/routes/demo.tsx @@ -0,0 +1,54 @@ +import { useState } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { QueryClient, QueryClientProvider, MutationCache, useIsMutating } from '@tanstack/react-query' +import { AdminLayout } from './admin' +import { resetDemoClient } from '@/lib/demo/client' +import { useT } from '@/lib/i18n' +import { Button } from '@/components/ui/button' + +export const Route = createFileRoute('/demo')({ + ssr: false, + component: DemoLayout, + head: () => ({ meta: [{ title: 'Try OpenSociety | Interactive demo' }, { name: 'robots', content: 'noindex' }] }), +}) + +function newDemoQueryClient() { + const client: QueryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: 0 }, mutations: { retry: false } }, + mutationCache: new MutationCache({ onSuccess: () => { void client.invalidateQueries() } }), + }) + return client +} + +function DemoLayout() { + const { t } = useT() + const [session, setSession] = useState(() => ({ client: newDemoQueryClient(), revision: 0 })) + const [resetting, setResetting] = useState(false) + const mutating = useIsMutating(undefined, session.client) + const reset = async () => { + if (session.client.isMutating()) return + setResetting(true) + await session.client.cancelQueries() + session.client.clear() + resetDemoClient() + setSession({ client: newDemoQueryClient(), revision: session.revision + 1 }) + setResetting(false) + } + return ( + +
+
+
+

{t('demo.title')}

+

{t('demo.description')}

+
+
+ + {t('demo.exit')} +
+
+
+ +
+ ) +} diff --git a/apps/web/src/routes/demo/analytics.tsx b/apps/web/src/routes/demo/analytics.tsx new file mode 100644 index 0000000..0bd6eac --- /dev/null +++ b/apps/web/src/routes/demo/analytics.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/analytics' + +export const Route = createFileRoute('/demo/analytics')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/apartments.tsx b/apps/web/src/routes/demo/apartments.tsx new file mode 100644 index 0000000..4b84a7e --- /dev/null +++ b/apps/web/src/routes/demo/apartments.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/apartments' + +export const Route = createFileRoute('/demo/apartments')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/billing.tsx b/apps/web/src/routes/demo/billing.tsx new file mode 100644 index 0000000..d21cdac --- /dev/null +++ b/apps/web/src/routes/demo/billing.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/billing' + +export const Route = createFileRoute('/demo/billing')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/duty.tsx b/apps/web/src/routes/demo/duty.tsx new file mode 100644 index 0000000..b31237a --- /dev/null +++ b/apps/web/src/routes/demo/duty.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/duty' + +export const Route = createFileRoute('/demo/duty')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/expenses.tsx b/apps/web/src/routes/demo/expenses.tsx new file mode 100644 index 0000000..f3ffcc8 --- /dev/null +++ b/apps/web/src/routes/demo/expenses.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/expenses' + +export const Route = createFileRoute('/demo/expenses')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/guards.tsx b/apps/web/src/routes/demo/guards.tsx new file mode 100644 index 0000000..08019cd --- /dev/null +++ b/apps/web/src/routes/demo/guards.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/guards' + +export const Route = createFileRoute('/demo/guards')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/house-help.tsx b/apps/web/src/routes/demo/house-help.tsx new file mode 100644 index 0000000..c98d805 --- /dev/null +++ b/apps/web/src/routes/demo/house-help.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/house-help' + +export const Route = createFileRoute('/demo/house-help')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/index.tsx b/apps/web/src/routes/demo/index.tsx new file mode 100644 index 0000000..978adc0 --- /dev/null +++ b/apps/web/src/routes/demo/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/index' + +export const Route = createFileRoute('/demo/')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/notices.tsx b/apps/web/src/routes/demo/notices.tsx new file mode 100644 index 0000000..5b3cb7b --- /dev/null +++ b/apps/web/src/routes/demo/notices.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/notices' + +export const Route = createFileRoute('/demo/notices')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/parking.tsx b/apps/web/src/routes/demo/parking.tsx new file mode 100644 index 0000000..9713517 --- /dev/null +++ b/apps/web/src/routes/demo/parking.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/parking' + +export const Route = createFileRoute('/demo/parking')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/pre-approvals.tsx b/apps/web/src/routes/demo/pre-approvals.tsx new file mode 100644 index 0000000..f64999c --- /dev/null +++ b/apps/web/src/routes/demo/pre-approvals.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/pre-approvals' + +export const Route = createFileRoute('/demo/pre-approvals')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/reports.tsx b/apps/web/src/routes/demo/reports.tsx new file mode 100644 index 0000000..d04bb8b --- /dev/null +++ b/apps/web/src/routes/demo/reports.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/reports' + +export const Route = createFileRoute('/demo/reports')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/residents.tsx b/apps/web/src/routes/demo/residents.tsx new file mode 100644 index 0000000..a01a562 --- /dev/null +++ b/apps/web/src/routes/demo/residents.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/residents' + +export const Route = createFileRoute('/demo/residents')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/setup.tsx b/apps/web/src/routes/demo/setup.tsx new file mode 100644 index 0000000..e70a5fb --- /dev/null +++ b/apps/web/src/routes/demo/setup.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/setup' + +export const Route = createFileRoute('/demo/setup')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/society.tsx b/apps/web/src/routes/demo/society.tsx new file mode 100644 index 0000000..7b95058 --- /dev/null +++ b/apps/web/src/routes/demo/society.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/society' + +export const Route = createFileRoute('/demo/society')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/tickets.tsx b/apps/web/src/routes/demo/tickets.tsx new file mode 100644 index 0000000..908a53f --- /dev/null +++ b/apps/web/src/routes/demo/tickets.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/tickets' + +export const Route = createFileRoute('/demo/tickets')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/vehicles.tsx b/apps/web/src/routes/demo/vehicles.tsx new file mode 100644 index 0000000..9aaf81c --- /dev/null +++ b/apps/web/src/routes/demo/vehicles.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/vehicles' + +export const Route = createFileRoute('/demo/vehicles')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/demo/visitors.tsx b/apps/web/src/routes/demo/visitors.tsx new file mode 100644 index 0000000..7c8f4b7 --- /dev/null +++ b/apps/web/src/routes/demo/visitors.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Route as AdminRoute } from '../admin/visitors' + +export const Route = createFileRoute('/demo/visitors')({ component: DemoPage }) + +function DemoPage() { + const Page = AdminRoute.options.component! + return +} diff --git a/apps/web/src/routes/index.tsx b/apps/web/src/routes/index.tsx index 2580694..3819f6b 100644 --- a/apps/web/src/routes/index.tsx +++ b/apps/web/src/routes/index.tsx @@ -34,14 +34,13 @@ function App() { An open-source alternative to MyGate and NoBrokerHood for gated communities. You own your data and your deployment.

-
+

Explore a sample society. No signup needed.

+
diff --git a/packages/shared/src/i18n.ts b/packages/shared/src/i18n.ts index c3673ed..13dd9f9 100644 --- a/packages/shared/src/i18n.ts +++ b/packages/shared/src/i18n.ts @@ -49,6 +49,17 @@ const commonHi: Dict = { } const webEn: Dict = { + 'demo.badge': 'Demo', + 'demo.title': 'Your demo society', + 'demo.description': 'Explore and make changes freely. All data is fictional and private to this tab. Refreshing starts over.', + 'demo.reset': 'Reset demo', + 'demo.exit': 'Exit demo', + 'demo.exploreTitle': 'Try a few everyday tasks', + 'demo.exploreDescription': 'This society is ready to explore. Your changes stay in this tab, and you can reset at any time.', + 'demo.tryVisitor': 'Approve a visitor', + 'demo.tryTicket': 'Resolve a ticket', + 'demo.tryPayment': 'Record a payment', + 'demo.tryNotice': 'Publish a notice', 'nav.overview': 'Overview', 'nav.society': 'Society', 'nav.apartments': 'Apartments', @@ -486,6 +497,17 @@ const webEn: Dict = { 'page.expenses.initLedger': 'Initialize accounts', } const webHi: Dict = { + 'demo.badge': 'डेमो', + 'demo.title': 'आपकी डेमो सोसाइटी', + 'demo.description': 'बेझिझक देखें और बदलाव करें। सभी डेटा काल्पनिक हैं और केवल इस टैब में रहते हैं। रिफ्रेश करने पर डेमो फिर से शुरू होता है।', + 'demo.reset': 'डेमो रीसेट करें', + 'demo.exit': 'डेमो से बाहर निकलें', + 'demo.exploreTitle': 'रोज़ के कुछ काम आज़माएँ', + 'demo.exploreDescription': 'यह सोसाइटी तैयार है। आपके बदलाव इसी टैब में रहते हैं और आप कभी भी रीसेट कर सकते हैं।', + 'demo.tryVisitor': 'आगंतुक को मंज़ूरी दें', + 'demo.tryTicket': 'शिकायत हल करें', + 'demo.tryPayment': 'भुगतान दर्ज करें', + 'demo.tryNotice': 'सूचना प्रकाशित करें', 'nav.overview': 'अवलोकन', 'nav.society': 'सोसायटी', 'nav.apartments': 'अपार्टमेंट', From 33c56805cccd26672e8d59cafacf47fe88930fb6 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:40:45 +0530 Subject: [PATCH 08/14] Share demo society fixtures with the phone app --- apps/web/src/lib/demo/data.ts | 127 +------------------------------ packages/shared/package.json | 4 + packages/shared/src/demo.ts | 136 ++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 126 deletions(-) create mode 100644 packages/shared/src/demo.ts diff --git a/apps/web/src/lib/demo/data.ts b/apps/web/src/lib/demo/data.ts index ecb9e5d..27b0596 100644 --- a/apps/web/src/lib/demo/data.ts +++ b/apps/web/src/lib/demo/data.ts @@ -1,126 +1 @@ -import * as s from '@opensociety/shared' -import type { HouseHelpRow, ParkingSlotRow } from '../api' - -export const demoId = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}` -export const DEMO_ADMIN = demoId(100) - -export function createDemoData(now = new Date()) { - const at = (days = 0, hours = 0) => new Date(now.getTime() + days * 86400000 + hours * 3600000).toISOString() - const stamp = { createdAt: at(-60), updatedAt: at() } - const apartments: s.Apartment[] = Array.from({ length: 12 }, (_, i) => ({ - id: demoId(i + 1), tower: i < 6 ? 'A' : 'B', apartmentNo: `${Math.floor(i % 6 / 2) + 1}0${i % 2 + 1}`, - floor: Math.floor(i % 6 / 2) + 1, bhkType: i < 6 ? '2BHK' : '3BHK', isActive: true, ...stamp, - })) - const names = ['Demo Admin', 'Priya Sharma', 'Arjun Rao', 'Meera Shah', 'Kabir Das', 'Nisha Patel', 'Ravi Kumar', 'Asha Iyer'] - const users: s.User[] = names.map((name, i) => ({ - id: demoId(100 + i), clerkId: `demo_${i}`, name, email: `resident${i}@example.com`, phone: null, - role: i === 0 ? 'ADMIN' : i === 7 ? 'STAFF' : 'RESIDENT', status: i === 5 || i === 6 ? 'PENDING' : 'APPROVED', isActive: true, ...stamp, - })) - const guards: s.Guard[] = ['Ramesh Singh', 'Suresh Kumar', 'Anita Devi'].map((name, i) => ({ - id: demoId(200 + i), name, userId: null, phone: null, employeeCode: `G-00${i + 1}`, isActive: true, ...stamp, - })) - const duty: s.GuardDutySession[] = Array.from({ length: 9 }, (_, i) => ({ - id: demoId(220 + i), guardId: guards[i % 3].id, guardName: guards[i % 3].name, - clockInAt: at(-Math.floor(i / 3), -4), clockOutAt: i < 2 ? null : at(-Math.floor(i / 3), -1), - clockInLat: null, clockInLng: null, clockOutLat: null, clockOutLng: null, createdAt: at(-Math.floor(i / 3), -4), - })) - const devices: s.GuardDevice[] = guards.map((g, i) => ({ - id: demoId(240 + i), guardId: g.id, deviceId: `demo-gate-${i}`, model: 'Demo gate phone', boundAt: at(-10), lastActiveAt: at(0, -1), revokedAt: null, - })) - const visitors: s.VisitorEntry[] = Array.from({ length: 24 }, (_, i) => ({ - id: demoId(300 + i), clientId: null, apartmentId: apartments[i % 12].id, preApprovalId: null, - visitorName: ['Aarav Mehta', 'Grocery delivery', 'Diya Kapoor', 'Lift technician'][i % 4], visitorPhone: null, - type: (['GUEST', 'DELIVERY', 'GUEST', 'SERVICE'] as const)[i % 4], - status: i === 0 ? 'PENDING' : i === 1 ? 'APPROVED' : i === 2 ? 'ENTERED' : 'EXITED', - purpose: ['Family visit', 'Weekly groceries', 'Evening visit', 'Scheduled service'][i % 4], - vehicleNumber: i % 2 ? null : `DEMO${1000 + i}`, photoUrl: null, approvedBy: i ? DEMO_ADMIN : null, deniedReason: null, - checkInBy: i > 1 ? guards[i % 3].id : null, checkOutBy: i > 2 ? guards[i % 3].id : null, - checkInAt: i > 1 ? at(-Math.floor(i / 3), -2) : null, checkOutAt: i > 2 ? at(-Math.floor(i / 3), -1) : null, - createdAt: at(-Math.floor(i / 3), -3), updatedAt: at(-Math.floor(i / 3), -1), - })) - const preApprovals: s.VisitorPreApproval[] = ['Weekend guest', 'Morning newspaper', 'Appliance service'].map((visitorName, i) => ({ - id: demoId(350 + i), apartmentId: apartments[i].id, createdBy: users[i + 1].id, visitorName, visitorPhone: null, - approvalType: i === 1 ? 'ALWAYS' : 'ONE_TIME', code: `DEMO0${i + 1}`, validFrom: at(-1), validUntil: at(7), maxUses: i === 1 ? null : 1, useCount: 0, isActive: true, createdAt: at(-1), - })) - const notices: s.Notice[] = [ - ['Water tank cleaning', 'Water supply will pause tomorrow from 10 AM to noon. Please store enough water beforehand.', 'MAINTENANCE', 'HIGH'], - ['Community potluck this weekend', 'Meet your neighbours in the clubhouse at 6 PM. Bring a favourite dish and join the games.', 'EVENT', 'NORMAL'], - ['Monthly maintenance bills are ready', 'You can view your maintenance bill and payment history in the app.', 'BILLING', 'NORMAL'], - ['Gate entry reminder', 'Please pre-approve your guests to help the gate team welcome them quickly.', 'SECURITY', 'NORMAL'], - ].map(([title, body, category, priority], i) => s.noticeSchema.parse({ - id: demoId(400 + i), title, body, category, priority, attachmentUrl: null, attachmentName: null, - publishedBy: DEMO_ADMIN, publishedAt: at(-i), expiresAt: at(14), readCount: 3, read: true, ...stamp, - })) - const tickets: s.Ticket[] = ['Kitchen tap leaking', 'Lobby light flickering', 'Garden bench repair', 'Staircase cleaning'].map((title, i) => ({ - id: demoId(450 + i), apartmentId: apartments[i].id, raisedBy: users[i + 1].id, title, - description: `${title}. Please arrange a visit from the maintenance team.`, category: (['PLUMBING', 'ELECTRICAL', 'CARPENTRY', 'HOUSEKEEPING'] as const)[i], - priority: i === 0 ? 'HIGH' : 'NORMAL', status: (['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'] as const)[i], - assignedTo: i ? users[7].id : null, resolutionNote: i > 1 ? 'Work completed and checked with the resident.' : null, - resolvedAt: i > 1 ? at(-1) : null, createdAt: at(-5), updatedAt: at(-1), - })) - const houseHelp: HouseHelpRow[] = ['Lakshmi Devi', 'Sunita Rao', 'Mohan Kumar'].map((name, i) => ({ - id: demoId(500 + i), name, type: (['MAID', 'COOK', 'DRIVER'] as const)[i], phone: null, photoUrl: null, - idProofType: null, idProofNumber: null, idProofUrl: null, isActive: true, registeredBy: DEMO_ADMIN, - ratingAvg: 4.5, reviewCount: 2, trustScore: 75, idVerified: i !== 2, backgroundCheck: i === 2 ? 'PENDING' : 'CLEARED', - incidentCount: 0, verificationLevel: i === 2 ? 'UNVERIFIED' : 'VERIFIED', ...stamp, - })) - const reviews: s.HouseHelpReview[] = houseHelp.flatMap((h, i) => [4, 5].map((rating, j) => ({ - id: demoId(520 + i * 2 + j), houseHelpId: h.id, rating, comment: j ? 'Reliable and punctual.' : 'Helpful and thorough.', createdAt: at(-j - 1), - }))) - const assignments: s.HouseHelpAssignment[] = houseHelp.map((h, i) => ({ id: demoId(540 + i), houseHelpId: h.id, apartmentId: apartments[i].id, assignedBy: DEMO_ADMIN, createdAt: at(-30) })) - const attendance: (s.HouseHelpAttendanceRow & { id: string })[] = Array.from({ length: 21 }, (_, i) => ({ - id: demoId(550 + i), houseHelpId: houseHelp[i % 3].id, helpName: houseHelp[i % 3].name, type: houseHelp[i % 3].type, - apartment: `${apartments[i % 3].tower}-${apartments[i % 3].apartmentNo}`, checkInAt: at(-Math.floor(i / 3), -3), checkOutAt: i === 0 ? null : at(-Math.floor(i / 3), -1), - })) - const vehicles: s.Vehicle[] = apartments.slice(0, 6).map((a, i) => ({ - id: demoId(600 + i), apartmentId: a.id, registeredBy: DEMO_ADMIN, registrationNumber: `DEMO${2000 + i}`, - type: i % 2 ? 'SCOOTER' : 'CAR', make: i % 2 ? 'City scooter' : 'Family car', color: i % 2 ? 'Blue' : 'White', isActive: true, ...stamp, - })) - const parking: ParkingSlotRow[] = Array.from({ length: 10 }, (_, i) => ({ - id: demoId(650 + i), slotNumber: i > 6 ? `V-${i - 6}` : `P-${i + 1}`, type: i > 6 ? 'OPEN' : 'COVERED', - apartmentId: i < 6 ? apartments[i].id : null, apartment: i < 6 ? `${apartments[i].tower}-${apartments[i].apartmentNo}` : null, - isTemporary: false, assignedUntil: null, assignedBy: i < 6 ? DEMO_ADMIN : null, assignedAt: i < 6 ? at(-30) : null, - isVisitor: i > 6, occupiedByEntryId: i === 7 ? visitors[2].id : null, occupiedAt: i === 7 ? visitors[2].checkInAt : null, - notes: null, isActive: true, ...stamp, - })) - const accounts: s.Account[] = s.DEFAULT_CHART_OF_ACCOUNTS.map((a, i, all) => ({ - id: demoId(700 + i), code: a.code, name: a.name, type: a.type, parentId: a.parentCode ? demoId(700 + all.findIndex(p => p.code === a.parentCode)) : null, - isGroup: a.isGroup ?? false, isMutual: a.isMutual ?? null, isActive: true, createdAt: at(-90), - })) - const bills: s.MaintenanceBill[] = [] - const payments: s.Payment[] = [] - for (let month = 0; month < 3; month++) { - const issued = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - month, 1)).toISOString() - const period = issued.slice(0, 7) - apartments.forEach((a, i) => { - const id = demoId(800 + month * 12 + i) - const paid = (month === 0 && i % 3 === 0) || (month === 1 && i === 0) ? 0 : month === 0 && i % 3 === 1 ? 200000 : 450000 - bills.push({ - id, apartmentId: a.id, apartment: `${a.tower}-${a.apartmentNo}`, type: 'MONTHLY', title: `Maintenance ${period}`, - periodMonth: period, subtotal: 450000, taxAmount: 0, totalAmount: 450000, paidAmount: paid, status: s.billStatusFor(450000, paid), - dueDate: s.dueDateForPeriod(period, 10), issuedAt: issued, createdBy: DEMO_ADMIN, createdAt: issued, updatedAt: issued, - lineItems: [{ id: demoId(900 + month * 12 + i), billId: id, description: 'Monthly maintenance', amount: 450000, taxRatePct: 0, taxAmount: 0, createdAt: issued }], - }) - if (paid) payments.push({ id: demoId(1000 + month * 12 + i), billId: id, apartmentId: a.id, amount: paid, - method: i % 2 ? 'UPI' : 'BANK_TRANSFER', reference: `DEMO-PAY-${month}-${i}`, notes: null, paidAt: issued, - recordedBy: DEMO_ADMIN, createdAt: issued }) - }) - } - const vendors: s.Vendor[] = ['Green Garden Services', 'Bright Lift Care', 'Community Security'].map((name, i) => ({ - id: demoId(1100 + i), name, category: ['Gardening', 'Repairs', 'Security'][i], pan: null, gstin: null, contact: null, bankAccount: null, isActive: true, createdAt: at(-40), - })) - const expenses: (s.Expense & { tdsSection?: s.TdsSection })[] = vendors.map((v, i) => ({ - id: demoId(1150 + i), vendorId: v.id, vendor: v.name, accountId: accounts.find(a => a.code === ['5000', '5040', '5010'][i])!.id, - account: ['Housekeeping', 'Repairs & Maintenance', 'Security'][i], amount: [800000, 1200000, 1800000][i], taxAmount: 0, - status: i === 1 ? 'PAYABLE' : 'PAID', description: ['Garden upkeep', 'Lift maintenance', 'Gate staffing'][i], billRef: `DEMO-INV-${i + 1}`, - method: i === 1 ? null : 'BANK_TRANSFER', paidAt: i === 1 ? null : at(-3), attachmentUrl: null, recordedBy: DEMO_ADMIN, - createdAt: at(-5), tdsAmount: [16000, 24000, 36000][i], tdsSection: 'SEC_194C', - })) - return { - society: { id: demoId(1200), name: 'Green Valley Demo Society', address: '12 Sample Garden Road', city: 'Bengaluru', state: 'Karnataka', pincode: '560001', gstin: null, ...stamp } satisfies s.SocietyConfig, - billConfig: { id: demoId(1201), dueDayOfMonth: 10, lineItems: [{ description: 'Monthly maintenance', amount: 450000, taxRatePct: 0 }], interestEnabled: true, interestRatePct: 18, gracePeriodDays: 15, updatedBy: DEMO_ADMIN, updatedAt: at() } satisfies s.BillConfig, - apartments, users, guards, duty, devices, visitors, preApprovals, notices, tickets, houseHelp, reviews, assignments, attendance, vehicles, parking, accounts, bills, payments, vendors, expenses, - } -} - -export type DemoData = ReturnType +export { createDemoData, demoId, DEMO_ADMIN, type DemoData } from '@opensociety/shared/demo' diff --git a/packages/shared/package.json b/packages/shared/package.json index 2851b2a..1977e96 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -9,6 +9,10 @@ ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" + }, + "./demo": { + "types": "./dist/demo.d.ts", + "default": "./dist/demo.js" } }, "scripts": { diff --git a/packages/shared/src/demo.ts b/packages/shared/src/demo.ts new file mode 100644 index 0000000..88bbe16 --- /dev/null +++ b/packages/shared/src/demo.ts @@ -0,0 +1,136 @@ +import * as s from './index' + +type HouseHelpRow = s.HouseHelp & { + ratingAvg: number | null + reviewCount: number + trustScore: number + idVerified: boolean + backgroundCheck: s.BackgroundCheckStatus + incidentCount: number + verificationLevel: s.VerificationLevel +} +type ParkingSlotRow = s.ParkingSlot & { apartment: string | null } + +export const demoId = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}` +export const DEMO_ADMIN = demoId(100) + +export function createDemoData(now = new Date()) { + const at = (days = 0, hours = 0) => new Date(now.getTime() + days * 86400000 + hours * 3600000).toISOString() + const stamp = { createdAt: at(-60), updatedAt: at() } + const apartments: s.Apartment[] = Array.from({ length: 12 }, (_, i) => ({ + id: demoId(i + 1), tower: i < 6 ? 'A' : 'B', apartmentNo: `${Math.floor(i % 6 / 2) + 1}0${i % 2 + 1}`, + floor: Math.floor(i % 6 / 2) + 1, bhkType: i < 6 ? '2BHK' : '3BHK', isActive: true, ...stamp, + })) + const names = ['Demo Admin', 'Priya Sharma', 'Arjun Rao', 'Meera Shah', 'Kabir Das', 'Nisha Patel', 'Ravi Kumar', 'Asha Iyer'] + const users: s.User[] = names.map((name, i) => ({ + id: demoId(100 + i), clerkId: `demo_${i}`, name, email: `resident${i}@example.com`, phone: null, + role: i === 0 ? 'ADMIN' : i === 7 ? 'STAFF' : 'RESIDENT', status: i === 5 || i === 6 ? 'PENDING' : 'APPROVED', isActive: true, ...stamp, + })) + const guards: s.Guard[] = ['Ramesh Singh', 'Suresh Kumar', 'Anita Devi'].map((name, i) => ({ + id: demoId(200 + i), name, userId: null, phone: null, employeeCode: `G-00${i + 1}`, isActive: true, ...stamp, + })) + const duty: s.GuardDutySession[] = Array.from({ length: 9 }, (_, i) => ({ + id: demoId(220 + i), guardId: guards[i % 3].id, guardName: guards[i % 3].name, + clockInAt: at(-Math.floor(i / 3), -4), clockOutAt: i < 2 ? null : at(-Math.floor(i / 3), -1), + clockInLat: null, clockInLng: null, clockOutLat: null, clockOutLng: null, createdAt: at(-Math.floor(i / 3), -4), + })) + const devices: s.GuardDevice[] = guards.map((g, i) => ({ + id: demoId(240 + i), guardId: g.id, deviceId: `demo-gate-${i}`, model: 'Demo gate phone', boundAt: at(-10), lastActiveAt: at(0, -1), revokedAt: null, + })) + const visitors: s.VisitorEntry[] = Array.from({ length: 24 }, (_, i) => ({ + id: demoId(300 + i), clientId: null, apartmentId: apartments[i % 12].id, preApprovalId: null, + visitorName: ['Aarav Mehta', 'Grocery delivery', 'Diya Kapoor', 'Lift technician'][i % 4], visitorPhone: null, + type: (['GUEST', 'DELIVERY', 'GUEST', 'SERVICE'] as const)[i % 4], + status: i === 0 ? 'PENDING' : i === 1 ? 'APPROVED' : i === 2 ? 'ENTERED' : 'EXITED', + purpose: ['Family visit', 'Weekly groceries', 'Evening visit', 'Scheduled service'][i % 4], + vehicleNumber: i % 2 ? null : `DEMO${1000 + i}`, photoUrl: null, approvedBy: i ? DEMO_ADMIN : null, deniedReason: null, + checkInBy: i > 1 ? guards[i % 3].id : null, checkOutBy: i > 2 ? guards[i % 3].id : null, + checkInAt: i > 1 ? at(-Math.floor(i / 3), -2) : null, checkOutAt: i > 2 ? at(-Math.floor(i / 3), -1) : null, + createdAt: at(-Math.floor(i / 3), -3), updatedAt: at(-Math.floor(i / 3), -1), + })) + const preApprovals: s.VisitorPreApproval[] = ['Weekend guest', 'Morning newspaper', 'Appliance service'].map((visitorName, i) => ({ + id: demoId(350 + i), apartmentId: apartments[i].id, createdBy: users[i + 1].id, visitorName, visitorPhone: null, + approvalType: i === 1 ? 'ALWAYS' : 'ONE_TIME', code: `DEMO0${i + 1}`, validFrom: at(-1), validUntil: at(7), maxUses: i === 1 ? null : 1, useCount: 0, isActive: true, createdAt: at(-1), + })) + const notices: s.Notice[] = [ + ['Water tank cleaning', 'Water supply will pause tomorrow from 10 AM to noon. Please store enough water beforehand.', 'MAINTENANCE', 'HIGH'], + ['Community potluck this weekend', 'Meet your neighbours in the clubhouse at 6 PM. Bring a favourite dish and join the games.', 'EVENT', 'NORMAL'], + ['Monthly maintenance bills are ready', 'You can view your maintenance bill and payment history in the app.', 'BILLING', 'NORMAL'], + ['Gate entry reminder', 'Please pre-approve your guests to help the gate team welcome them quickly.', 'SECURITY', 'NORMAL'], + ].map(([title, body, category, priority], i) => s.noticeSchema.parse({ + id: demoId(400 + i), title, body, category, priority, attachmentUrl: null, attachmentName: null, + publishedBy: DEMO_ADMIN, publishedAt: at(-i), expiresAt: at(14), readCount: 3, read: true, ...stamp, + })) + const tickets: s.Ticket[] = ['Kitchen tap leaking', 'Lobby light flickering', 'Garden bench repair', 'Staircase cleaning'].map((title, i) => ({ + id: demoId(450 + i), apartmentId: apartments[i].id, raisedBy: users[i + 1].id, title, + description: `${title}. Please arrange a visit from the maintenance team.`, category: (['PLUMBING', 'ELECTRICAL', 'CARPENTRY', 'HOUSEKEEPING'] as const)[i], + priority: i === 0 ? 'HIGH' : 'NORMAL', status: (['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'] as const)[i], + assignedTo: i ? users[7].id : null, resolutionNote: i > 1 ? 'Work completed and checked with the resident.' : null, + resolvedAt: i > 1 ? at(-1) : null, createdAt: at(-5), updatedAt: at(-1), + })) + const houseHelp: HouseHelpRow[] = ['Lakshmi Devi', 'Sunita Rao', 'Mohan Kumar'].map((name, i) => ({ + id: demoId(500 + i), name, type: (['MAID', 'COOK', 'DRIVER'] as const)[i], phone: null, photoUrl: null, + idProofType: null, idProofNumber: null, idProofUrl: null, isActive: true, registeredBy: DEMO_ADMIN, + ratingAvg: 4.5, reviewCount: 2, trustScore: 75, idVerified: i !== 2, backgroundCheck: i === 2 ? 'PENDING' : 'CLEARED', + incidentCount: 0, verificationLevel: i === 2 ? 'UNVERIFIED' : 'VERIFIED', ...stamp, + })) + const reviews: s.HouseHelpReview[] = houseHelp.flatMap((h, i) => [4, 5].map((rating, j) => ({ + id: demoId(520 + i * 2 + j), houseHelpId: h.id, rating, comment: j ? 'Reliable and punctual.' : 'Helpful and thorough.', createdAt: at(-j - 1), + }))) + const assignments: s.HouseHelpAssignment[] = houseHelp.map((h, i) => ({ id: demoId(540 + i), houseHelpId: h.id, apartmentId: apartments[i].id, assignedBy: DEMO_ADMIN, createdAt: at(-30) })) + const attendance: (s.HouseHelpAttendanceRow & { id: string })[] = Array.from({ length: 21 }, (_, i) => ({ + id: demoId(550 + i), houseHelpId: houseHelp[i % 3].id, helpName: houseHelp[i % 3].name, type: houseHelp[i % 3].type, + apartment: `${apartments[i % 3].tower}-${apartments[i % 3].apartmentNo}`, checkInAt: at(-Math.floor(i / 3), -3), checkOutAt: i === 0 ? null : at(-Math.floor(i / 3), -1), + })) + const vehicles: s.Vehicle[] = apartments.slice(0, 6).map((a, i) => ({ + id: demoId(600 + i), apartmentId: a.id, registeredBy: DEMO_ADMIN, registrationNumber: `DEMO${2000 + i}`, + type: i % 2 ? 'SCOOTER' : 'CAR', make: i % 2 ? 'City scooter' : 'Family car', color: i % 2 ? 'Blue' : 'White', isActive: true, ...stamp, + })) + const parking: ParkingSlotRow[] = Array.from({ length: 10 }, (_, i) => ({ + id: demoId(650 + i), slotNumber: i > 6 ? `V-${i - 6}` : `P-${i + 1}`, type: i > 6 ? 'OPEN' : 'COVERED', + apartmentId: i < 6 ? apartments[i].id : null, apartment: i < 6 ? `${apartments[i].tower}-${apartments[i].apartmentNo}` : null, + isTemporary: false, assignedUntil: null, assignedBy: i < 6 ? DEMO_ADMIN : null, assignedAt: i < 6 ? at(-30) : null, + isVisitor: i > 6, occupiedByEntryId: i === 7 ? visitors[2].id : null, occupiedAt: i === 7 ? visitors[2].checkInAt : null, + notes: null, isActive: true, ...stamp, + })) + const accounts: s.Account[] = s.DEFAULT_CHART_OF_ACCOUNTS.map((a, i, all) => ({ + id: demoId(700 + i), code: a.code, name: a.name, type: a.type, parentId: a.parentCode ? demoId(700 + all.findIndex(p => p.code === a.parentCode)) : null, + isGroup: a.isGroup ?? false, isMutual: a.isMutual ?? null, isActive: true, createdAt: at(-90), + })) + const bills: s.MaintenanceBill[] = [] + const payments: s.Payment[] = [] + for (let month = 0; month < 3; month++) { + const issued = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - month, 1)).toISOString() + const period = issued.slice(0, 7) + apartments.forEach((a, i) => { + const id = demoId(800 + month * 12 + i) + const paid = (month === 0 && i % 3 === 0) || (month === 1 && i === 0) ? 0 : month === 0 && i % 3 === 1 ? 200000 : 450000 + bills.push({ + id, apartmentId: a.id, apartment: `${a.tower}-${a.apartmentNo}`, type: 'MONTHLY', title: `Maintenance ${period}`, + periodMonth: period, subtotal: 450000, taxAmount: 0, totalAmount: 450000, paidAmount: paid, status: s.billStatusFor(450000, paid), + dueDate: s.dueDateForPeriod(period, 10), issuedAt: issued, createdBy: DEMO_ADMIN, createdAt: issued, updatedAt: issued, + lineItems: [{ id: demoId(900 + month * 12 + i), billId: id, description: 'Monthly maintenance', amount: 450000, taxRatePct: 0, taxAmount: 0, createdAt: issued }], + }) + if (paid) payments.push({ id: demoId(1000 + month * 12 + i), billId: id, apartmentId: a.id, amount: paid, + method: i % 2 ? 'UPI' : 'BANK_TRANSFER', reference: `DEMO-PAY-${month}-${i}`, notes: null, paidAt: issued, + recordedBy: DEMO_ADMIN, createdAt: issued }) + }) + } + const vendors: s.Vendor[] = ['Green Garden Services', 'Bright Lift Care', 'Community Security'].map((name, i) => ({ + id: demoId(1100 + i), name, category: ['Gardening', 'Repairs', 'Security'][i], pan: null, gstin: null, contact: null, bankAccount: null, isActive: true, createdAt: at(-40), + })) + const expenses: (s.Expense & { tdsSection?: s.TdsSection })[] = vendors.map((v, i) => ({ + id: demoId(1150 + i), vendorId: v.id, vendor: v.name, accountId: accounts.find(a => a.code === ['5000', '5040', '5010'][i])!.id, + account: ['Housekeeping', 'Repairs & Maintenance', 'Security'][i], amount: [800000, 1200000, 1800000][i], taxAmount: 0, + status: i === 1 ? 'PAYABLE' : 'PAID', description: ['Garden upkeep', 'Lift maintenance', 'Gate staffing'][i], billRef: `DEMO-INV-${i + 1}`, + method: i === 1 ? null : 'BANK_TRANSFER', paidAt: i === 1 ? null : at(-3), attachmentUrl: null, recordedBy: DEMO_ADMIN, + createdAt: at(-5), tdsAmount: [16000, 24000, 36000][i], tdsSection: 'SEC_194C', + })) + return { + society: { id: demoId(1200), name: 'Green Valley Demo Society', address: '12 Sample Garden Road', city: 'Bengaluru', state: 'Karnataka', pincode: '560001', gstin: null, ...stamp } satisfies s.SocietyConfig, + billConfig: { id: demoId(1201), dueDayOfMonth: 10, lineItems: [{ description: 'Monthly maintenance', amount: 450000, taxRatePct: 0 }], interestEnabled: true, interestRatePct: 18, gracePeriodDays: 15, updatedBy: DEMO_ADMIN, updatedAt: at() } satisfies s.BillConfig, + apartments, users, guards, duty, devices, visitors, preApprovals, notices, tickets, houseHelp, reviews, assignments, attendance, vehicles, parking, accounts, bills, payments, vendors, expenses, + } +} + +export type DemoData = ReturnType From d5609c4198653c2b5761bd00349aa305d6737c54 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:43:12 +0530 Subject: [PATCH 09/14] Model resident and guard visitor flows in the phone demo --- apps/mobile/lib/demo/store.ts | 51 +++++++++++++++++++ apps/mobile/lib/demo/visitors.test.ts | 56 +++++++++++++++++++++ apps/mobile/lib/demo/visitors.ts | 72 +++++++++++++++++++++++++++ apps/mobile/package.json | 6 ++- pnpm-lock.yaml | 3 ++ 5 files changed, 186 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/lib/demo/store.ts create mode 100644 apps/mobile/lib/demo/visitors.test.ts create mode 100644 apps/mobile/lib/demo/visitors.ts diff --git a/apps/mobile/lib/demo/store.ts b/apps/mobile/lib/demo/store.ts new file mode 100644 index 0000000..a93b1a1 --- /dev/null +++ b/apps/mobile/lib/demo/store.ts @@ -0,0 +1,51 @@ +import { createDemoData, demoId } from '@opensociety/shared/demo' +import type { HouseHelpEntry } from '@opensociety/shared' +import type { apiClient } from '../../api/client' + +export type MobileApi = typeof apiClient +export type DemoRole = 'resident' | 'guard' +export type DemoMethods = { [K in keyof T]: T[K] extends (...args: infer A) => Promise ? (...args: A) => R : never } + +// Demo records contain only JSON values. This also works on Hermes without +// relying on browser globals such as structuredClone or crypto.randomUUID. +export function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T } +export function find(rows: T[], id: string): T { + const row = rows.find(item => item.id === id) + if (!row) throw new Error('Demo record not found.') + return row +} +export const nowIso = () => new Date().toISOString() + +export function createMobileDemoStore() { + const data = createDemoData() + const apartmentId = data.apartments[0].id + const residentId = data.users[1].id + const guardId = data.guards[0].id + data.visitors.slice(0, 4).forEach(v => { v.apartmentId = apartmentId }) + data.tickets.forEach(ticket => { ticket.apartmentId = apartmentId; ticket.raisedBy = residentId }) + data.notices.forEach((notice, i) => { notice.read = i > 1 }) + const entries: HouseHelpEntry[] = data.attendance.map(row => ({ + ...row, apartmentId: data.assignments.find(a => a.houseHelpId === row.houseHelpId)?.apartmentId ?? null, + checkInBy: guardId, checkOutBy: row.checkOutAt ? guardId : null, createdAt: row.checkInAt, + })) + let sequence = 2000 + return { + data, apartmentId, residentId, guardId, entries, + newRecord: () => ({ id: demoId(sequence++), createdAt: nowIso(), updatedAt: nowIso() }), + } +} +export type MobileDemoStore = ReturnType + +export function scope(store: MobileDemoStore, role: DemoRole) { + return { + requireRole(expected: DemoRole) { + if (role !== expected) throw new Error(`Switch to the ${expected} demo to try this action.`) + }, + apartment(id: string) { + const row = find(store.data.apartments, id) + if (role === 'resident' && id !== store.apartmentId) throw new Error('Choose your demo apartment.') + return row + }, + visible(id: string) { return role === 'guard' || id === store.apartmentId }, + } +} diff --git a/apps/mobile/lib/demo/visitors.test.ts b/apps/mobile/lib/demo/visitors.test.ts new file mode 100644 index 0000000..5442578 --- /dev/null +++ b/apps/mobile/lib/demo/visitors.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { visitorEntrySchema, visitorPreApprovalSchema } from '@opensociety/shared' +import { createMobileDemoStore } from './store' +import { demoVisitors } from './visitors' + +describe('phone demo visitor workflow', () => { + it('shares registrations and approvals between roles within one sandbox', () => { + const store = createMobileDemoStore() + const guard = demoVisitors(store, 'guard') + const resident = demoVisitors(store, 'resident') + const entry = guard.createVisitor({ apartmentId: store.apartmentId, visitorName: 'Demo guest', type: 'GUEST' }) + expect(visitorEntrySchema.parse(entry).status).toBe('PENDING') + expect(resident.listVisitors('PENDING').some(v => v.id === entry.id)).toBe(true) + expect(resident.approveVisitor(entry.id).status).toBe('APPROVED') + expect(guard.checkInVisitor(entry.id).status).toBe('ENTERED') + expect(guard.checkOutVisitor(entry.id).status).toBe('EXITED') + expect(() => guard.checkInVisitor(entry.id)).toThrow('no longer available') + }) + + it('redeems resident guest codes once and rejects expired codes', () => { + const store = createMobileDemoStore() + const guard = demoVisitors(store, 'guard') + const resident = demoVisitors(store, 'resident') + const approval = resident.createPreApproval({ apartmentId: store.apartmentId, visitorName: 'Invited guest', approvalType: 'ONE_TIME' }) + expect(visitorPreApprovalSchema.safeParse(approval).success).toBe(true) + expect(guard.redeemPreApproval(approval.code.toLowerCase()).status).toBe('ENTERED') + expect(() => guard.redeemPreApproval(approval.code)).toThrow() + store.data.preApprovals[1].validUntil = '2000-01-01T00:00:00Z' + expect(() => guard.redeemPreApproval(store.data.preApprovals[1].code)).toThrow() + }) + + it('keeps visitors scoped to the resident and enforces role actions', () => { + const store = createMobileDemoStore() + const resident = demoVisitors(store, 'resident') + const guard = demoVisitors(store, 'guard') + expect(resident.listVisitors().every(v => v.apartmentId === store.apartmentId)).toBe(true) + const entry = guard.createVisitor({ apartmentId: store.data.apartments[1].id, visitorName: 'Another flat', type: 'GUEST' }) + expect(() => resident.approveVisitor(entry.id)).toThrow('demo apartment') + expect(() => guard.approveVisitor(entry.id)).toThrow('resident') + expect(() => resident.createVisitor({ apartmentId: store.apartmentId, visitorName: 'Guest', type: 'GUEST' })).toThrow('guard') + const pending = resident.listVisitors('PENDING')[0] + expect(() => resident.denyVisitor(pending.id, '')).toThrow() + expect(resident.denyVisitor(pending.id, 'Not expected').status).toBe('DENIED') + }) + + it('deduplicates a retried registration and starts each demo with fresh records', () => { + const store = createMobileDemoStore() + const guard = demoVisitors(store, 'guard') + const input = { apartmentId: store.apartmentId, visitorName: 'Retried guest', type: 'GUEST' as const, + clientId: '00000000-0000-4000-8000-999999999999' } + const first = guard.createVisitor(input) + expect(guard.createVisitor(input).id).toBe(first.id) + expect(guard.listVisitors().filter(v => v.clientId === input.clientId)).toHaveLength(1) + expect(demoVisitors(createMobileDemoStore(), 'guard').listVisitors().some(v => v.visitorName === input.visitorName)).toBe(false) + }) +}) diff --git a/apps/mobile/lib/demo/visitors.ts b/apps/mobile/lib/demo/visitors.ts new file mode 100644 index 0000000..293f9d0 --- /dev/null +++ b/apps/mobile/lib/demo/visitors.ts @@ -0,0 +1,72 @@ +import * as s from '@opensociety/shared' +import { find, nowIso, scope, type DemoMethods, type DemoRole, type MobileApi, type MobileDemoStore } from './store' + +type VisitorApi = Pick + +export function demoVisitors(store: MobileDemoStore, role: DemoRole): DemoMethods { + const { data: d, newRecord } = store + const access = scope(store, role) + const action = (id: string, name: s.VisitorAction, reason?: string) => { + access.requireRole(name === 'approve' || name === 'deny' ? 'resident' : 'guard') + const row = find(d.visitors, id) + access.apartment(row.apartmentId) + if (!s.canTransition(name, row.status)) throw new Error('This visitor action is no longer available.') + if (name === 'deny') s.denyVisitorSchema.parse({ reason }) + row.status = s.VISITOR_TRANSITIONS[name].to + row.updatedAt = nowIso() + if (name === 'approve') row.approvedBy = store.residentId + if (name === 'deny') row.deniedReason = reason ?? null + if (name === 'checkin') { row.checkInAt = nowIso(); row.checkInBy = store.guardId } + if (name === 'checkout') { row.checkOutAt = nowIso(); row.checkOutBy = store.guardId } + return row + } + const visitor = (input: s.CreateVisitorEntry): s.VisitorEntry => ({ + ...newRecord(), clientId: null, visitorPhone: null, purpose: null, vehicleNumber: null, photoUrl: null, + ...input, status: 'PENDING', preApprovalId: null, approvedBy: null, deniedReason: null, + checkInBy: null, checkInAt: null, checkOutBy: null, checkOutAt: null, + }) + return { + listVisitors: status => d.visitors.filter(v => access.visible(v.apartmentId) && (!status || v.status === status)), + createVisitor: body => { + access.requireRole('guard') + const input = s.createVisitorEntrySchema.parse(body) + access.apartment(input.apartmentId) + const existing = input.clientId && d.visitors.find(v => v.clientId === input.clientId) + if (existing) return existing + const row = visitor(input) + d.visitors.unshift(row) + return row + }, + approveVisitor: id => action(id, 'approve'), + denyVisitor: (id, reason) => action(id, 'deny', reason), + checkInVisitor: id => action(id, 'checkin'), + checkOutVisitor: id => action(id, 'checkout'), + createPreApproval: body => { + access.requireRole('resident') + const input = s.createPreApprovalSchema.parse(body) + access.apartment(input.apartmentId) + const record = newRecord() + const row: s.VisitorPreApproval = { + ...record, visitorPhone: null, validUntil: null, maxUses: null, ...input, createdBy: store.residentId, + code: `DEMO${record.id.slice(-4)}`, validFrom: nowIso(), useCount: 0, isActive: true, + } + d.preApprovals.unshift(row) + return row + }, + redeemPreApproval: code => { + access.requireRole('guard') + const pa = d.preApprovals.find(p => p.code === code.trim().toUpperCase()) + if (!pa) throw new Error('Invalid demo visitor code.') + const error = s.preApprovalRedeemError({ ...pa, validUntilMs: pa.validUntil ? Date.parse(pa.validUntil) : null }, Date.now()) + if (error) throw new Error(error) + const row: s.VisitorEntry = { + ...visitor({ apartmentId: pa.apartmentId, visitorName: pa.visitorName, type: 'GUEST' }), + visitorPhone: pa.visitorPhone, preApprovalId: pa.id, approvedBy: pa.createdBy, status: 'ENTERED', + checkInBy: store.guardId, checkInAt: nowIso(), purpose: 'Pre-approved visit', + } + pa.useCount++ + d.visitors.unshift(row) + return row + }, + } +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index a5b15ab..5765e08 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -8,7 +8,8 @@ "ios": "expo start --ios", "web": "expo start --web", "check-types": "tsc --noEmit", - "lint": "eslint ." + "lint": "eslint .", + "test": "vitest run" }, "dependencies": { "@clerk/clerk-expo": "^2.19.31", @@ -55,7 +56,8 @@ "lightningcss": "1.30.1", "postcss": "^8.5.19", "tailwindcss": "^4.1.18", - "typescript": "~6.0.3" + "typescript": "~6.0.3", + "vitest": "^3.0.5" }, "private": true } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 710900c..2bab516 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -200,6 +200,9 @@ importers: typescript: specifier: ~6.0.3 version: 6.0.3 + vitest: + specifier: ^3.0.5 + version: 3.2.4(@types/debug@4.1.13)(@types/node@22.18.11)(jiti@2.7.0)(jsdom@27.4.0(@noble/hashes@1.8.0)(bufferutil@4.1.0)(utf-8-validate@6.0.6))(lightningcss@1.30.1)(terser@5.46.0)(tsx@4.20.6)(yaml@2.8.2) apps/web: dependencies: From b7f1c923f6a95daa250f32b627cf3f75fcdac37c Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:44:33 +0530 Subject: [PATCH 10/14] Add offline data and actions for phone demos --- apps/mobile/lib/demo/client.test.ts | 91 +++++++++++++++ apps/mobile/lib/demo/client.ts | 167 ++++++++++++++++++++++++++++ 2 files changed, 258 insertions(+) create mode 100644 apps/mobile/lib/demo/client.test.ts create mode 100644 apps/mobile/lib/demo/client.ts diff --git a/apps/mobile/lib/demo/client.test.ts b/apps/mobile/lib/demo/client.test.ts new file mode 100644 index 0000000..15d95e5 --- /dev/null +++ b/apps/mobile/lib/demo/client.test.ts @@ -0,0 +1,91 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import * as s from '@opensociety/shared' +import { createMobileDemoStore } from './store' +import { createMobileDemoClient } from './client' +import { setAuthTokenGetter } from '../../api/client' + +function sandbox() { + const store = createMobileDemoStore() + return { store, resident: createMobileDemoClient(store, 'resident'), guard: createMobileDemoClient(store, 'guard') } +} + +afterEach(() => { vi.unstubAllGlobals(); setAuthTokenGetter(null) }) + +describe('phone demo API', () => { + it('fills every screen without contacting the API or requesting credentials', async () => { + const fetch = vi.fn(() => { throw new Error('Network forbidden') }) + const token = vi.fn(async () => 'real-session-token') + vi.stubGlobal('fetch', fetch) + vi.stubGlobal('structuredClone', undefined) + vi.stubGlobal('crypto', undefined) + setAuthTokenGetter(token) + const { resident, guard, store } = sandbox() + const lists = await Promise.all([ + resident.listApartments(), resident.listMyApartments(), resident.listMyResidents(), resident.listVisitors(), + resident.listNotices(), resident.listTickets(), resident.listBills(), resident.listPayments(), + resident.listHouseHelp(), resident.listHouseHelpForApartment(store.apartmentId), resident.listVehicles(), + guard.listGuards(), guard.listActiveDuty(), guard.listHouseHelpEntries({ active: true }), + ]) + for (const rows of lists) expect(rows.length).toBeGreaterThan(0) + expect((await resident.getApartmentStatement(store.apartmentId)).closing).toBe(900000) + expect((await guard.verifyVehicle('demo 2000')).parkingSlots).toHaveLength(1) + expect((await resident.getSociety())?.name).toContain('Demo') + await expect(resident.fetchUploadObjectUrl('/uploads/real-file')).rejects.toThrow('not included') + expect(fetch).not.toHaveBeenCalled() + expect(token).not.toHaveBeenCalled() + }) + + it('clones responses and keeps independent demo sessions separate', async () => { + const { resident, store } = sandbox() + const notices = await resident.listNotices() + notices[0].title = 'Changed outside the sandbox' + expect((await resident.listNotices())[0].title).not.toBe(notices[0].title) + await resident.markNoticeRead(notices[0].id) + await resident.markNoticeRead(notices[0].id) + expect((await resident.listNotices())[0]).toMatchObject({ read: true, readCount: 4 }) + expect((await sandbox().resident.listNotices())[0].read).toBe(false) + const ticket = await resident.createTicket({ apartmentId: store.apartmentId, title: 'Fan repair', + description: 'The ceiling fan needs repair.', category: 'ELECTRICAL', priority: 'NORMAL' }) + expect(s.ticketSchema.parse(ticket).raisedBy).toBe(store.residentId) + expect((await resident.listTickets('OPEN')).some(t => t.id === ticket.id)).toBe(true) + }) + + it('updates vehicles and gate verification together', async () => { + const { resident, guard, store } = sandbox() + const vehicle = await resident.createVehicle({ apartmentId: store.apartmentId, registrationNumber: 'demo 9999', type: 'CAR' }) + expect(s.vehicleSchema.parse(vehicle).registrationNumber).toBe('DEMO9999') + expect((await guard.verifyVehicle('demo-9999')).registered).toBe(true) + await resident.updateVehicle(vehicle.id, { isActive: false }) + expect((await guard.verifyVehicle('demo9999')).registered).toBe(false) + await expect(resident.createVehicle({ apartmentId: store.apartmentId, registrationNumber: 'DEMO9999', type: 'CAR' })).rejects.toThrow('already registered') + await expect(resident.updateVehicle(store.data.vehicles[1].id, { isActive: false })).rejects.toThrow('demo apartment') + }) + + it('supports assignments, ratings and house-help check-in and checkout', async () => { + const { resident, guard, store } = sandbox() + const helper = (await resident.listHouseHelp())[1] + const assignment = await resident.assignHouseHelp(helper.id, store.apartmentId) + expect((await resident.assignHouseHelp(helper.id, store.apartmentId)).id).toBe(assignment.id) + await resident.rateHouseHelp(helper.id, { rating: 1 }) + expect((await resident.listHouseHelpForApartment(store.apartmentId)).find(h => h.id === helper.id)?.reviewCount).toBe(3) + const entry = await guard.checkInHouseHelp(helper.id, { apartmentId: store.apartmentId }) + expect(s.houseHelpEntrySchema.safeParse(entry).success).toBe(true) + await expect(guard.checkInHouseHelp(helper.id)).rejects.toThrow('Already checked in') + await guard.checkOutHouseHelpEntry(entry.id) + expect(await guard.listHouseHelpEntries({ active: true, houseHelpId: helper.id })).toHaveLength(0) + await resident.removeHouseHelpAssignment(helper.id, store.apartmentId) + expect((await resident.listHouseHelpForApartment(store.apartmentId)).some(h => h.id === helper.id)).toBe(false) + }) + + it('runs guard shifts and rejects duplicate clock-ins', async () => { + const { guard, resident, store } = sandbox() + const active = await guard.listActiveDuty() + await expect(guard.clockInGuard(store.guardId)).rejects.toThrow('Already on duty') + await guard.clockOutGuard(active[0].id) + expect(await guard.listActiveDuty()).toHaveLength(0) + const shift = await guard.clockInGuard(store.guardId) + expect(s.guardDutySessionSchema.safeParse(shift).success).toBe(true) + await expect(resident.clockOutGuard(shift.id)).rejects.toThrow('guard') + await expect(guard.listBills()).rejects.toThrow('resident') + }) +}) diff --git a/apps/mobile/lib/demo/client.ts b/apps/mobile/lib/demo/client.ts new file mode 100644 index 0000000..28e97ff --- /dev/null +++ b/apps/mobile/lib/demo/client.ts @@ -0,0 +1,167 @@ +import * as s from '@opensociety/shared' +import { clone, find, nowIso, scope, type DemoMethods, type DemoRole, type MobileApi, type MobileDemoStore } from './store' +import { demoVisitors } from './visitors' + +export function createMobileDemoClient(store: MobileDemoStore, role: DemoRole): MobileApi { + const { data: d, newRecord } = store + const access = scope(store, role) + const helpRow = (id: string) => { + const h = find(d.houseHelp, id) + const ratings = s.summarizeRatings(d.reviews.filter(r => r.houseHelpId === id).map(r => r.rating)) + return { ...h, ratingAvg: ratings.average, reviewCount: ratings.count, + verificationLevel: s.verificationLevel(h.idVerified, h.backgroundCheck), + trustScore: s.computeTrustScore({ ratingTrust: ratings.trustScore, idVerified: h.idVerified, + backgroundCheck: h.backgroundCheck, incidentCount: h.incidentCount, + tenureDays: Math.max(0, (Date.now() - Date.parse(h.createdAt)) / 86400000) }) } + } + const methods: DemoMethods = { + ...demoVisitors(store, role), + health: () => ({ status: 'ok' }), + getSociety: () => d.society, + listApartments: () => d.apartments.filter(a => access.visible(a.id)), + listMyApartments: () => role === 'resident' ? [find(d.apartments, store.apartmentId)] : [], + listMyResidents: () => role === 'resident' ? d.users.slice(1, 3).map((u, i) => ({ + apartmentId: store.apartmentId, userId: u.id, name: u.name, relation: i ? 'FAMILY' : 'OWNER', + })) : [], + listNotices: () => d.notices, + markNoticeRead: id => { + const row = find(d.notices, id) + if (!row.read) { row.read = true; row.readCount = (row.readCount ?? 0) + 1 } + return { ok: true } + }, + listBills: () => { access.requireRole('resident'); return d.bills.filter(b => b.apartmentId === store.apartmentId) }, + listPayments: () => { access.requireRole('resident'); return d.payments.filter(p => p.apartmentId === store.apartmentId) }, + getApartmentStatement: apartmentId => { + access.requireRole('resident') + const apartment = access.apartment(apartmentId) + return { apartmentId, apartment: `${apartment.tower}-${apartment.apartmentNo}`, ...s.buildStatement([ + ...d.bills.filter(b => b.apartmentId === apartmentId).map(b => ({ date: b.issuedAt, type: 'BILL' as const, + description: b.title, debit: b.totalAmount, credit: 0, ref: b.id })), + ...d.payments.filter(p => p.apartmentId === apartmentId).map(p => ({ date: p.paidAt, type: 'PAYMENT' as const, + description: `Payment (${p.method})`, debit: 0, credit: p.amount, ref: p.id })), + ]) } + }, + listTickets: status => d.tickets.filter(t => access.visible(t.apartmentId) && (!status || t.status === status)), + createTicket: body => { + access.requireRole('resident') + const input = s.createTicketSchema.parse(body) + access.apartment(input.apartmentId) + const row: s.Ticket = { ...newRecord(), ...input, raisedBy: store.residentId, + status: 'OPEN', assignedTo: null, resolutionNote: null, resolvedAt: null } + d.tickets.unshift(row) + return row + }, + listHouseHelp: type => d.houseHelp.filter(h => !type || h.type === type).map(h => helpRow(h.id)), + listHouseHelpForApartment: apartmentId => { + access.apartment(apartmentId) + return d.assignments.filter(a => a.apartmentId === apartmentId).map(a => helpRow(a.houseHelpId)) + }, + rateHouseHelp: (id, body) => { + access.requireRole('resident') + find(d.houseHelp, id) + const input = s.createHouseHelpReviewSchema.parse(body) + const row = { ...newRecord(), houseHelpId: id, comment: null, ...input } + d.reviews.unshift(row) + return { ok: true, id: row.id, rating: row.rating } + }, + assignHouseHelp: (id, apartmentId) => { + access.requireRole('resident') + access.apartment(apartmentId) + find(d.houseHelp, id) + const existing = d.assignments.find(a => a.houseHelpId === id && a.apartmentId === apartmentId) + if (existing) return existing + const row = { ...newRecord(), houseHelpId: id, apartmentId, assignedBy: store.residentId } + d.assignments.push(row) + return row + }, + removeHouseHelpAssignment: (id, apartmentId) => { + access.requireRole('resident') + access.apartment(apartmentId) + const index = d.assignments.findIndex(a => a.houseHelpId === id && a.apartmentId === apartmentId) + if (index === -1) throw new Error('Assignment not found.') + return d.assignments.splice(index, 1)[0] + }, + listHouseHelpEntries: params => store.entries.filter(e => (!params?.active || !e.checkOutAt) + && (!params?.houseHelpId || e.houseHelpId === params.houseHelpId) + && (role === 'guard' || e.apartmentId === store.apartmentId)), + checkInHouseHelp: (id, body = {}) => { + access.requireRole('guard') + const help = find(d.houseHelp, id) + const input = s.checkInHouseHelpSchema.parse(body) + if (input.apartmentId) access.apartment(input.apartmentId) + if (store.entries.some(e => e.houseHelpId === id && !e.checkOutAt)) throw new Error('Already checked in.') + const row: s.HouseHelpEntry = { ...newRecord(), houseHelpId: id, helpName: help.name, type: help.type, + apartmentId: input.apartmentId ?? null, checkInAt: nowIso(), checkInBy: store.guardId, checkOutAt: null, checkOutBy: null } + store.entries.unshift(row) + return row + }, + checkOutHouseHelpEntry: id => { + access.requireRole('guard') + const row = find(store.entries, id) + if (row.checkOutAt) throw new Error('Already checked out.') + row.checkOutAt = nowIso(); row.checkOutBy = store.guardId + return row + }, + listVehicles: apartmentId => d.vehicles.filter(v => access.visible(v.apartmentId) && (!apartmentId || v.apartmentId === apartmentId)), + createVehicle: body => { + access.requireRole('resident') + const input = s.createVehicleSchema.parse(body) + access.apartment(input.apartmentId) + const registrationNumber = s.normalizePlate(input.registrationNumber) + if (d.vehicles.some(v => v.registrationNumber === registrationNumber)) throw new Error('Vehicle already registered.') + const row = { ...newRecord(), make: null, color: null, ...input, registrationNumber, registeredBy: store.residentId, isActive: true } + d.vehicles.push(row) + return row + }, + updateVehicle: (id, body) => { + access.requireRole('resident') + const row = find(d.vehicles, id) + access.apartment(row.apartmentId) + const input = s.updateVehicleSchema.parse(body) + if (input.registrationNumber) { + input.registrationNumber = s.normalizePlate(input.registrationNumber) + if (d.vehicles.some(v => v.id !== id && v.registrationNumber === input.registrationNumber)) throw new Error('Vehicle already registered.') + } + return Object.assign(row, input, { updatedAt: nowIso() }) + }, + verifyVehicle: plate => { + access.requireRole('guard') + plate = s.normalizePlate(plate) + const vehicle = d.vehicles.find(v => v.registrationNumber === plate && v.isActive) + const apartment = vehicle && access.apartment(vehicle.apartmentId) + return { plate, registered: !!vehicle, vehicle: vehicle && apartment ? { + ...vehicle, apartment: `${apartment.tower}-${apartment.apartmentNo}`, + } : null, parkingSlots: vehicle ? d.parking.filter(p => p.apartmentId === vehicle.apartmentId && p.isActive) + .map(p => ({ slotNumber: p.slotNumber, type: p.type })) : [] } + }, + listGuards: () => { access.requireRole('guard'); return d.guards.filter(g => g.id === store.guardId) }, + listActiveDuty: () => { access.requireRole('guard'); return d.duty.filter(duty => duty.guardId === store.guardId && !duty.clockOutAt) }, + clockInGuard: (guardId, coords = {}) => { + access.requireRole('guard') + if (guardId !== store.guardId) throw new Error('Choose your demo guard.') + const guard = find(d.guards, guardId) + const input = s.clockInSchema.parse(coords) + if (d.duty.some(duty => duty.guardId === guardId && !duty.clockOutAt)) throw new Error('Already on duty.') + const row: s.GuardDutySession = { ...newRecord(), guardId, guardName: guard.name, clockInAt: nowIso(), + clockInLat: input.lat ?? null, clockInLng: input.lng ?? null, clockOutAt: null, clockOutLat: null, clockOutLng: null } + d.duty.unshift(row) + return row + }, + clockOutGuard: (id, coords = {}) => { + access.requireRole('guard') + const row = find(d.duty, id) + if (row.guardId !== store.guardId) throw new Error('Choose your demo guard.') + if (row.clockOutAt) throw new Error('Already off duty.') + const input = s.clockOutSchema.parse(coords) + return Object.assign(row, { clockOutAt: nowIso(), clockOutLat: input.lat ?? null, clockOutLng: input.lng ?? null }) + }, + fetchUploadObjectUrl: () => { throw new Error('Attachments are not included in the phone demo.') }, + } + return new Proxy(methods, { + get(target, property: keyof MobileApi) { + const method = target[property] + if (typeof method !== 'function') throw new Error(`Unsupported demo action: ${String(property)}`) + return async (...args: unknown[]) => clone(Reflect.apply(method, target, args)) + }, + }) as unknown as MobileApi +} From 1bcaea60c59dd32ffcb086a34a9ea621601e7663 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:47:53 +0530 Subject: [PATCH 11/14] Bind phone screens to their session API client --- apps/mobile/api/context.tsx | 5 +++++ apps/mobile/app/bills.tsx | 3 ++- apps/mobile/app/duty.tsx | 3 ++- apps/mobile/app/gate.tsx | 3 ++- apps/mobile/app/house-help.tsx | 3 ++- apps/mobile/app/my-house-help.tsx | 6 +++++- apps/mobile/app/my-vehicles.tsx | 3 ++- apps/mobile/app/notices.tsx | 19 ++++++++++--------- apps/mobile/app/pre-approve.tsx | 3 ++- apps/mobile/app/profile.tsx | 3 ++- apps/mobile/app/register.tsx | 3 ++- apps/mobile/app/tickets.tsx | 3 ++- apps/mobile/app/vehicle-gate.tsx | 3 ++- apps/mobile/app/visitor-history.tsx | 3 ++- apps/mobile/app/visitors.tsx | 3 ++- 15 files changed, 44 insertions(+), 22 deletions(-) create mode 100644 apps/mobile/api/context.tsx diff --git a/apps/mobile/api/context.tsx b/apps/mobile/api/context.tsx new file mode 100644 index 0000000..e5e308e --- /dev/null +++ b/apps/mobile/api/context.tsx @@ -0,0 +1,5 @@ +import { createContext, useContext } from 'react' +import { apiClient } from './client' + +export const ApiContext = createContext(apiClient) +export const useApiClient = () => useContext(ApiContext) diff --git a/apps/mobile/app/bills.tsx b/apps/mobile/app/bills.tsx index e9d7933..60d3af2 100644 --- a/apps/mobile/app/bills.tsx +++ b/apps/mobile/app/bills.tsx @@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query' import { ActivityIndicator, ScrollView, View } from 'react-native' import type { BillStatus } from '@opensociety/shared' import { formatPaise } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { cn } from '../lib/utils' import { Text } from '../components/ui/text' @@ -21,6 +21,7 @@ function fmtDate(iso: string | null): string { } export default function Bills() { + const apiClient = useApiClient() const { t } = useT() const bills = useQuery({ queryKey: ['bills'], queryFn: () => apiClient.listBills() }) const payments = useQuery({ queryKey: ['payments'], queryFn: () => apiClient.listPayments() }) diff --git a/apps/mobile/app/duty.tsx b/apps/mobile/app/duty.tsx index 5e6b268..3a99e70 100644 --- a/apps/mobile/app/duty.tsx +++ b/apps/mobile/app/duty.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, FlatList, View } from 'react-native' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { cn } from '../lib/utils' import { Button } from '../components/ui/button' @@ -11,6 +11,7 @@ import { Text } from '../components/ui/text' // duty session marks a guard ON DUTY. (Location capture on native needs // expo-location — added as a follow-up; the API accepts optional coords.) export default function Duty() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const guards = useQuery({ queryKey: ['guards'], queryFn: () => apiClient.listGuards() }) diff --git a/apps/mobile/app/gate.tsx b/apps/mobile/app/gate.tsx index 44acc7a..d993ae9 100644 --- a/apps/mobile/app/gate.tsx +++ b/apps/mobile/app/gate.tsx @@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, FlatList, Modal, Platform, View } from 'react-native' import { CameraView, useCameraPermissions } from 'expo-camera' import { availableVisitorActions, parsePreApprovalQrValue } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useSyncStatus } from '../lib/offline/use-sync-status' import { useT } from '../lib/i18n' import { OfflineBanner } from '../components/offline-banner' @@ -16,6 +16,7 @@ import { Text } from '../components/ui/text' // Guard gate view: the visitors a guard acts on — APPROVED (expected at the // gate) and ENTERED (currently inside) — with check-in / check-out actions. export default function Gate() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const { isOnline } = useSyncStatus() diff --git a/apps/mobile/app/house-help.tsx b/apps/mobile/app/house-help.tsx index e452e60..0ed4b40 100644 --- a/apps/mobile/app/house-help.tsx +++ b/apps/mobile/app/house-help.tsx @@ -1,7 +1,7 @@ import { useMemo, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, FlatList, View } from 'react-native' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { cn } from '../lib/utils' import { Button } from '../components/ui/button' @@ -12,6 +12,7 @@ import { Text } from '../components/ui/text' // (no resident approval). Each active worker shows their in/out state and the // matching action; an open attendance entry means "currently inside". export default function HouseHelp() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const help = useQuery({ queryKey: ['house-help'], queryFn: () => apiClient.listHouseHelp() }) diff --git a/apps/mobile/app/my-house-help.tsx b/apps/mobile/app/my-house-help.tsx index 8c38b8b..2ea471c 100644 --- a/apps/mobile/app/my-house-help.tsx +++ b/apps/mobile/app/my-house-help.tsx @@ -1,7 +1,8 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native' import type { Apartment } from '@opensociety/shared' -import { apiClient, type HouseHelpWithRating } from '../api/client' +import type { HouseHelpWithRating } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Text } from '../components/ui/text' @@ -9,6 +10,7 @@ import { cn } from '../lib/utils' // Resident view: manage which registered house help serves each of their flats. export default function MyHouseHelp() { + const apiClient = useApiClient() const { t } = useT() const apts = useQuery({ queryKey: ['my-apartments'], queryFn: () => apiClient.listMyApartments() }) const registry = useQuery({ queryKey: ['house-help'], queryFn: () => apiClient.listHouseHelp() }) @@ -47,6 +49,7 @@ export default function MyHouseHelp() { } function StarRating({ help, apartmentKey }: { help: HouseHelpWithRating; apartmentKey: string }) { + const apiClient = useApiClient() const { t } = useT() const qc = useQueryClient() const rate = useMutation({ @@ -77,6 +80,7 @@ function StarRating({ help, apartmentKey }: { help: HouseHelpWithRating; apartme } function ApartmentAssignments({ apartment, registry }: { apartment: Apartment; registry: HouseHelpWithRating[] }) { + const apiClient = useApiClient() const { t } = useT() const qc = useQueryClient() const assigned = useQuery({ diff --git a/apps/mobile/app/my-vehicles.tsx b/apps/mobile/app/my-vehicles.tsx index e6aba60..22bf61e 100644 --- a/apps/mobile/app/my-vehicles.tsx +++ b/apps/mobile/app/my-vehicles.tsx @@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, ScrollView, View } from 'react-native' import type { Apartment, CreateVehicle, VehicleType } from '@opensociety/shared' import { vehicleTypeSchema } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Chip } from '../components/ui/chip' @@ -13,6 +13,7 @@ import { cn } from '../lib/utils' // Resident view: register and manage the vehicles for their own flat(s). export default function MyVehicles() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const apts = useQuery({ queryKey: ['my-apartments'], queryFn: () => apiClient.listMyApartments() }) diff --git a/apps/mobile/app/notices.tsx b/apps/mobile/app/notices.tsx index 06e675b..7f11f66 100644 --- a/apps/mobile/app/notices.tsx +++ b/apps/mobile/app/notices.tsx @@ -3,7 +3,7 @@ import { ActivityIndicator, FlatList, Linking, Pressable, View } from 'react-nat import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { Notice } from '@opensociety/shared' import { noticeMatchesQuery } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Input } from '../components/ui/input' import { Text } from '../components/ui/text' @@ -20,16 +20,17 @@ function isUrgent(priority: Notice['priority']): boolean { return priority === 'HIGH' || priority === 'URGENT' } -async function openAttachment(path: string) { - try { - const url = await apiClient.fetchUploadObjectUrl(path) - await Linking.openURL(url) - } catch { - // best-effort; the attachment simply won't open if the fetch fails +export default function Notices() { + const apiClient = useApiClient() + async function openAttachment(path: string) { + try { + const url = await apiClient.fetchUploadObjectUrl(path) + await Linking.openURL(url) + } catch { + // best-effort; the attachment simply won't open if the fetch fails + } } -} -export default function Notices() { const { t } = useT() const [search, setSearch] = useState('') const { data, isLoading, isError, error } = useQuery({ queryKey: ['notices'], queryFn: () => apiClient.listNotices() }) diff --git a/apps/mobile/app/pre-approve.tsx b/apps/mobile/app/pre-approve.tsx index 50fbdea..15fc6c2 100644 --- a/apps/mobile/app/pre-approve.tsx +++ b/apps/mobile/app/pre-approve.tsx @@ -4,7 +4,7 @@ import { ActivityIndicator, ScrollView, View } from 'react-native' import QRCode from 'react-native-qrcode-svg' import type { VisitorPreApproval } from '@opensociety/shared' import { preApprovalQrValue } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Chip } from '../components/ui/chip' @@ -12,6 +12,7 @@ import { Input } from '../components/ui/input' import { Text } from '../components/ui/text' export default function PreApprove() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const [name, setName] = useState('') diff --git a/apps/mobile/app/profile.tsx b/apps/mobile/app/profile.tsx index 10db7ce..348fe18 100644 --- a/apps/mobile/app/profile.tsx +++ b/apps/mobile/app/profile.tsx @@ -2,7 +2,7 @@ import { useMemo } from 'react' import { ActivityIndicator, ScrollView, View } from 'react-native' import { useQuery } from '@tanstack/react-query' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Text } from '../components/ui/text' @@ -15,6 +15,7 @@ function groupBy(items: T[], key: (item: T) => string): Record { // Resident profile: for each flat the user lives in, its co-residents and the // vehicles registered to it. export default function Profile() { + const apiClient = useApiClient() const { t } = useT() const apts = useQuery({ queryKey: ['my-apartments'], queryFn: () => apiClient.listMyApartments() }) const residents = useQuery({ queryKey: ['my-residents'], queryFn: () => apiClient.listMyResidents() }) diff --git a/apps/mobile/app/register.tsx b/apps/mobile/app/register.tsx index 7b07537..8fe5e90 100644 --- a/apps/mobile/app/register.tsx +++ b/apps/mobile/app/register.tsx @@ -4,7 +4,7 @@ import { useMutation, useQuery } from '@tanstack/react-query' import { ActivityIndicator, ScrollView, View } from 'react-native' import { visitorTypeSchema, type CreateVisitorEntry, type VisitorEntry, type VisitorType } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { CREATE_VISITOR_KEY } from '../lib/offline/mutation-defaults' import { newClientId } from '../lib/offline/optimistic' import { useSyncStatus } from '../lib/offline/use-sync-status' @@ -19,6 +19,7 @@ import { Text } from '../components/ui/text' const TYPES = visitorTypeSchema.options export default function Register() { + const apiClient = useApiClient() const router = useRouter() const { t } = useT() const { isOnline } = useSyncStatus() diff --git a/apps/mobile/app/tickets.tsx b/apps/mobile/app/tickets.tsx index 9c5e691..903822f 100644 --- a/apps/mobile/app/tickets.tsx +++ b/apps/mobile/app/tickets.tsx @@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, ScrollView, View } from 'react-native' import type { TicketCategory, TicketPriority, TicketStatus } from '@opensociety/shared' import { ticketCategorySchema, ticketPrioritySchema } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Chip } from '../components/ui/chip' @@ -20,6 +20,7 @@ const STATUS_COLOR: Record = { } export default function Tickets() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const [title, setTitle] = useState('') diff --git a/apps/mobile/app/vehicle-gate.tsx b/apps/mobile/app/vehicle-gate.tsx index 3be8994..1054842 100644 --- a/apps/mobile/app/vehicle-gate.tsx +++ b/apps/mobile/app/vehicle-gate.tsx @@ -3,7 +3,7 @@ import { ScrollView, View } from 'react-native' import { useMutation } from '@tanstack/react-query' import type { VehicleVerification } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Input } from '../components/ui/input' @@ -12,6 +12,7 @@ import { Text } from '../components/ui/text' // Guard gate tool: type an arriving vehicle's plate to see whether it's a // registered resident vehicle (with owner flat + parking slots) or unknown. export default function VehicleGate() { + const apiClient = useApiClient() const { t } = useT() const [plate, setPlate] = useState('') const verify = useMutation({ mutationFn: (p: string) => apiClient.verifyVehicle(p) }) diff --git a/apps/mobile/app/visitor-history.tsx b/apps/mobile/app/visitor-history.tsx index 14e561e..7cf501d 100644 --- a/apps/mobile/app/visitor-history.tsx +++ b/apps/mobile/app/visitor-history.tsx @@ -3,7 +3,7 @@ import { ActivityIndicator, FlatList, Share, View } from 'react-native' import { useQuery } from '@tanstack/react-query' import { visitorStatusSchema, visitorEntriesToCsv, type VisitorStatus } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Chip } from '../components/ui/chip' @@ -30,6 +30,7 @@ function formatTime(iso: string): string { // Resident visitor history: their apartments' past + current visitor entries, // filterable by status and time range, exportable as CSV. export default function VisitorHistory() { + const apiClient = useApiClient() const { t } = useT() const [status, setStatus] = useState('ALL') // Compute the cutoff timestamp when a range is picked (an event), not during diff --git a/apps/mobile/app/visitors.tsx b/apps/mobile/app/visitors.tsx index 957b059..ec74dc3 100644 --- a/apps/mobile/app/visitors.tsx +++ b/apps/mobile/app/visitors.tsx @@ -2,7 +2,7 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { ActivityIndicator, FlatList, View } from 'react-native' import { availableVisitorActions } from '@opensociety/shared' -import { apiClient } from '../api/client' +import { useApiClient } from '../api/context' import { useT } from '../lib/i18n' import { Button } from '../components/ui/button' import { Card } from '../components/ui/card' @@ -10,6 +10,7 @@ import { Input } from '../components/ui/input' import { Text } from '../components/ui/text' export default function Visitors() { + const apiClient = useApiClient() const qc = useQueryClient() const { t } = useT() const [denyingId, setDenyingId] = useState(null) From dd0eaaf52f4f263cb8d174b20dd0421537b258f0 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:51:06 +0530 Subject: [PATCH 12/14] Isolate phone demo caches and pending actions --- apps/mobile/lib/demo/runtime.test.ts | 65 ++++++++++++++++++++++++++++ apps/mobile/lib/demo/runtime.ts | 34 +++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 apps/mobile/lib/demo/runtime.test.ts create mode 100644 apps/mobile/lib/demo/runtime.ts diff --git a/apps/mobile/lib/demo/runtime.test.ts b/apps/mobile/lib/demo/runtime.test.ts new file mode 100644 index 0000000..ed25a17 --- /dev/null +++ b/apps/mobile/lib/demo/runtime.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { onlineManager, QueryClient } from '@tanstack/react-query' +import type { CreateVisitorEntry } from '@opensociety/shared' + +import { createDemoRuntime } from './runtime' +import { CREATE_VISITOR_KEY, registerOfflineMutationDefaults } from '../offline/mutation-defaults' + +vi.mock('expo-crypto', () => ({ randomUUID: () => '00000000-0000-4000-8000-999999999999' })) + +const runtimes: ReturnType[] = [] +function runtime(role: 'resident' | 'guard' = 'guard') { + const value = createDemoRuntime(role) + runtimes.push(value) + return value +} +afterEach(() => { runtimes.forEach(r => r.retire()); runtimes.length = 0; onlineManager.setOnline(true); vi.unstubAllGlobals() }) + +describe('demo session isolation', () => { + it('executes queries and registrations while the device is offline', async () => { + onlineManager.setOnline(false) + const demo = runtime() + const visitors = await demo.queryClient.fetchQuery({ queryKey: ['visitors'], queryFn: () => demo.api.listVisitors() }) + expect(visitors.length).toBeGreaterThan(0) + const mutation = demo.queryClient.getMutationCache().build(demo.queryClient, { mutationKey: CREATE_VISITOR_KEY }) + await mutation.execute({ apartmentId: demo.store.apartmentId, visitorName: 'Offline demo guest', type: 'GUEST' }) + expect(mutation.state.isPaused).toBe(false) + expect((await demo.api.listVisitors())[0].visitorName).toBe('Offline demo guest') + }) + + it('never sends a delayed demo write through live mutation defaults after exit', async () => { + const fetch = vi.fn(() => { throw new Error('Live network forbidden') }) + vi.stubGlobal('fetch', fetch) + const demo = runtime() + let release!: () => void + const hold = new Promise(resolve => { release = resolve }) + const mutation = demo.queryClient.getMutationCache().build(demo.queryClient, { + mutationKey: CREATE_VISITOR_KEY, onMutate: () => hold, + }) + const result = mutation.execute({ apartmentId: demo.store.apartmentId, visitorName: 'Delayed demo', type: 'GUEST' } satisfies CreateVisitorEntry) + const rejected = expect(result).rejects.toThrow('session has ended') + demo.retire() + const live = new QueryClient() + registerOfflineMutationDefaults(live) + release() + await rejected + await live.resumePausedMutations() + expect(live.getMutationCache().getAll()).toHaveLength(0) + expect(fetch).not.toHaveBeenCalled() + live.clear() + }) + + it('preserves data across role switches and resets data and cache for a new demo', async () => { + const demo = runtime('resident') + const pending = (await demo.api.listVisitors('PENDING'))[0] + await demo.api.approveVisitor(pending.id) + const guard = createDemoRuntime('guard', demo.store) + runtimes.push(guard) + demo.retire() + expect((await guard.api.checkInVisitor(pending.id)).status).toBe('ENTERED') + await expect(demo.api.listVisitors()).rejects.toThrow('session has ended') + const fresh = runtime('resident') + expect((await fresh.api.listVisitors('PENDING'))[0].id).toBe(pending.id) + expect(fresh.queryClient.getQueryCache().getAll()).toHaveLength(0) + }) +}) diff --git a/apps/mobile/lib/demo/runtime.ts b/apps/mobile/lib/demo/runtime.ts new file mode 100644 index 0000000..f81e7a0 --- /dev/null +++ b/apps/mobile/lib/demo/runtime.ts @@ -0,0 +1,34 @@ +import type { CreateVisitorEntry } from '@opensociety/shared' +import { MutationCache, QueryClient } from '@tanstack/react-query' +import { createMobileDemoClient } from './client' +import { createMobileDemoStore, type DemoRole, type MobileApi } from './store' +import { CREATE_VISITOR_KEY } from '../offline/mutation-defaults' + +export function createDemoRuntime(role: DemoRole, store = createMobileDemoStore()) { + let active = true + const client = createMobileDemoClient(store, role) + const api = new Proxy(client, { + get(target, property: keyof MobileApi) { + const method = target[property] + return async (...args: unknown[]) => { + if (!active) throw new Error('This demo session has ended.') + return Reflect.apply(method, target, args) + } + }, + }) + const queryClient: QueryClient = new QueryClient({ + defaultOptions: { + queries: { networkMode: 'always', retry: false, staleTime: 0 }, + mutations: { networkMode: 'always', retry: false }, + }, + mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries() }), + }) + // This cache never uses the live persister or the live mutation defaults. + // The function captures this session's client even if it executes after exit. + queryClient.setMutationDefaults(CREATE_VISITOR_KEY, { mutationFn: (body: CreateVisitorEntry) => api.createVisitor(body) }) + return { + role, store, api, queryClient, + retire() { active = false; queryClient.clear() }, + } +} +export type DemoRuntime = ReturnType From 177809930bd9b5cb4617a57912c3b07307c7fe51 Mon Sep 17 00:00:00 2001 From: ankitsejwal Date: Fri, 23 Oct 2026 21:58:16 +0530 Subject: [PATCH 13/14] Add a no-signup demo to the phone app --- apps/mobile/DEMO.md | 9 ++ apps/mobile/app/_layout.tsx | 101 +++++++++++++-------- apps/mobile/app/gate.tsx | 7 +- apps/mobile/app/index.tsx | 20 +++- apps/mobile/app/sign-in.tsx | 8 +- apps/mobile/app/vehicle-gate.tsx | 5 + apps/mobile/components/demo-banner.tsx | 27 ++++++ apps/mobile/components/demo-entry.tsx | 24 +++++ apps/mobile/lib/offline/use-sync-status.ts | 6 +- apps/mobile/lib/session.tsx | 42 +++++++++ packages/shared/src/i18n.ts | 28 ++++++ 11 files changed, 228 insertions(+), 49 deletions(-) create mode 100644 apps/mobile/DEMO.md create mode 100644 apps/mobile/components/demo-banner.tsx create mode 100644 apps/mobile/components/demo-entry.tsx create mode 100644 apps/mobile/lib/session.tsx diff --git a/apps/mobile/DEMO.md b/apps/mobile/DEMO.md new file mode 100644 index 0000000..54ebbbc --- /dev/null +++ b/apps/mobile/DEMO.md @@ -0,0 +1,9 @@ +Open the phone app, choose Resident or Guard, and tap **Try demo**. No account or API connection is needed. The same screens used by real societies show fictional Green Valley Society data. **Open my society** enters the existing live login and offline sync flow. + +As Resident, approve a visitor for A-101, raise a maintenance ticket, read a notice, add a vehicle or manage house help. Switch to Guard using the controls at the bottom of any screen to check approved visitors in and out. Guest code `DEMO01` and vehicle `DEMO2000` are ready to try. A newly generated resident guest code can also be redeemed in Guard mode on the same device. + +Role switches keep changes in the same sandbox. Reset, Exit and a full app restart discard them. Backgrounding the app keeps the demo while its process remains alive. Demo records and query caches stay in memory, with no AsyncStorage persister. Requests capture their own demo client, and ending or resetting a session disables its old client. The live cache and queued visitor registrations retain their existing storage and replay behavior. + +The demo simulates one device. It does not send notifications or messages, take payments, or synchronize with another phone or the web demo. The gate offers a sample guest pass so trying the flow does not require camera access. + +Run `pnpm --filter @opensociety/mobile test` for the visitor, contract and session isolation checks. `pnpm --filter @opensociety/shared build` prepares the shared fixtures; `pnpm --filter @opensociety/mobile exec expo export --platform all` checks web, iOS and Android bundles. A native smoke check still needs an Expo development build or a compatible Expo Go installation. diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 54340d4..eb3deba 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -1,12 +1,17 @@ import '../global.css' import { useEffect } from 'react' -import { Stack } from 'expo-router' +import { Stack, usePathname } from 'expo-router' +import { View } from 'react-native' +import { QueryClientProvider } from '@tanstack/react-query' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import { ClerkProvider, useAuth } from '@clerk/clerk-expo' import { tokenCache } from '../lib/token-cache' -import { setAuthTokenGetter } from '../api/client' +import { apiClient, setAuthTokenGetter } from '../api/client' +import { ApiContext } from '../api/context' +import { SessionProvider, useSession } from '../lib/session' +import { DemoBanner } from '../components/demo-banner' import { queryClient, persistOptions } from '../lib/offline/query-client' import { setupOnlineManager } from '../lib/offline/network' import { registerOfflineMutationDefaults } from '../lib/offline/mutation-defaults' @@ -33,51 +38,67 @@ function AuthBridge() { function Nav() { const { t } = useT() + const { mode, demo, revision } = useSession() return ( - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + {mode === 'demo' && } + ) } -export default function RootLayout() { +function LiveApp() { const content = ( - { - // Cache restored from disk — flush any writes that were queued offline - // in a previous session. - queryClient.resumePausedMutations() - }} - > - + + { void queryClient.resumePausedMutations() }}>