Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: CI

on:
push:
branches: [main]
branches: [dev, main]
pull_request:
branches: [main]
branches: [dev, main]

concurrency:
group: ci-${{ github.ref }}
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ OpenSociety is an ad-free, open-source app for apartment communities. Welcome gu

Residents and gate staff use the iPhone and Android app. Community administrators manage the society from a web dashboard. Each society runs its own API and database, keeping its records separate and its deployment under its control.

[Explore the app](#a-look-inside) · [Availability](#availability) · [Run locally](#run-locally) · [Deployment guide](deploy/README.md) · [Contribute](#contributing)
[Explore the app](#a-look-inside) · [Availability](#availability) · [Try the demo](#try-the-demo) · [Run locally](#run-locally) · [Deployment guide](deploy/README.md) · [Contribute](#contributing)

## A look inside

Expand Down Expand Up @@ -46,6 +46,10 @@ The mobile app supports English and Hindi, system text scaling, and layouts for

You can explore the code and run a development instance today. A society deployment needs its own database, authentication configuration, storage, and hosting; running those services can incur costs. Start with the [deployment guide](deploy/README.md) and [mobile release guide](docs/mobile.md) when preparing a pilot.

## Try the demo

The web dashboard has a no-signup demo at `/demo`, also reachable from **Try the demo** on the home page. The phone app offers **Try demo** on the sign-in screen, as a Resident or a Guard. Both show a fictional sample society and keep every change in the browser tab or on the device; they never call the society API or Clerk. **Reset demo** restores fresh sample data. [`apps/mobile/DEMO.md`](apps/mobile/DEMO.md) covers what the phone demo can and can't do.

## Run locally

Use **Node 22** and **pnpm 10.0.0**. The pnpm version is pinned in `package.json`. Development uses pnpm workspaces and Turborepo; no local Docker setup is required.
Expand Down
169 changes: 1 addition & 168 deletions apps/api/src/lib/xlsx.ts
Original file line number Diff line number Diff line change
@@ -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) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', "'": '&apos;', '"': '&quot;' })[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 `<c r="${ref}"/>`
if (typeof val === 'number' && Number.isFinite(val)) return `<c r="${ref}"><v>${val}</v></c>`
return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escapeXml(String(val))}</t></is></c>`
})
.join('')
return `<row r="${r + 1}">${cells}</row>`
})
.join('')
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${body}</sheetData></worksheet>`
}

function contentTypesXml(n: number): string {
const overrides = Array.from(
{ length: n },
(_, i) =>
`<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`,
).join('')
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${overrides}</Types>`
}

function workbookXml(sheets: Sheet[]): string {
const els = sheets
.map((s, i) => `<sheet name="${escapeXml(s.name).slice(0, 31)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`)
.join('')
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${els}</sheets></workbook>`
}

function workbookRelsXml(n: number): string {
const rels = Array.from(
{ length: n },
(_, i) =>
`<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`,
).join('')
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${rels}</Relationships>`
}

const ROOT_RELS = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`

// ----- 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'
14 changes: 13 additions & 1 deletion apps/api/src/xlsx.test.ts
Original file line number Diff line number Diff line change
@@ -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)', () => {
Expand Down Expand Up @@ -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()
}
})
})
9 changes: 9 additions & 0 deletions apps/mobile/DEMO.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions apps/mobile/api/context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createContext, useContext } from 'react'
import { apiClient } from './client'

export const ApiContext = createContext(apiClient)
export const useApiClient = () => useContext(ApiContext)
101 changes: 68 additions & 33 deletions apps/mobile/app/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import '../global.css'

import { useEffect } from 'react'
import { Stack } from 'expo-router'
import { Platform } from 'react-native'
import { Stack, usePathname } from 'expo-router'
import { Platform, View } from 'react-native'
import { StatusBar } from 'expo-status-bar'
import { palette } from '../lib/theme'
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'
Expand Down Expand Up @@ -37,10 +41,12 @@ function AuthBridge() {

function Nav() {
const { t } = useT()
const { mode, demo, revision } = useSession()
return (
<>
<View className="flex-1 bg-background">
<StatusBar style="dark" />
<Stack
key={revision}
screenOptions={{
headerStyle: { backgroundColor: palette.background },
headerTintColor: palette.ink,
Expand All @@ -52,41 +58,48 @@ function Nav() {
}}
>
<Stack.Screen name="index" options={{ headerShown: false }} />
<Stack.Screen name="sign-in" options={{ title: t('nav.signIn') }} />
<Stack.Screen name="profile" options={{ title: t('nav.profile') }} />
<Stack.Screen name="visitors" options={{ title: t('nav.visitors') }} />
<Stack.Screen name="visitor-history" options={{ title: t('nav.visitorHistory') }} />
<Stack.Screen name="pre-approve" options={{ title: t('nav.preApproveVisitor') }} />
<Stack.Screen name="notices" options={{ title: t('nav.notices') }} />
<Stack.Screen name="tickets" options={{ title: t('nav.maintenance') }} />
<Stack.Screen name="gate" options={{ title: t('nav.gate') }} />
<Stack.Screen name="vehicle-gate" options={{ title: t('nav.vehicleGate') }} />
<Stack.Screen name="duty" options={{ title: t('nav.guardDuty') }} />
<Stack.Screen name="register" options={{ title: t('nav.registerVisitor') }} />
<Stack.Screen name="house-help" options={{ title: t('nav.houseHelp') }} />
<Stack.Screen name="my-house-help" options={{ title: t('nav.myHouseHelp') }} />
<Stack.Screen name="my-vehicles" options={{ title: t('nav.myVehicles') }} />
<Stack.Screen name="bills" options={{ title: t('nav.bills') }} />
<Stack.Protected guard={mode === 'live' && !!CLERK_PUBLISHABLE_KEY}>
<Stack.Screen name="sign-in" options={{ title: t('nav.signIn') }} />
</Stack.Protected>
<Stack.Protected guard={mode === 'live' || demo?.role === 'resident'}>
<Stack.Screen name="profile" options={{ title: t('nav.profile') }} />
<Stack.Screen name="visitors" options={{ title: t('nav.visitors') }} />
<Stack.Screen name="visitor-history" options={{ title: t('nav.visitorHistory') }} />
<Stack.Screen name="pre-approve" options={{ title: t('nav.preApproveVisitor') }} />
<Stack.Screen name="notices" options={{ title: t('nav.notices') }} />
<Stack.Screen name="tickets" options={{ title: t('nav.maintenance') }} />
<Stack.Screen name="my-house-help" options={{ title: t('nav.myHouseHelp') }} />
<Stack.Screen name="my-vehicles" options={{ title: t('nav.myVehicles') }} />
<Stack.Screen name="bills" options={{ title: t('nav.bills') }} />
</Stack.Protected>
<Stack.Protected guard={mode === 'live' || demo?.role === 'guard'}>
<Stack.Screen name="gate" options={{ title: t('nav.gate') }} />
<Stack.Screen name="vehicle-gate" options={{ title: t('nav.vehicleGate') }} />
<Stack.Screen name="duty" options={{ title: t('nav.guardDuty') }} />
<Stack.Screen name="register" options={{ title: t('nav.registerVisitor') }} />
<Stack.Screen name="house-help" options={{ title: t('nav.houseHelp') }} />
</Stack.Protected>
</Stack>
</>
{mode === 'demo' && <DemoBanner />}
</View>
)
}

export default function RootLayout() {
function LiveApp() {
const content = (
<PersistQueryClientProvider
client={queryClient}
persistOptions={persistOptions}
onSuccess={() => {
// Cache restored from disk — flush any writes that were queued offline
// in a previous session.
queryClient.resumePausedMutations()
}}
>
<I18nProvider>
<ApiContext.Provider value={apiClient}>
<PersistQueryClientProvider
client={queryClient}
persistOptions={persistOptions}
onSuccess={() => {
// Cache restored from disk — flush any writes that were queued offline
// in a previous session.
void queryClient.resumePausedMutations()
}}
>
<Nav />
</I18nProvider>
</PersistQueryClientProvider>
</PersistQueryClientProvider>
</ApiContext.Provider>
)
// Clerk is optional: without a publishable key the app runs on the dev
// x-user-id fallback, mirroring the API's own conditional auth.
Expand All @@ -98,3 +111,25 @@ export default function RootLayout() {
</ClerkProvider>
)
}

// Demo sessions get their own in-memory API and query cache, and never mount
// Clerk or push registration.
function SessionApp() {
const { mode, demo, revision } = useSession()
if (mode === 'live') return <LiveApp />
if (demo) return (
<ApiContext.Provider key={revision} value={demo.api}>
<QueryClientProvider client={demo.queryClient}><Nav /></QueryClientProvider>
</ApiContext.Provider>
)
return <Nav />
}

export default function RootLayout() {
const pathname = usePathname()
return (
<I18nProvider>
<SessionProvider initialLive={pathname === '/sign-in'}><SessionApp /></SessionProvider>
</I18nProvider>
)
}
3 changes: 2 additions & 1 deletion apps/mobile/app/bills.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query'
import { 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'
Expand All @@ -26,6 +26,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() })
Expand Down
Loading
Loading