diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e2de9f4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +.git +.context +**/node_modules +**/dist +**/.turbo +**/.wrangler +**/.expo +**/.tanstack +**/coverage +**/.env* +**/*.env +**/*.env.* +**/.dev.vars* +**/*.pem +**/*.p8 +**/*.log +apps/mobile +.local +.DS_Store diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 67cd386..dc77592 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,9 @@ jobs: - name: Build run: pnpm build + - name: Bundle Node API + run: pnpm --filter @opensociety/api build:node + - name: Type-check run: pnpm check-types @@ -44,3 +47,22 @@ jobs: - name: Test run: pnpm test + + hosting: + name: Hosting containers + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Build API image + run: docker build --target api -t opensociety-api:test . + - name: Build staging web image + run: | + docker build --target web -t opensociety-web:test \ + --build-arg DEPLOY_ENV=staging \ + --build-arg VITE_API_URL=https://api.example.com \ + --build-arg VITE_CLERK_PUBLISHABLE_KEY=pk_test_ZXhhbXBsZS5jb20k . + - name: Smoke-test containers without external services + run: node --test scripts/hosting-smoke.test.mjs diff --git a/.github/workflows/containers.yml b/.github/workflows/containers.yml new file mode 100644 index 0000000..ae7621b --- /dev/null +++ b/.github/workflows/containers.yml @@ -0,0 +1,44 @@ +name: Build hosting images + +on: + workflow_dispatch: + inputs: + environment: + description: GitHub environment holding API_ORIGIN and CLERK_PUBLISHABLE_KEY variables + type: choice + options: [staging, production] + required: true + default: staging + +permissions: + contents: read + packages: write + +jobs: + images: + runs-on: ubuntu-latest + environment: ${{ inputs.environment }} + strategy: + matrix: + target: [api, web] + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - uses: docker/build-push-action@v6 + with: + context: . + target: ${{ matrix.target }} + platforms: linux/amd64 + push: true + tags: ghcr.io/${{ github.repository }}-${{ matrix.target }}:${{ inputs.environment }}-${{ github.sha }} + build-args: | + DEPLOY_ENV=${{ inputs.environment }} + VITE_API_URL=${{ vars.API_ORIGIN }} + VITE_CLERK_PUBLISHABLE_KEY=${{ vars.CLERK_PUBLISHABLE_KEY }} + cache-from: type=gha,scope=${{ matrix.target }}-${{ inputs.environment }} + cache-to: type=gha,mode=max,scope=${{ matrix.target }}-${{ inputs.environment }} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ecbb6e1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,46 @@ +# syntax=docker/dockerfile:1 +FROM node:22-bookworm-slim AS build +ENV PNPM_HOME=/pnpm +ENV PATH=$PNPM_HOME:$PATH +RUN corepack enable && corepack prepare pnpm@10.0.0 --activate +WORKDIR /repo +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY packages ./packages +COPY apps/api ./apps/api +COPY apps/web ./apps/web +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter @opensociety/api... --filter @opensociety/web... install --frozen-lockfile +RUN pnpm --filter @opensociety/shared build && pnpm --filter @opensociety/db build + +FROM build AS api-build +RUN pnpm --filter @opensociety/api build && pnpm --filter @opensociety/api build:node + +FROM node:22-bookworm-slim AS api +ENV NODE_ENV=production HOST=0.0.0.0 PORT=8787 +WORKDIR /app +COPY --from=api-build --chown=node:node /repo/apps/api/dist/node.mjs ./node.mjs +USER node +EXPOSE 8787 +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD node -e "fetch('http://127.0.0.1:8787/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "node.mjs"] + +FROM build AS web-build +ARG DEPLOY_ENV=production +ARG VITE_API_URL +ARG VITE_CLERK_PUBLISHABLE_KEY +ENV DEPLOY_ENV=$DEPLOY_ENV VITE_API_URL=$VITE_API_URL VITE_CLERK_PUBLISHABLE_KEY=$VITE_CLERK_PUBLISHABLE_KEY +# pnpm 10.0's portable deploy requires injection in both config and lockfile. +# Change only that setting in the container; keep every resolved version pinned. +RUN pnpm --filter @opensociety/web build \ + && sed -i '/^settings:/a\ injectWorkspacePackages: true' pnpm-lock.yaml \ + && pnpm --config.inject-workspace-packages=true --filter @opensociety/web deploy --prod /web + +FROM node:22-bookworm-slim AS web +ENV NODE_ENV=production HOST=0.0.0.0 PORT=3000 +WORKDIR /app +COPY --from=web-build --chown=node:node /web/node_modules ./node_modules +COPY --from=web-build --chown=node:node /repo/apps/web/package.json /repo/apps/web/server.mjs ./ +COPY --from=web-build --chown=node:node /repo/apps/web/dist ./dist +USER node +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD node -e "fetch('http://127.0.0.1:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "server.mjs"] diff --git a/README.md b/README.md index 7e919fe..c2878be 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ - Mobile: [Expo](https://expo.dev) Router (React Native, SDK 57) + TanStack Query **Backend:** -- API: [Hono](https://hono.dev) on [Cloudflare Workers](https://workers.cloudflare.com) +- API: [Hono](https://hono.dev) on Node 22 for shared hosting; Cloudflare Workers adapter also available - Database: [Neon Postgres](https://neon.tech) via [Drizzle ORM](https://orm.drizzle.team) (neon-http driver) - Shared contracts: Zod (`@opensociety/shared`) @@ -31,7 +31,7 @@ See `BLOCKING_DECISIONS.md` (in the Obsidian notes) for the rationale behind ten ``` apps/ - api Hono API on Cloudflare Workers (wrangler) + api Hono API with Node and Cloudflare Workers adapters web TanStack Start admin dashboard mobile Expo Router app (residents + guards) packages/ @@ -42,26 +42,30 @@ packages/ ## Quickstart +Use Node 22 and the pinned pnpm 10 workspace install. Local development runs directly on the Mac; Docker builds and container checks run in GitHub Actions. + +```sh +pnpm install --frozen-lockfile +cp apps/api/.env.example apps/api/.env +cp apps/web/.env.example apps/web/.env +# Fill in the development Neon/Clerk values, then start both applications: +pnpm dev ``` -pnpm install -pnpm check-types # type-check all packages -pnpm --filter @opensociety/db db:generate # generate a migration from the schema -pnpm --filter @opensociety/api dev # wrangler dev (needs apps/api/.dev.vars) -pnpm --filter @opensociety/web dev # http://localhost:3000 -``` -Then open the admin dashboard at **http://localhost:3000/admin**. +Turborepo builds the shared and database packages before starting the Node API on port 8787 and the web dashboard on port 3000. Its watcher rebuilds workspace dependencies and restarts affected applications when files change. Open **http://localhost:3000/admin**. Start the mobile app separately with `pnpm --filter @opensociety/mobile start` when needed. + +Run `pnpm build`, `pnpm check-types`, `pnpm lint`, and `pnpm test` from the root. These reuse the workspace install and Turbo cache. `pnpm --filter @opensociety/api dev:worker` remains available for the Workers adapter. ### Environment Copy the example env files and fill in real values (all are gitignored): ``` -cp apps/api/.dev.vars.example apps/api/.dev.vars # DATABASE_URL, CLERK_* (API) -cp apps/web/.env.example apps/web/.env # VITE_API_URL, VITE_DEV_USER_ID (web) +cp apps/api/.env.example apps/api/.env # DATABASE_URL, CLERK_* (Node API) +cp apps/web/.env.example apps/web/.env # VITE_API_URL, VITE_CLERK_PUBLISHABLE_KEY ``` -Per-society secrets (`DATABASE_URL`, `CLERK_*`, R2) go in `apps/api/.dev.vars` for local dev and `wrangler secret put` for production. See `.env.example` for the full list. +Per-society secrets (`DATABASE_URL`, `CLERK_*`, R2) go in `apps/api/.dev.vars` for local Workers development. Node hosting uses runtime environment variables. See [the deployment guide](deploy/README.md) for container builds, configuration, migrations, scheduled jobs, and rollback. Clerk sessions authenticate web and mobile requests. The API accepts the local `x-user-id` fallback only when no Clerk secret is configured. Keep development identity overrides out of preview and store builds. @@ -101,7 +105,7 @@ Configure this app's APNs credential in EAS for iOS. For Android, configure the Before pilot distribution, verify on physical iOS and Android devices: permission grant/denial; foreground/background/cold-start notification taps; resident and guard event routing; tower targeting; partial/paid/cancelled bill reminders; token refresh; sign-out and account switching. Database integration tests cover queue claims, deduplication, retries, receipts, account reassignment, and dead-token removal; they do not prove delivery through APNs/FCM. -Hosting is not provisioned by these changes. The current API adapter targets Workers/R2/Queues; the shared hosting plan is a DigitalOcean Droplet. Reconcile that deployment adapter, scheduled jobs, and storage before enabling a public backend. Store profiles also need the deployed HTTPS API and live Clerk configuration. +The shared DigitalOcean Droplet is not provisioned yet. A Node API adapter, web server, R2 S3 adapter, restart recovery, and container configuration are prepared in [the deployment guide](deploy/README.md). Store profiles still need the deployed HTTPS API and live Clerk configuration. ## Admin dashboard diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 0000000..930453c --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,17 @@ +# Local Node API. Copy to .env and use your development Neon branch. +# This placeholder supports /health but cannot serve database-backed routes. +DATABASE_URL=postgresql://test:test@localhost/test +WEB_ORIGINS=http://localhost:3000,http://localhost:8081 +BILLING_ENABLED=false +PUSH_ENABLED=false + +# Use the same Clerk instance as the web/mobile client. +# CLERK_SECRET_KEY=sk_test_... +# CLERK_PUBLISHABLE_KEY=pk_test_... +# CLERK_WEBHOOK_SECRET=whsec_... + +# Optional for local development; required to exercise uploads against R2. +# R2_ACCOUNT_ID= +# R2_BUCKET_NAME=opensociety-uploads +# R2_ACCESS_KEY_ID= +# R2_SECRET_ACCESS_KEY= diff --git a/apps/api/build-node.mjs b/apps/api/build-node.mjs new file mode 100644 index 0000000..9b312e9 --- /dev/null +++ b/apps/api/build-node.mjs @@ -0,0 +1,7 @@ +import { build } from 'esbuild' + +await build({ + entryPoints: ['src/node/server.ts'], outfile: 'dist/node.mjs', bundle: true, + platform: 'node', target: 'node22', format: 'esm', + banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" }, +}) diff --git a/apps/api/package.json b/apps/api/package.json index 6088846..7e17e3f 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -4,15 +4,20 @@ "private": true, "type": "module", "scripts": { - "dev": "wrangler dev", + "dev": "tsx --env-file-if-exists=.env src/node/server.ts", "deploy": "wrangler deploy", "build": "tsc --noEmit", "check-types": "tsc --noEmit", "lint": "eslint .", - "test": "vitest run" + "test": "vitest run", + "build:node": "node build-node.mjs", + "start": "node dist/node.mjs", + "dev:worker": "wrangler dev" }, "dependencies": { + "@aws-sdk/client-s3": "^3.1145.0", "@clerk/backend": "^1.21.0", + "@hono/node-server": "^2.1.3", "@hono/zod-validator": "^0.4.2", "@opensociety/db": "workspace:*", "@opensociety/shared": "workspace:*", @@ -26,7 +31,10 @@ "@cloudflare/workers-types": "^4.20240512.0", "@electric-sql/pglite": "^0.5.8", "@opensociety/eslint-config": "workspace:*", + "@types/node": "^22.10.2", + "esbuild": "^0.28.2", "eslint": "^9.18.0", + "tsx": "^4.19.2", "typescript": "^5.7.2", "vitest": "^3.0.5", "wrangler": "^3.99.0" diff --git a/apps/api/src/billing-postgres.test.ts b/apps/api/src/billing-postgres.test.ts new file mode 100644 index 0000000..353eec7 --- /dev/null +++ b/apps/api/src/billing-postgres.test.ts @@ -0,0 +1,95 @@ +import { afterAll, beforeAll, beforeEach, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { randomUUID } from 'node:crypto' +import { PGlite } from '@electric-sql/pglite' +import { drizzle } from 'drizzle-orm/pglite' +import { accounts, apartments, billLineItems, journalEntries, journalLines, maintenanceBills, type Database } from '@opensociety/db' +import { insertJournalEntry, postMonthlyBills } from './lib/ledger-posting' +import { generateMonthlyBills } from './lib/generate-bills' + +const postgres = new PGlite() +const pg = drizzle(postgres) +const db = pg as unknown as Database +const options = { + periodMonth: '2026-10', title: 'October maintenance', dueDate: new Date('2026-10-10T00:00:00Z'), + lineItems: [{ description: 'Maintenance', amount: 10000, taxRatePct: 18 }], +} + +beforeAll(async () => { + const directory = new URL('../../../packages/db/drizzle/', import.meta.url) + const journal = JSON.parse(readFileSync(new URL('meta/_journal.json', directory), 'utf8')) + for (const entry of journal.entries) await postgres.exec(readFileSync(new URL(`${entry.tag}.sql`, directory), 'utf8')) +}, 30_000) +afterAll(async () => postgres.close()) +beforeEach(async () => { await postgres.exec('TRUNCATE apartments, accounts, journal_entries CASCADE') }) + +it('generates complete monthly bills for 1,000 apartments and safely repeats a run', async () => { + await pg.insert(apartments).values(Array.from({ length: 1000 }, (_, i) => ({ tower: 'A', apartmentNo: String(i + 1) }))) + await pg.insert(apartments).values({ tower: 'B', apartmentNo: '1', isActive: false }) + const result = await generateMonthlyBills(db, options) + expect(result.created).toBe(1000) + expect(result.skipped).toBe(0) + const bills = await pg.select().from(maintenanceBills) + expect(bills).toHaveLength(1000) + expect(bills.every((bill) => bill.totalAmount === 11800 && bill.taxAmount === 1800)).toBe(true) + expect(await pg.select().from(billLineItems)).toHaveLength(1000) + expect(await generateMonthlyBills(db, options)).toEqual({ created: 0, skipped: 1000, billIds: [] }) +}, 15_000) + +it('allows only one bill when generation calls overlap', async () => { + await pg.insert(apartments).values({ tower: 'A', apartmentNo: '1' }) + const runs = await Promise.all([generateMonthlyBills(db, options), generateMonthlyBills(db, options)]) + expect(runs.map((run) => run.created).sort()).toEqual([0, 1]) + expect(await pg.select().from(billLineItems)).toHaveLength(1) +}) + +it('rolls back the bill when a charge references a missing ledger account', async () => { + await pg.insert(apartments).values({ tower: 'A', apartmentNo: '1' }) + await expect(generateMonthlyBills(db, { + ...options, lineItems: [{ ...options.lineItems[0], accountId: randomUUID() }], + })).rejects.toThrow() + expect(await pg.select().from(maintenanceBills)).toHaveLength(0) + expect(await pg.select().from(billLineItems)).toHaveLength(0) + expect((await generateMonthlyBills(db, options)).created).toBe(1) +}) + +it('handles a society with no active apartments', async () => { + expect(await generateMonthlyBills(db, options)).toEqual({ created: 0, skipped: 0, billIds: [] }) +}) + + +it('keeps journal entries atomic and allows retry after a rejected line', async () => { + const [account] = await pg.insert(accounts).values({ code: '1100', name: 'Receivable', type: 'ASSET' }).returning() + const draft = { + entryDate: '2026-10-01', period: '2026-10', narration: 'Test bill', sourceType: 'BILL' as const, sourceId: randomUUID(), + lines: [{ accountId: account.id, debit: 10000, credit: 0 }, { accountId: randomUUID(), debit: 0, credit: 10000 }], + } + await expect(insertJournalEntry(db, draft)).rejects.toThrow() + expect(await pg.select().from(journalEntries)).toHaveLength(0) + expect(await pg.select().from(journalLines)).toHaveLength(0) + draft.lines[1].accountId = account.id + expect(await insertJournalEntry(db, draft)).toBeTypeOf('string') + expect(await insertJournalEntry(db, draft)).toBeNull() + expect(await pg.select().from(journalEntries)).toHaveLength(1) + expect(await pg.select().from(journalLines)).toHaveLength(2) +}) + + +it('posts 1,000 bills in batches and recovers generation completed before ledger initialization', async () => { + await pg.insert(apartments).values(Array.from({ length: 1000 }, (_, i) => ({ tower: 'A', apartmentNo: String(i + 1) }))) + await generateMonthlyBills(db, options) + expect(await postMonthlyBills(db, options.periodMonth)).toBe(0) + await pg.insert(accounts).values([ + { code: '1100', name: 'Receivable', type: 'ASSET' }, + { code: '2200', name: 'GST', type: 'LIABILITY' }, + { code: '4000', name: 'Income', type: 'INCOME' }, + ]) + expect(await postMonthlyBills(db, options.periodMonth)).toBe(1000) + expect(await pg.select().from(journalEntries)).toHaveLength(1000) + const lines = await pg.select().from(journalLines) + expect(lines).toHaveLength(3000) + expect(lines.reduce((sum, line) => sum + line.debit - line.credit, 0)).toBe(0) + expect(lines.reduce((sum, line) => sum + line.debit, 0)).toBe(11800000) + expect(await postMonthlyBills(db, options.periodMonth)).toBe(0) + expect(await pg.select().from(journalLines)).toHaveLength(3000) +}, 15_000) diff --git a/apps/api/src/cors.test.ts b/apps/api/src/cors.test.ts new file mode 100644 index 0000000..0b21958 --- /dev/null +++ b/apps/api/src/cors.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from 'vitest' +import { app } from './index' +import type { Bindings } from './types' + +it('allows only configured browser origins and keeps native requests working', async () => { + const env = { WEB_ORIGINS: 'https://society.example.com', CLERK_SECRET_KEY: 'sk_live_test' } as Bindings + for (const origin of ['https://society.example.com', 'https://unexpected.example.com', 'http://localhost:3000']) { + const response = await app.request('/health', { headers: { Origin: origin } }, env) + expect(response.status).toBe(200) + expect(response.headers.get('access-control-allow-origin')).toBe(origin === env.WEB_ORIGINS ? origin : null) + } + const response = await app.request('/health', {}, env) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ status: 'ok' }) +}) + +it('does not allow development origins when Clerk is configured without an allowlist', async () => { + const response = await app.request('/health', { headers: { Origin: 'http://localhost:3000' } }, { CLERK_SECRET_KEY: 'sk_test_test' } as Bindings) + expect(response.headers.get('access-control-allow-origin')).toBeNull() +}) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 3c4face..1307bab 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -4,7 +4,7 @@ import { createDb, billConfig } from '@opensociety/db' import { periodMonthOf, dueDateForPeriod } from '@opensociety/shared' import type { AppEnv, Bindings } from './types' import { generateMonthlyBills } from './lib/generate-bills' -import { safePostBill } from './lib/ledger-posting' +import { postMonthlyBills } from './lib/ledger-posting' import { societyRoutes } from './routes/society' import { apartmentRoutes } from './routes/apartments' import { visitorRoutes } from './routes/visitors' @@ -27,10 +27,16 @@ import { pushRoutes } from './routes/push' import { dispatchAndSchedule, requestPushDispatch } from './lib/push-dispatch' import { sendBillReminders } from './lib/bill-reminders' -const app = new Hono() +export const app = new Hono() -// TODO: tighten origins once web/mobile deploy URLs are known. -app.use('*', cors()) +app.use('*', cors({ + origin: (origin, c) => { + const configured: string | undefined = c.env?.WEB_ORIGINS + const allowed = configured?.split(',').map((value) => value.trim()) ?? + (c.env?.CLERK_SECRET_KEY ? [] : ['http://localhost:3000', 'http://localhost:8081']) + return allowed.includes(origin) ? origin : undefined + }, +})) // Health checks intentionally avoid the DB so they work without DATABASE_URL. app.get('/', (c) => c.json({ name: 'opensociety-api', status: 'ok' })) @@ -59,12 +65,12 @@ app.route('/push', pushRoutes) app.notFound((c) => c.json({ error: 'not found' }, 404)) app.onError((err, c) => { console.error(err) - return c.json({ error: err.message || 'internal error' }, 500) + return c.json({ error: 'internal error' }, 500) }) // Monthly cron (see wrangler.jsonc crons): generate bills for the current month // from the saved bill config. Idempotent, so re-runs are safe. -async function runMonthlyBilling(env: Bindings, scheduledTime: number) { +export async function runMonthlyBilling(env: Bindings, scheduledTime: number) { const db = createDb(env.DATABASE_URL) const [cfg] = await db.select().from(billConfig).limit(1) if (!cfg || cfg.lineItems.length === 0) { @@ -78,7 +84,8 @@ async function runMonthlyBilling(env: Bindings, scheduledTime: number) { dueDate: new Date(dueDateForPeriod(period, cfg.dueDayOfMonth)), lineItems: cfg.lineItems, }) - for (const billId of result.billIds) await safePostBill(db, billId) + // Let the scheduler retry failures; bill creation is already idempotent. + await postMonthlyBills(db, period) console.log(`auto-billing ${period}: created ${result.created}, skipped ${result.skipped}`) // TODO: notify residents when bills are generated (blocked on the push service, #15). } diff --git a/apps/api/src/ledger.route.test.ts b/apps/api/src/ledger.route.test.ts index e151e02..e900f22 100644 --- a/apps/api/src/ledger.route.test.ts +++ b/apps/api/src/ledger.route.test.ts @@ -1,19 +1,19 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' const { fakeDb, setQueue } = vi.hoisted(() => { - let queue: unknown[][] = [] + let queue: unknown[] = [] const makeChain = (): unknown => new Proxy(function () {}, { get(_t, prop) { if (prop === 'then') { - const r = queue.length ? (queue.shift() as unknown[]) : [] + const r = queue.length ? queue.shift() : [] return (resolve: (v: unknown) => void) => resolve(r) } return () => makeChain() }, apply: () => makeChain(), }) - return { fakeDb: () => makeChain(), setQueue: (q: unknown[][]) => (queue = q) } + return { fakeDb: () => makeChain(), setQueue: (q: unknown[]) => (queue = q) } }) vi.mock('@opensociety/db', async (orig) => ({ @@ -86,7 +86,7 @@ describe('POST /journal-entries — balanced-entry guard', () => { }) it('201s a balanced entry from an admin', async () => { - setQueue([[ADMIN], [{ id: 'entry-1' }]]) + setQueue([[ADMIN], { rows: [{ id: 'entry-1' }] }]) const res = await jsonReq('/journal-entries', 'a1', { entryDate: '2026-07-10', narration: 'Opening balance', diff --git a/apps/api/src/lib/generate-bills.ts b/apps/api/src/lib/generate-bills.ts index fbe98f5..a4a7d0a 100644 --- a/apps/api/src/lib/generate-bills.ts +++ b/apps/api/src/lib/generate-bills.ts @@ -1,53 +1,36 @@ import type { Database } from '@opensociety/db' -import { maintenanceBills, billLineItems, apartments } from '@opensociety/db' -import { eq } from 'drizzle-orm' +import { sql } from 'drizzle-orm' import { computeBill, type BillLineInput } from '@opensociety/shared' -// Generate a monthly bill (the same line items) for every active flat that does -// not already have one for `periodMonth`. Idempotent per period. Shared by the -// admin generate route and the monthly cron. +// The unique monthly index arbitrates concurrent admin/cron runs. Bills and +// their line items commit together, so a failed charge cannot leave an empty bill. export async function generateMonthlyBills( db: Database, opts: { periodMonth: string; title: string; dueDate?: Date | null; lineItems: BillLineInput[]; createdBy?: string }, ): Promise<{ created: number; skipped: number; billIds: string[] }> { + if (!opts.lineItems.length) throw new Error('At least one bill line is required') const totals = computeBill(opts.lineItems) - const flats = await db.select({ id: apartments.id }).from(apartments).where(eq(apartments.isActive, true)) - const existing = await db - .select({ apartmentId: maintenanceBills.apartmentId }) - .from(maintenanceBills) - .where(eq(maintenanceBills.periodMonth, opts.periodMonth)) - const already = new Set(existing.map((r) => r.apartmentId)) - const targets = flats.filter((f) => !already.has(f.id)) - if (targets.length === 0) return { created: 0, skipped: flats.length, billIds: [] } - - const created = await db - .insert(maintenanceBills) - .values( - targets.map((f) => ({ - apartmentId: f.id, - type: 'MONTHLY' as const, - title: opts.title, - periodMonth: opts.periodMonth, - subtotal: totals.subtotal, - taxAmount: totals.taxAmount, - totalAmount: totals.total, - dueDate: opts.dueDate ?? null, - createdBy: opts.createdBy, - })), + const lines = totals.lines.map((line) => ({ + description: line.description, amount: line.amount, tax_rate_pct: line.taxRatePct, + tax_amount: line.taxAmount, account_id: line.accountId ?? null, + })) + const result = await db.execute<{ id: string | null; total: number }>(sql` + with active as (select id from apartments where is_active = true), + created as ( + insert into maintenance_bills (apartment_id, type, title, period_month, subtotal, tax_amount, total_amount, due_date, created_by) + select id, 'MONTHLY', ${opts.title}, ${opts.periodMonth}, ${totals.subtotal}, ${totals.taxAmount}, ${totals.total}, + ${opts.dueDate?.toISOString() ?? null}::timestamp, ${opts.createdBy ?? null}::uuid from active + on conflict (apartment_id, period_month) where type = 'MONTHLY' and period_month is not null do nothing + returning id + ), charges as ( + insert into bill_line_items (bill_id, description, amount, tax_rate_pct, tax_amount, account_id) + select created.id, line.description, line.amount, line.tax_rate_pct, line.tax_amount, line.account_id + from created cross join jsonb_to_recordset(${JSON.stringify(lines)}::jsonb) + as line(description text, amount integer, tax_rate_pct integer, tax_amount integer, account_id uuid) ) - .returning({ id: maintenanceBills.id }) - - await db.insert(billLineItems).values( - created.flatMap((b) => - totals.lines.map((l) => ({ - billId: b.id, - description: l.description, - amount: l.amount, - taxRatePct: l.taxRatePct, - taxAmount: l.taxAmount, - accountId: l.accountId ?? null, - })), - ), - ) - return { created: created.length, skipped: already.size, billIds: created.map((b) => b.id) } + select created.id, (select count(*)::int from active) as total + from (select 1) singleton left join created on true + `) + const billIds = result.rows.flatMap((row) => row.id ? [row.id] : []) + return { created: billIds.length, skipped: Number(result.rows[0]?.total ?? 0) - billIds.length, billIds } } diff --git a/apps/api/src/lib/ledger-posting.ts b/apps/api/src/lib/ledger-posting.ts index f6bfbfb..3eb04c4 100644 --- a/apps/api/src/lib/ledger-posting.ts +++ b/apps/api/src/lib/ledger-posting.ts @@ -1,6 +1,6 @@ import type { Database } from '@opensociety/db' import { accounts, journalEntries, journalLines, maintenanceBills, billLineItems, payments } from '@opensociety/db' -import { and, eq, inArray, ne, sql } from 'drizzle-orm' +import { and, eq, inArray, isNull, ne, sql } from 'drizzle-orm' import { ACCOUNT_CODES, postBillIssued as buildBillEntry, @@ -23,11 +23,6 @@ import { // on (source_type, source_id)). If the chart of accounts hasn't been initialized // yet, posting is skipped until an admin runs POST /ledger/init. -function isUniqueViolation(e: unknown): boolean { - const code = (e as { code?: string })?.code - return code === '23505' || /duplicate key value/i.test((e as Error)?.message ?? '') -} - function toDateStr(d: Date | string): string { return (d instanceof Date ? d.toISOString() : new Date(d).toISOString()).slice(0, 10) } @@ -40,46 +35,46 @@ export async function resolveAccounts(db: Database, codes: string[]): Promise [r.code, r.id])) } -// Persist a balanced draft as one journal entry + its lines. Returns the entry -// id, or null when the entry already exists (idempotent). Throws only on an -// unbalanced draft — that is a programming error, not a data condition. -export async function insertJournalEntry(db: Database, draft: JournalDraft, createdBy?: string): Promise { - const errors = validateEntryLines(draft.lines) - if (errors.length) throw new Error(`unbalanced journal entry: ${errors.join('; ')}`) - - let entryId: string - try { - const [entry] = await db - .insert(journalEntries) - .values({ - entryDate: draft.entryDate, - narration: draft.narration, - sourceType: draft.sourceType, - sourceId: draft.sourceId ?? null, - period: draft.period, - isReversal: draft.isReversal ?? false, - reversesId: draft.reversesId ?? null, - createdBy: createdBy ?? null, - }) - .returning({ id: journalEntries.id }) - entryId = entry.id - } catch (e) { - if (isUniqueViolation(e)) return null // already posted - throw e - } +// Persist headers and lines in the same statement. A failed line rolls back +// its header, leaving the business event eligible for a subsequent retry. +export async function insertJournalEntries(db: Database, drafts: JournalDraft[], createdBy?: string): Promise { + if (!drafts.length) return [] + const entries = drafts.map((draft) => { + const errors = validateEntryLines(draft.lines) + if (errors.length) throw new Error(`unbalanced journal entry: ${errors.join('; ')}`) + return { + id: crypto.randomUUID(), entry_date: draft.entryDate, narration: draft.narration, + source_type: draft.sourceType, source_id: draft.sourceId ?? null, period: draft.period, + is_reversal: draft.isReversal ?? false, reverses_id: draft.reversesId ?? null, + created_by: createdBy ?? null, + } + }) + const lines = drafts.flatMap((draft, i) => draft.lines.map((line) => ({ + entry_id: entries[i].id, account_id: line.accountId, debit: line.debit, credit: line.credit, + apartment_id: line.apartmentId ?? null, vendor_id: line.vendorId ?? null, memo: line.memo ?? null, + }))) + const result = await db.execute<{ id: string }>(sql` + with created as ( + insert into journal_entries (id, entry_date, narration, source_type, source_id, period, is_reversal, reverses_id, created_by) + select id, entry_date, narration, source_type, source_id, period, is_reversal, reverses_id, created_by + from jsonb_to_recordset(${JSON.stringify(entries)}::jsonb) as entry( + id uuid, entry_date date, narration text, source_type journal_source, source_id uuid, + period text, is_reversal boolean, reverses_id uuid, created_by uuid + ) on conflict (source_type, source_id) where source_type in ('BILL', 'PAYMENT', 'EXPENSE', 'INTEREST') do nothing + returning id + ), lines as ( + insert into journal_lines (entry_id, account_id, debit, credit, apartment_id, vendor_id, memo) + select line.entry_id, line.account_id, line.debit, line.credit, line.apartment_id, line.vendor_id, line.memo + from jsonb_to_recordset(${JSON.stringify(lines)}::jsonb) as line( + entry_id uuid, account_id uuid, debit integer, credit integer, apartment_id uuid, vendor_id uuid, memo text + ) join created on created.id = line.entry_id + ) select id from created + `) + return result.rows.map((row) => row.id) +} - await db.insert(journalLines).values( - draft.lines.map((l) => ({ - entryId, - accountId: l.accountId, - debit: l.debit, - credit: l.credit, - apartmentId: l.apartmentId ?? null, - vendorId: l.vendorId ?? null, - memo: l.memo ?? null, - })), - ) - return entryId +export async function insertJournalEntry(db: Database, draft: JournalDraft, createdBy?: string): Promise { + return (await insertJournalEntries(db, [draft], createdBy))[0] ?? null } // §6.1 — post the "bill issued" entry for a freshly created bill. Each line @@ -133,6 +128,40 @@ export async function postBill(db: Database, billId: string, createdBy?: string) return insertJournalEntry(db, draft, createdBy) } +// Fetch a month's unposted bills once, then persist bounded batches. Re-running +// also repairs bills whose earlier posting failed after generation committed. +export async function postMonthlyBills(db: Database, period: string, createdBy?: string): Promise { + const acc = await resolveAccounts(db, [ACCOUNT_CODES.MEMBER_DUES_RECEIVABLE, ACCOUNT_CODES.GST_OUTPUT_PAYABLE, ACCOUNT_CODES.MAINTENANCE_INCOME]) + const receivable = acc.get(ACCOUNT_CODES.MEMBER_DUES_RECEIVABLE) + const gst = acc.get(ACCOUNT_CODES.GST_OUTPUT_PAYABLE) + const income = acc.get(ACCOUNT_CODES.MAINTENANCE_INCOME) + if (!receivable || !gst || !income) return 0 + const rows = await db.select({ + billId: maintenanceBills.id, apartmentId: maintenanceBills.apartmentId, issuedAt: maintenanceBills.issuedAt, + amount: billLineItems.amount, tax: billLineItems.taxAmount, accountId: billLineItems.accountId, + }).from(maintenanceBills) + .innerJoin(billLineItems, eq(billLineItems.billId, maintenanceBills.id)) + .leftJoin(journalEntries, and(eq(journalEntries.sourceType, 'BILL'), eq(journalEntries.sourceId, maintenanceBills.id))) + .where(and(eq(maintenanceBills.type, 'MONTHLY'), eq(maintenanceBills.periodMonth, period), ne(maintenanceBills.status, 'CANCELLED'), isNull(journalEntries.id))) + const groups = new Map() + for (const row of rows) { + const group = groups.get(row.billId) ?? { apartmentId: row.apartmentId, entryDate: toDateStr(row.issuedAt), lines: [] } + group.lines.push({ accountId: row.accountId ?? income, net: row.amount, tax: row.tax }) + groups.set(row.billId, group) + } + const drafts = [...groups].map(([billId, bill]) => buildBillEntry({ + ...bill, billId, period, accounts: { memberDuesReceivable: receivable, gstOutputPayable: gst }, narration: 'Maintenance bill issued', + })) + let posted = 0 + for (let i = 0; i < drafts.length; i += 100) posted += (await insertJournalEntries(db, drafts.slice(i, i + 100), createdBy)).length + return posted +} + +export async function safePostMonthlyBills(db: Database, period: string, createdBy?: string): Promise { + try { await postMonthlyBills(db, period, createdBy) } + catch { console.error('ledger: failed to post monthly bills', period) } +} + // §6.2 — post the "payment received" entry. Debits Bank/Cash; credits Member // Dues Receivable for the portion that clears dues and Member Advances for any // overpayment (computed from the apartment's dues just before this payment). diff --git a/apps/api/src/node/config.test.ts b/apps/api/src/node/config.test.ts new file mode 100644 index 0000000..a533d7a --- /dev/null +++ b/apps/api/src/node/config.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { readNodeConfig } from './config' +const base = { DATABASE_URL: 'postgresql://test:test@localhost/test' } +const production = { + ...base, NODE_ENV: 'production', CLERK_SECRET_KEY: 'sk_live_test', WEB_ORIGINS: 'https://society.example.com', + R2_ACCOUNT_ID: 'test', R2_BUCKET_NAME: 'test', R2_ACCESS_KEY_ID: 'test', R2_SECRET_ACCESS_KEY: 'test', +} +describe('Node deployment configuration', () => { + it('binds unauthenticated development only to loopback by default', () => { + expect(readNodeConfig(base)).toMatchObject({ hostname: '127.0.0.1', port: 8787, uploads: undefined }) + }) + it('requires production auth, exact HTTPS origins, and complete storage credentials', () => { + for (const key of ['CLERK_SECRET_KEY', 'WEB_ORIGINS', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_BUCKET_NAME']) { + expect(() => readNodeConfig({ ...production, [key]: '' })).toThrow() + } + expect(() => readNodeConfig({ ...production, WEB_ORIGINS: '*' })).toThrow() + expect(() => readNodeConfig({ ...production, WEB_ORIGINS: 'http://society.example.com' })).toThrow() + expect(() => readNodeConfig({ ...production, CLERK_SECRET_KEY: 'sk_test_test' })).toThrow() + }) + it('allows test Clerk keys only for an explicit staging deployment', () => { + expect(readNodeConfig({ ...production, APP_ENV: 'staging', CLERK_SECRET_KEY: 'sk_test_test' }).clerkSecret).toBe('sk_test_test') + }) + it('rejects malformed runtime settings without exposing secret values', () => { + expect(() => readNodeConfig({ ...base, DATABASE_URL: 'secret-not-a-url' })).toThrow('DATABASE_URL must be a valid URL') + for (const PORT of ['0', '70000', 'invalid']) expect(() => readNodeConfig({ ...base, PORT })).toThrow('PORT') + expect(() => readNodeConfig({ ...production, S3_ENDPOINT: 'https://user:password@host' })).toThrow('contain no credentials') + expect(() => readNodeConfig({ ...production, DATABASE_URL: 'https://example.com' })).toThrow('PostgreSQL') + }) +}) diff --git a/apps/api/src/node/config.ts b/apps/api/src/node/config.ts new file mode 100644 index 0000000..6ad738e --- /dev/null +++ b/apps/api/src/node/config.ts @@ -0,0 +1,43 @@ +export type UploadConfig = { endpoint: string; bucket: string; accessKeyId: string; secretAccessKey: string; pathStyle: boolean } + +export function readNodeConfig(env: Record) { + const production = env.NODE_ENV === 'production' + const parseUrl = (value: string, setting: string) => { + try { return new URL(value) } + catch { throw new Error(`${setting} must be a valid URL`) } + } + const required = (key: string) => { + const value = env[key]?.trim() + if (!value) throw new Error(`${key} is required`) + return value + } + const port = Number(env.PORT ?? 8787) + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('PORT must be between 1 and 65535') + const databaseUrl = required('DATABASE_URL') + const database = parseUrl(databaseUrl, 'DATABASE_URL') + if (!['postgres:', 'postgresql:'].includes(database.protocol)) throw new Error('DATABASE_URL must use PostgreSQL') + const clerkSecret = env.CLERK_SECRET_KEY?.trim() + if (production && !/^sk_(live|test)_/.test(clerkSecret ?? '')) throw new Error('Production requires CLERK_SECRET_KEY') + if (production && env.APP_ENV !== 'staging' && !clerkSecret?.startsWith('sk_live_')) { + throw new Error('Live deployments require a live Clerk key; use APP_ENV=staging for test keys') + } + const origins = (env.WEB_ORIGINS ?? (production ? '' : 'http://localhost:3000,http://localhost:8081')).split(',').filter(Boolean) + if (!origins.length) throw new Error('WEB_ORIGINS is required') + for (const origin of origins) { + const url = parseUrl(origin, 'WEB_ORIGINS') + if (url.origin !== origin || (production && url.protocol !== 'https:') || !['http:', 'https:'].includes(url.protocol)) { + throw new Error('WEB_ORIGINS must contain exact web origins, using HTTPS in production') + } + } + const endpoint = env.S3_ENDPOINT ?? (env.R2_ACCOUNT_ID ? `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com` : undefined) + let uploads: UploadConfig | undefined + if (endpoint || production) { + if (!endpoint) throw new Error('R2_ACCOUNT_ID or S3_ENDPOINT is required') + const url = parseUrl(endpoint, 'Storage endpoint') + if (url.username || url.password || !['http:', 'https:'].includes(url.protocol) || (production && url.protocol !== 'https:')) { + throw new Error('The storage endpoint must use HTTPS in production and contain no credentials') + } + uploads = { endpoint, bucket: required('R2_BUCKET_NAME'), accessKeyId: required('R2_ACCESS_KEY_ID'), secretAccessKey: required('R2_SECRET_ACCESS_KEY'), pathStyle: env.S3_FORCE_PATH_STYLE === 'true' } + } + return { port, hostname: env.HOST ?? (production ? '0.0.0.0' : '127.0.0.1'), databaseUrl, clerkSecret, origins: origins.join(','), uploads } +} diff --git a/apps/api/src/node/jobs.test.ts b/apps/api/src/node/jobs.test.ts new file mode 100644 index 0000000..f960c07 --- /dev/null +++ b/apps/api/src/node/jobs.test.ts @@ -0,0 +1,53 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { runMonthlyBilling } from '../index' +import { dispatchAndSchedule } from '../lib/push-dispatch' +import { sendBillReminders } from '../lib/bill-reminders' +import { startJobs } from './jobs' +import type { Bindings } from '../types' + +vi.mock('../index', () => ({ runMonthlyBilling: vi.fn() })) +vi.mock('../lib/push-dispatch', () => ({ dispatchAndSchedule: vi.fn() })) +vi.mock('../lib/bill-reminders', () => ({ sendBillReminders: vi.fn() })) + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-10-02T00:00:00Z')) + vi.mocked(runMonthlyBilling).mockReset().mockResolvedValue(undefined) + vi.mocked(dispatchAndSchedule).mockReset().mockResolvedValue(undefined) + vi.mocked(sendBillReminders).mockReset().mockResolvedValue(false) +}) +afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() }) + +it('recovers push at startup and otherwise waits for a business event', async () => { + const env = { DATABASE_URL: 'postgresql://test:test@localhost/test', PUSH_ENABLED: 'true' } as Bindings + const stop = startJobs(env, false) + await vi.advanceTimersByTimeAsync(0) + expect(dispatchAndSchedule).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(3600_000) + expect(dispatchAndSchedule).toHaveBeenCalledTimes(1) + await env.PUSH_DISPATCH!.send({ type: 'dispatch' }, { delaySeconds: 60 }) + await vi.advanceTimersByTimeAsync(60_000) + expect(dispatchAndSchedule).toHaveBeenCalledTimes(2) + await stop() + expect(vi.getTimerCount()).toBe(0) +}) + +it('catches up billing, retries an interrupted run, and waits for the next month', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.mocked(runMonthlyBilling).mockRejectedValueOnce(new Error('ledger write interrupted')) + const stop = startJobs({} as Bindings, true) + await vi.advanceTimersByTimeAsync(0) + expect(runMonthlyBilling).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(60_000) + expect(runMonthlyBilling).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(30 * 86400_000 - 60_000) + expect(runMonthlyBilling).toHaveBeenCalledTimes(3) + expect(runMonthlyBilling).toHaveBeenLastCalledWith({}, Date.parse('2026-11-01T00:00:00Z')) + await stop() +}) + +it('does not schedule database work when billing and push are disabled', async () => { + const stop = startJobs({} as Bindings, false) + expect(vi.getTimerCount()).toBe(0) + await stop() +}) diff --git a/apps/api/src/node/jobs.ts b/apps/api/src/node/jobs.ts new file mode 100644 index 0000000..5dd4bc9 --- /dev/null +++ b/apps/api/src/node/jobs.ts @@ -0,0 +1,32 @@ +import { createDb } from '@opensociety/db' +import { runMonthlyBilling } from '../index' +import { sendBillReminders } from '../lib/bill-reminders' +import { dispatchAndSchedule } from '../lib/push-dispatch' +import type { Bindings } from '../types' +import { createWakeup } from './wakeup' + +export function startJobs(env: Bindings, billingEnabled: boolean) { + const failed = (name: string) => () => console.error(`${name}: job failed; retrying in one minute`) + const push = createWakeup(async () => { + await dispatchAndSchedule(createDb(env.DATABASE_URL), env) + }, failed('push')) + const billing = createWakeup(async () => { + await runMonthlyBilling(env, Date.now()) + const now = new Date() + billing.schedule(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1) - now.getTime()) + }, failed('billing')) + const reminders = createWakeup(async () => { + const ran = await sendBillReminders(createDb(env.DATABASE_URL), { + now: new Date(), days: env.BILL_REMINDER_DAYS, timeZone: env.SOCIETY_TIME_ZONE, + }) + if (ran) push.schedule() + reminders.schedule(3600_000 - Date.now() % 3600_000) + }, failed('reminders')) + if (env.PUSH_ENABLED === 'true') { + env.PUSH_DISPATCH = { async send(_body, options) { push.schedule((options?.delaySeconds ?? 0) * 1000) } } + push.schedule() // Recover persisted deliveries, including unexpired leases, after a restart. + reminders.schedule() + } + if (billingEnabled) billing.schedule() // Catch up the current month using the unique bill index. + return async () => { await Promise.all([push.stop(), billing.stop(), reminders.stop()]) } +} diff --git a/apps/api/src/node/server.ts b/apps/api/src/node/server.ts new file mode 100644 index 0000000..d545135 --- /dev/null +++ b/apps/api/src/node/server.ts @@ -0,0 +1,30 @@ +import { serve } from '@hono/node-server' +import { app } from '../index' +import type { Bindings } from '../types' +import { readNodeConfig } from './config' +import { startJobs } from './jobs' +import { createUploadStore } from './uploads' + +const config = readNodeConfig(process.env) +const env: Bindings = { + DATABASE_URL: config.databaseUrl, CLERK_SECRET_KEY: config.clerkSecret, + CLERK_PUBLISHABLE_KEY: process.env.CLERK_PUBLISHABLE_KEY, CLERK_WEBHOOK_SECRET: process.env.CLERK_WEBHOOK_SECRET, + WEB_ORIGINS: config.origins, UPLOADS: createUploadStore(config.uploads), + PUSH_ENABLED: process.env.PUSH_ENABLED, EXPO_ACCESS_TOKEN: process.env.EXPO_ACCESS_TOKEN, + BILL_REMINDER_DAYS: process.env.BILL_REMINDER_DAYS, SOCIETY_TIME_ZONE: process.env.SOCIETY_TIME_ZONE, +} +const stopJobs = startJobs(env, process.env.BILLING_ENABLED === 'true') +const server = serve({ fetch: (request) => app.fetch(request, env), port: config.port, hostname: config.hostname }, () => { + console.log(`OpenSociety API listening on ${config.hostname}:${config.port}`) +}) +let closing = false +async function shutdown() { + if (closing) return + closing = true + const timeout = setTimeout(() => process.exit(1), 25_000) + await Promise.all([stopJobs(), new Promise((resolve) => server.close(() => resolve()))]) + clearTimeout(timeout) + process.exit(0) +} +process.on('SIGTERM', shutdown) +process.on('SIGINT', shutdown) diff --git a/apps/api/src/node/uploads.test.ts b/apps/api/src/node/uploads.test.ts new file mode 100644 index 0000000..e4e2737 --- /dev/null +++ b/apps/api/src/node/uploads.test.ts @@ -0,0 +1,41 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { createServer, type Server } from 'node:http' +import { once } from 'node:events' +import { createUploadStore } from './uploads' +import type { UploadStore } from '../types' + +let server: Server +let store: UploadStore +const objects = new Map() +const authorization: string[] = [] +beforeAll(async () => { + server = createServer(async (req, res) => { + authorization.push(req.headers.authorization ?? '') + const key = req.url!.split('?')[0] + if (req.method === 'PUT') { + const chunks: Buffer[] = [] + for await (const chunk of req) chunks.push(chunk) + objects.set(key, { body: Buffer.concat(chunks), contentType: req.headers['content-type']! }) + res.setHeader('etag', '"test-etag"'); res.end(); return + } + const object = objects.get(key) + if (!object) { res.writeHead(404, { 'content-type': 'application/xml' }); res.end('NoSuchKey'); return } + res.writeHead(200, { 'content-type': object.contentType, etag: '"test-etag"' }); res.end(object.body) + }).listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() as { port: number } + store = createUploadStore({ endpoint: `http://127.0.0.1:${address.port}`, bucket: 'uploads', accessKeyId: 'test', secretAccessKey: 'test', pathStyle: true }) +}) +afterAll(() => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))) +describe('S3 upload adapter', () => { + it('round-trips authenticated private objects with metadata and streamed bodies', async () => { + await store.put('test.pdf', new TextEncoder().encode('private document').buffer, { httpMetadata: { contentType: 'application/pdf' } }) + const object = await store.get('test.pdf') + expect(await new Response(object!.body).text()).toBe('private document') + const headers = new Headers(); object!.writeHttpMetadata(headers) + expect(headers.get('content-type')).toBe('application/pdf') + expect(object!.httpEtag).toBe('"test-etag"') + expect(authorization.every((value) => value.startsWith('AWS4-HMAC-SHA256 '))).toBe(true) + }) + it('returns null for missing objects', async () => { expect(await store.get('missing.pdf')).toBeNull() }) +}) diff --git a/apps/api/src/node/uploads.ts b/apps/api/src/node/uploads.ts new file mode 100644 index 0000000..4e4d302 --- /dev/null +++ b/apps/api/src/node/uploads.ts @@ -0,0 +1,34 @@ +import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3' +import type { UploadStore } from '../types' +import type { UploadConfig } from './config' + +export function createUploadStore(config?: UploadConfig): UploadStore { + if (!config) return { + async put() { throw new Error('Uploads are not configured') }, + async get() { throw new Error('Uploads are not configured') }, + } + const client = new S3Client({ + endpoint: config.endpoint, region: 'auto', forcePathStyle: config.pathStyle, + credentials: { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey }, + requestChecksumCalculation: 'WHEN_REQUIRED', responseChecksumValidation: 'WHEN_REQUIRED', + }) + return { + async put(key, body, options) { + await client.send(new PutObjectCommand({ Bucket: config.bucket, Key: key, Body: new Uint8Array(body), ContentType: options.httpMetadata.contentType })) + }, + async get(key) { + try { + const object = await client.send(new GetObjectCommand({ Bucket: config.bucket, Key: key })) + if (!object.Body) throw new Error('Storage returned an empty response') + return { + body: object.Body.transformToWebStream() as ReadableStream, + httpEtag: object.ETag ?? '', + writeHttpMetadata(headers) { if (object.ContentType) headers.set('content-type', object.ContentType) }, + } + } catch (error) { + if ((error as { name?: string }).name === 'NoSuchKey') return null + throw error + } + }, + } +} diff --git a/apps/api/src/node/wakeup.test.ts b/apps/api/src/node/wakeup.test.ts new file mode 100644 index 0000000..8f2f5fb --- /dev/null +++ b/apps/api/src/node/wakeup.test.ts @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createWakeup } from './wakeup' + +beforeEach(() => vi.useFakeTimers()) +afterEach(() => vi.useRealTimers()) + +it('coalesces wake-ups at the earliest deadline and stops when idle', async () => { + const run = vi.fn().mockResolvedValue(undefined) + const queue = createWakeup(run, vi.fn()) + queue.schedule(1000) + queue.schedule(5000) + queue.schedule(100) + await vi.advanceTimersByTimeAsync(100) + expect(run).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(86400_000) + expect(run).toHaveBeenCalledTimes(1) + await queue.stop() +}) + +it('waits for a monthly deadline beyond Node’s maximum timer delay', async () => { + const run = vi.fn().mockResolvedValue(undefined) + const queue = createWakeup(run, vi.fn()) + const month = 31 * 86400_000 + queue.schedule(month) + await vi.advanceTimersByTimeAsync(2_147_483_647) + expect(run).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(month - 2_147_483_647) + expect(run).toHaveBeenCalledTimes(1) + await queue.stop() +}) + +it('retains a wake-up requested during a pass without overlapping callbacks', async () => { + let finish!: () => void + const run = vi.fn().mockImplementationOnce(() => new Promise((resolve) => { finish = resolve })) + .mockResolvedValue(undefined) + const queue = createWakeup(run, vi.fn()) + queue.schedule() + await vi.advanceTimersByTimeAsync(0) + queue.schedule() + await vi.advanceTimersByTimeAsync(100) + expect(run).toHaveBeenCalledTimes(1) + finish() + await vi.advanceTimersByTimeAsync(1) + expect(run).toHaveBeenCalledTimes(2) + await queue.stop() +}) + +it('retries failures after a minute and cancels pending work at shutdown', async () => { + const run = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined) + const error = vi.fn() + const queue = createWakeup(run, error) + queue.schedule() + await vi.advanceTimersByTimeAsync(0) + expect(error).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(59_999) + expect(run).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(run).toHaveBeenCalledTimes(2) + queue.schedule() + await queue.stop() + await vi.advanceTimersByTimeAsync(60_000) + expect(run).toHaveBeenCalledTimes(2) +}) diff --git a/apps/api/src/node/wakeup.ts b/apps/api/src/node/wakeup.ts new file mode 100644 index 0000000..93c52da --- /dev/null +++ b/apps/api/src/node/wakeup.ts @@ -0,0 +1,38 @@ +// One process owns a wake-up timer, while the database owns the durable work. +// Deadlines coalesce, callbacks never overlap, and failures retry without +// turning an empty outbox into a database polling loop. +export function createWakeup(run: () => Promise, onError: () => void) { + let deadline: number | undefined + let timer: ReturnType | undefined + let running: Promise | undefined + let stopped = false + + function arm() { + if (stopped || running || deadline === undefined) return + if (timer !== undefined) clearTimeout(timer) + timer = setTimeout(() => { + timer = undefined + // Node clamps delays above 2^31-1 ms to 1 ms. Monthly deadlines can + // exceed that limit, so wake only to re-arm until the deadline is due. + if (deadline !== undefined && deadline > Date.now()) { arm(); return } + deadline = undefined + running = Promise.resolve().then(run).catch(() => { + onError() + schedule(60_000) + }).finally(() => { running = undefined; arm() }) + }, Math.min(2_147_483_647, Math.max(0, deadline - Date.now()))) + } + function schedule(delayMs = 0) { + if (stopped) return + deadline = Math.min(deadline ?? Infinity, Date.now() + Math.max(0, delayMs)) + arm() + } + return { + schedule, + async stop() { + stopped = true + if (timer !== undefined) clearTimeout(timer) + await running + }, + } +} diff --git a/apps/api/src/routes/bills.ts b/apps/api/src/routes/bills.ts index 36d0a8d..607ce3e 100644 --- a/apps/api/src/routes/bills.ts +++ b/apps/api/src/routes/bills.ts @@ -17,7 +17,7 @@ import { } from '@opensociety/shared' import { withDb, withAuth, requireAuth, requireRole, actingUserId } from '../middleware' import { generateMonthlyBills } from '../lib/generate-bills' -import { safePostBill, safeReverseBill, resolveAccounts } from '../lib/ledger-posting' +import { safePostMonthlyBills, safePostBill, safeReverseBill, resolveAccounts } from '../lib/ledger-posting' import { tableExport } from '../lib/report-export' import { renderInvoicePdf } from '../lib/invoice-pdf' import type { AppEnv } from '../types' @@ -63,8 +63,8 @@ billRoutes.post('/generate', requireRole('ADMIN'), zValidator('json', generateBi lineItems: input.lineItems, createdBy: actingUserId(c), }) - // Auto-post each new bill to the ledger (best-effort, idempotent). - for (const billId of result.billIds) await safePostBill(db, billId, actingUserId(c)) + // Reconcile this month, including bills from a previously interrupted run. + await safePostMonthlyBills(db, input.periodMonth, actingUserId(c)) return c.json({ created: result.created, skipped: result.skipped }, result.created > 0 ? 201 : 200) }) diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts index 5e1760a..b72165d 100644 --- a/apps/api/src/types.ts +++ b/apps/api/src/types.ts @@ -1,13 +1,27 @@ import type { Database } from '@opensociety/db' import type { UserRole, UserStatus } from '@opensociety/shared' +export interface UploadStore { + put(key: string, body: ArrayBuffer, options: { httpMetadata: { contentType: string } }): Promise + get(key: string): Promise<{ + body: ReadableStream + httpEtag: string + writeHttpMetadata(headers: Headers): void + } | null> +} + +export interface PushDispatch { + send(body: { type: 'dispatch' }, options?: { delaySeconds?: number }): Promise +} + export type Bindings = { DATABASE_URL: string CLERK_SECRET_KEY?: string CLERK_PUBLISHABLE_KEY?: string CLERK_WEBHOOK_SECRET?: string - UPLOADS: R2Bucket - PUSH_DISPATCH?: Queue<{ type: 'dispatch' }> + UPLOADS: UploadStore + PUSH_DISPATCH?: PushDispatch + WEB_ORIGINS?: string PUSH_ENABLED?: string EXPO_ACCESS_TOKEN?: string BILL_REMINDER_DAYS?: string diff --git a/apps/web/.env.example b/apps/web/.env.example index e1ee1ed..675056b 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -4,8 +4,12 @@ # Base URL of the API. Defaults to http://localhost:8787 if unset. VITE_API_URL=http://localhost:8787 -# Dev-only stand-in for the authenticated user, until Clerk sessions are wired -# into the web app. When set, it is sent as the `x-user-id` header so writes -# that record an author (e.g. publishing a notice, approving a visitor) work. +# Enable Clerk sign-in with the same instance used by the API. +# VITE_CLERK_PUBLISHABLE_KEY=pk_test_... + +# Development only: the API accepts this identity only without a Clerk secret. # Must be a real users.id (uuid) from your database. # VITE_DEV_USER_ID=00000000-0000-0000-0000-000000000000 + +# Set for hosting builds to require HTTPS, Clerk, and no development identity. +# DEPLOY_ENV=staging diff --git a/apps/web/hosting-config.test.ts b/apps/web/hosting-config.test.ts new file mode 100644 index 0000000..b793abb --- /dev/null +++ b/apps/web/hosting-config.test.ts @@ -0,0 +1,13 @@ +import { expect, it } from 'vitest' +import { validateHostingConfig } from './hosting-config' + +it('rejects deployment builds with missing auth, local APIs, or development identities', () => { + const valid = { DEPLOY_ENV: 'production', VITE_API_URL: 'https://api.example.com', VITE_CLERK_PUBLISHABLE_KEY: 'pk_live_example' } + expect(() => validateHostingConfig(valid)).not.toThrow() + for (const override of [ + { VITE_API_URL: 'http://localhost:8787' }, { VITE_CLERK_PUBLISHABLE_KEY: '' }, + { VITE_CLERK_PUBLISHABLE_KEY: 'pk_test_example' }, { VITE_DEV_USER_ID: 'user-id' }, { DEPLOY_ENV: 'typo' }, + ]) expect(() => validateHostingConfig({ ...valid, ...override })).toThrow() + expect(() => validateHostingConfig({ ...valid, DEPLOY_ENV: 'staging', VITE_CLERK_PUBLISHABLE_KEY: 'pk_test_example' })).not.toThrow() + expect(() => validateHostingConfig({})).not.toThrow() +}) diff --git a/apps/web/hosting-config.ts b/apps/web/hosting-config.ts new file mode 100644 index 0000000..e4ecf30 --- /dev/null +++ b/apps/web/hosting-config.ts @@ -0,0 +1,11 @@ +// Explicit deployment builds fail closed; ordinary local builds remain usable +// without a Clerk account or a public API. +export function validateHostingConfig(env: Record) { + if (!env.DEPLOY_ENV) return + if (!['staging', 'production'].includes(env.DEPLOY_ENV)) throw new Error('DEPLOY_ENV must be staging or production') + const api = new URL(env.VITE_API_URL ?? '') + if (api.protocol !== 'https:' || api.origin !== env.VITE_API_URL) throw new Error('VITE_API_URL must be an exact HTTPS origin') + const prefix = env.DEPLOY_ENV === 'production' ? /^pk_live_/ : /^pk_(test|live)_/ + if (!prefix.test(env.VITE_CLERK_PUBLISHABLE_KEY ?? '')) throw new Error('A matching Clerk publishable key is required for deployment') + if (env.VITE_DEV_USER_ID) throw new Error('VITE_DEV_USER_ID is not allowed in deployment builds') +} diff --git a/apps/web/package.json b/apps/web/package.json index 88ae555..f240b99 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,10 +8,12 @@ "check-types": "tsc --noEmit", "lint": "eslint .", "preview": "vite preview", - "test": "vitest run" + "test": "vitest run", + "start": "node server.mjs" }, "dependencies": { "@clerk/tanstack-react-start": "^1.4.12", + "@hono/node-server": "^2.1.3", "@opensociety/shared": "workspace:*", "@radix-ui/react-label": "^2.1.2", "@radix-ui/react-select": "^2.1.6", @@ -26,6 +28,7 @@ "@tanstack/router-plugin": "^1.132.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "hono": "^4.10.1", "lucide-react": "^0.545.0", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -50,4 +53,4 @@ "vite": "^7.1.7", "vitest": "^3.0.5" } -} \ No newline at end of file +} diff --git a/apps/web/server.mjs b/apps/web/server.mjs new file mode 100644 index 0000000..4aef415 --- /dev/null +++ b/apps/web/server.mjs @@ -0,0 +1,26 @@ +import process from 'node:process' +import { setTimeout, clearTimeout } from 'node:timers' +import { fileURLToPath, URL } from 'node:url' +import { serve } from '@hono/node-server' +import { serveStatic } from '@hono/node-server/serve-static' +import { Hono } from 'hono' +import start from './dist/server/server.js' + +const app = new Hono() +app.get('/health', (c) => c.json({ status: 'ok' })) +app.use('/assets/*', async (c, next) => { + await next() + if (c.res.ok) c.header('cache-control', 'public, max-age=31536000, immutable') +}) +app.use('*', serveStatic({ root: fileURLToPath(new URL('./dist/client', import.meta.url)) })) +app.all('*', (c) => start.fetch(c.req.raw)) +const server = serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000), hostname: process.env.HOST ?? '127.0.0.1' }) +let closing = false +function shutdown() { + if (closing) return + closing = true + const timeout = setTimeout(() => process.exit(1), 25_000) + server.close(() => { clearTimeout(timeout); process.exit(0) }) +} +process.on('SIGTERM', shutdown) +process.on('SIGINT', shutdown) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 12ccaac..ef7e952 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,4 +1,5 @@ -import { defineConfig } from 'vite' +import { defineConfig, loadEnv } from 'vite' +import { validateHostingConfig } from './hosting-config' import { devtools } from '@tanstack/devtools-vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' @@ -6,7 +7,9 @@ import viteTsConfigPaths from 'vite-tsconfig-paths' import { fileURLToPath, URL } from 'node:url' import tailwindcss from '@tailwindcss/vite' -const config = defineConfig({ +const config = defineConfig(({ mode }) => { + validateHostingConfig({ ...loadEnv(mode, process.cwd(), ''), ...process.env }) + return { resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), @@ -22,6 +25,7 @@ const config = defineConfig({ tanstackStart(), viteReact(), ], + } }) export default config diff --git a/deploy/.env.example b/deploy/.env.example new file mode 100644 index 0000000..547cfad --- /dev/null +++ b/deploy/.env.example @@ -0,0 +1,4 @@ +API_IMAGE=ghcr.io/opencore-x/opensociety-api:production-REPLACE_WITH_COMMIT_SHA +WEB_IMAGE=ghcr.io/opencore-x/opensociety-web:production-REPLACE_WITH_COMMIT_SHA +API_PORT=8787 +WEB_PORT=3000 diff --git a/deploy/.gitignore b/deploy/.gitignore new file mode 100644 index 0000000..6929353 --- /dev/null +++ b/deploy/.gitignore @@ -0,0 +1 @@ +api.env diff --git a/deploy/Caddyfile.example b/deploy/Caddyfile.example new file mode 100644 index 0000000..c493973 --- /dev/null +++ b/deploy/Caddyfile.example @@ -0,0 +1,11 @@ +# Add these sites to the shared host's existing Caddy configuration. +# Replace domains and adjust ports to match deploy/.env. +society.example.com { + encode zstd gzip + reverse_proxy 127.0.0.1:3000 +} + +api.society.example.com { + encode zstd gzip + reverse_proxy 127.0.0.1:8787 +} diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..a4f5e7f --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,58 @@ +# Shared Droplet deployment + +The Droplet is not provisioned, confirmed on 2026-10-02. No public deployment, production migration, DNS change, or image publication has been performed. Shared account and billing facts remain in the shared hosting memory. + +Run one API and one web container per society, with Neon for the database and R2 for object storage. A shared host-level Caddy process terminates HTTPS and forwards to loopback-only ports. Each container has a 384 MiB memory cap. Measure these initial limits alongside the other shared applications before claiming capacity. Build images in GitHub Actions. Local development uses pnpm workspaces and Turborepo to keep Docker images and cache off the Mac. + +## Build + +Use Node 22 and pnpm 10.0.0 from the repository root: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm check-types +pnpm lint +pnpm test +pnpm --filter @opensociety/api build:node +``` + +Use `pnpm dev` for local API/web development. CI builds and smoke-tests both containers without using local Docker storage. + +Only public configuration goes into web build arguments. Secrets belong in the API runtime environment. Production web builds require a live Clerk publishable key. Production API runtime requires a live secret unless `APP_ENV=staging` is explicit. Both require exact HTTPS origins. Set `WEB_ORIGINS` for the Workers adapter too if deploying it. + +The manual **Build hosting images** GitHub workflow builds `linux/amd64` images. Set the chosen GitHub environment's `API_ORIGIN` and `CLERK_PUBLISHABLE_KEY` variables first. Run it against a revision whose CI passed. Tags include the environment and full commit SHA; record image digests for deployment and rollback. This workflow publishes images when manually invoked and does not connect to a server. + +## First deployment + +1. Provision the shared host and confirm its SSH alias, domains, firewall, Caddy installation, available memory, and unused application ports. Keep application ports on loopback. +2. Create a production Neon database/branch, configure the society's Clerk instance and webhook, and create an R2 bucket with bucket-scoped object read/write credentials. Set Clerk application URLs to the actual web domain. The webhook endpoint is `/webhooks/clerk` on the API host. +3. Back up the database or create a recovery branch. Review the query below before migration 0024 on an existing database. Resolve duplicates through an accounting review; the migration never deletes bills or payments. From the exact release checkout, run `pnpm --filter @opensociety/db db:migrate` with `DATABASE_URL` supplied securely. Migrations do not run during container startup. +4. Copy `compose.yaml`, `.env.example`, and `api.env.example` to a protected directory on the host. Rename the examples to `.env` and `api.env`, fill in actual values and immutable image references, then run `chmod 600 .env api.env`. Use a read-only GHCR token if image packages are private. +5. Run `docker compose pull` and `docker compose up -d`. Add the sites from `Caddyfile.example` to the existing host configuration, validate it, and reload Caddy. Configure DNS and verify HTTPS. +6. Check both `/health` endpoints, rendered pages, static assets, Clerk sign-in, role restrictions, private uploads, and the webhook. Health checks deliberately avoid Neon, so they do not wake a suspended database or certify database availability. +7. Review saved billing configuration before setting `BILLING_ENABLED=true`. Enable push after app-specific APNs/FCM setup and physical-device verification. Set the public API URL and matching Clerk publishable key in EAS, then rebuild pilot profiles. + +```sql +SELECT apartment_id, period_month, count(*) +FROM maintenance_bills +WHERE type = 'MONTHLY' AND period_month IS NOT NULL +GROUP BY apartment_id, period_month +HAVING count(*) > 1; +``` + +## Jobs and recovery + +Billing and push are initially disabled. Enabling billing generates missing bills for the current UTC month at startup, then schedules 00:00 UTC on the first. It does not backfill older months. Monthly uniqueness prevents duplicate admin/cron runs. Bills and charges commit atomically; journal headers and lines also commit atomically. Repeated monthly runs recover missing ledger entries in batches of 100. + +Push retains its durable database outbox. Node runs recovery at startup, then schedules timers only for pending deliveries/receipts. Business events wake the dispatcher; empty queues do not poll Neon. Hourly reminder checks query the database only during the local 09:00 hour. That daily run also recovers missed wake-ups. Job failures retry after one minute. Run one Node API process per society; disable Workers cron and queue consumption before enabling Node jobs. + +SIGTERM stops new work and drains requests/jobs for up to 25 seconds; Docker allows 30 seconds. Interrupted outbox leases expire for later recovery. Check `docker compose ps`, `docker compose logs --tail=100 api web`, and `docker stats --no-stream`. Avoid printing interpolated Compose configuration because it includes secrets from `api.env`. + +## Release and rollback + +Pull immutable images, apply reviewed migrations once, update `.env`, and run `docker compose up -d`. Verify authentication and representative reads/writes before enabling jobs. Keep previous image references and a database recovery point. To roll back the application, restore those references and run `docker compose up -d`; do not reverse financial data or migrations automatically. Migration 0024 only adds an index. + +Local PostgreSQL tests cover 1,000-apartment billing, batched journal posting, failed-write rollback, and deduplication. They do not establish Droplet or Neon capacity. Run staging load tests using an isolated database before claiming the 1,000-concurrent-user or 10,000-visitor/day targets. + +References: [Hono Node adapter](https://hono.dev/docs/getting-started/nodejs), [pnpm portable deployment](https://pnpm.io/10.x/cli/deploy). diff --git a/deploy/api.env.example b/deploy/api.env.example new file mode 100644 index 0000000..4f8ee55 --- /dev/null +++ b/deploy/api.env.example @@ -0,0 +1,19 @@ +APP_ENV=production +DATABASE_URL=postgresql://USER:PASSWORD@NEON_HOST/DATABASE?sslmode=require +CLERK_SECRET_KEY=sk_live_REPLACE_ME +CLERK_PUBLISHABLE_KEY=pk_live_REPLACE_ME +CLERK_WEBHOOK_SECRET=whsec_REPLACE_ME +WEB_ORIGINS=https://society.example.com +R2_ACCOUNT_ID=REPLACE_ME +R2_BUCKET_NAME=opensociety-uploads +R2_ACCESS_KEY_ID=REPLACE_ME +R2_SECRET_ACCESS_KEY=REPLACE_ME + +# Enable only after migrations and bill configuration have been reviewed. +# Startup catches up the current month, then runs at 00:00 UTC on the first. +BILLING_ENABLED=false +# Enable after this app's APNs and FCM setup and a physical-device test. +PUSH_ENABLED=false +EXPO_ACCESS_TOKEN= +BILL_REMINDER_DAYS=-7,0,3 +SOCIETY_TIME_ZONE=Asia/Kolkata diff --git a/deploy/compose.yaml b/deploy/compose.yaml new file mode 100644 index 0000000..20ba007 --- /dev/null +++ b/deploy/compose.yaml @@ -0,0 +1,45 @@ +name: opensociety +services: + api: + image: ${API_IMAGE:?Set API_IMAGE to a tested image tag or digest} + env_file: api.env + environment: + NODE_ENV: production + HOST: 0.0.0.0 + PORT: 8787 + NODE_OPTIONS: --max-old-space-size=256 + ports: + - 127.0.0.1:${API_PORT:-8787}:8787 + restart: unless-stopped + init: true + read_only: true + tmpfs: [/tmp:size=32m] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 384m + cpus: 0.5 + stop_grace_period: 30s + logging: + driver: json-file + options: { max-size: 10m, max-file: '3' } + web: + image: ${WEB_IMAGE:?Set WEB_IMAGE to a tested image tag or digest} + environment: + NODE_ENV: production + HOST: 0.0.0.0 + PORT: 3000 + NODE_OPTIONS: --max-old-space-size=256 + ports: + - 127.0.0.1:${WEB_PORT:-3000}:3000 + restart: unless-stopped + init: true + read_only: true + tmpfs: [/tmp:size=32m] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 384m + cpus: 0.5 + stop_grace_period: 30s + logging: + driver: json-file + options: { max-size: 10m, max-file: '3' } diff --git a/package.json b/package.json index 31ea5e4..767d8a4 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "MIT", "scripts": { "build": "turbo run build", - "dev": "turbo run dev", + "dev": "turbo watch dev", "lint": "turbo run lint", "format": "prettier --write .", "check-types": "turbo run check-types", diff --git a/packages/db/drizzle/0024_monthly_bill_uniqueness.sql b/packages/db/drizzle/0024_monthly_bill_uniqueness.sql new file mode 100644 index 0000000..4cecaa6 --- /dev/null +++ b/packages/db/drizzle/0024_monthly_bill_uniqueness.sql @@ -0,0 +1 @@ +CREATE UNIQUE INDEX "maintenance_bills_monthly_apartment_uniq" ON "maintenance_bills" USING btree ("apartment_id","period_month") WHERE "maintenance_bills"."type" = 'MONTHLY' and "maintenance_bills"."period_month" is not null; \ No newline at end of file diff --git a/packages/db/drizzle/meta/0024_snapshot.json b/packages/db/drizzle/meta/0024_snapshot.json new file mode 100644 index 0000000..1c60384 --- /dev/null +++ b/packages/db/drizzle/meta/0024_snapshot.json @@ -0,0 +1,3941 @@ +{ + "id": "ebeeaeab-8d2b-4671-9fef-3f19c25cd222", + "prevId": "06893fed-a33d-4aac-8b86-8988b68a9a32", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "clerk_id": { + "name": "clerk_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "user_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'RESIDENT'" + }, + "status": { + "name": "status", + "type": "user_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'PENDING'" + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_clerk_id_unique": { + "name": "users_clerk_id_unique", + "nullsNotDistinct": false, + "columns": [ + "clerk_id" + ] + }, + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + }, + "users_phone_unique": { + "name": "users_phone_unique", + "nullsNotDistinct": false, + "columns": [ + "phone" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.society_config": { + "name": "society_config", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "city": { + "name": "city", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pincode": { + "name": "pincode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gstin": { + "name": "gstin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.apartments": { + "name": "apartments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "tower": { + "name": "tower", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "apartment_no": { + "name": "apartment_no", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "floor": { + "name": "floor", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "bhk_type": { + "name": "bhk_type", + "type": "bhk_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "apartments_tower_apartment_no_unique": { + "name": "apartments_tower_apartment_no_unique", + "nullsNotDistinct": false, + "columns": [ + "tower", + "apartment_no" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.residencies": { + "name": "residencies", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "relation": { + "name": "relation", + "type": "residency_relation", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'OWNER'" + }, + "is_primary": { + "name": "is_primary", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "start_date": { + "name": "start_date", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "end_date": { + "name": "end_date", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "residencies_user_id_idx": { + "name": "residencies_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "residencies_apartment_id_idx": { + "name": "residencies_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "residencies_user_id_users_id_fk": { + "name": "residencies_user_id_users_id_fk", + "tableFrom": "residencies", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "residencies_apartment_id_apartments_id_fk": { + "name": "residencies_apartment_id_apartments_id_fk", + "tableFrom": "residencies", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guards": { + "name": "guards", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "employee_code": { + "name": "employee_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "guards_user_id_users_id_fk": { + "name": "guards_user_id_users_id_fk", + "tableFrom": "guards", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.visitor_pre_approvals": { + "name": "visitor_pre_approvals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "visitor_name": { + "name": "visitor_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visitor_phone": { + "name": "visitor_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approval_type": { + "name": "approval_type", + "type": "pre_approval_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'ONE_TIME'" + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "valid_until": { + "name": "valid_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "max_uses": { + "name": "max_uses", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "use_count": { + "name": "use_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "visitor_pre_approvals_apartment_id_apartments_id_fk": { + "name": "visitor_pre_approvals_apartment_id_apartments_id_fk", + "tableFrom": "visitor_pre_approvals", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "visitor_pre_approvals_created_by_users_id_fk": { + "name": "visitor_pre_approvals_created_by_users_id_fk", + "tableFrom": "visitor_pre_approvals", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "visitor_pre_approvals_code_unique": { + "name": "visitor_pre_approvals_code_unique", + "nullsNotDistinct": false, + "columns": [ + "code" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.visitor_entries": { + "name": "visitor_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "client_id": { + "name": "client_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pre_approval_id": { + "name": "pre_approval_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "visitor_name": { + "name": "visitor_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visitor_phone": { + "name": "visitor_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "visitor_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'GUEST'" + }, + "status": { + "name": "status", + "type": "visitor_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'PENDING'" + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "vehicle_number": { + "name": "vehicle_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "photo_url": { + "name": "photo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "denied_reason": { + "name": "denied_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "check_in_by": { + "name": "check_in_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "check_out_by": { + "name": "check_out_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "check_in_at": { + "name": "check_in_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "check_out_at": { + "name": "check_out_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "visitor_entries_status_idx": { + "name": "visitor_entries_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "visitor_entries_apartment_id_idx": { + "name": "visitor_entries_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "visitor_entries_created_at_idx": { + "name": "visitor_entries_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "visitor_entries_client_id_idx": { + "name": "visitor_entries_client_id_idx", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "visitor_entries_apartment_id_apartments_id_fk": { + "name": "visitor_entries_apartment_id_apartments_id_fk", + "tableFrom": "visitor_entries", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "visitor_entries_pre_approval_id_visitor_pre_approvals_id_fk": { + "name": "visitor_entries_pre_approval_id_visitor_pre_approvals_id_fk", + "tableFrom": "visitor_entries", + "tableTo": "visitor_pre_approvals", + "columnsFrom": [ + "pre_approval_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "visitor_entries_approved_by_users_id_fk": { + "name": "visitor_entries_approved_by_users_id_fk", + "tableFrom": "visitor_entries", + "tableTo": "users", + "columnsFrom": [ + "approved_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "visitor_entries_check_in_by_guards_id_fk": { + "name": "visitor_entries_check_in_by_guards_id_fk", + "tableFrom": "visitor_entries", + "tableTo": "guards", + "columnsFrom": [ + "check_in_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "visitor_entries_check_out_by_guards_id_fk": { + "name": "visitor_entries_check_out_by_guards_id_fk", + "tableFrom": "visitor_entries", + "tableTo": "guards", + "columnsFrom": [ + "check_out_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notices": { + "name": "notices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "priority": { + "name": "priority", + "type": "notice_priority", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'NORMAL'" + }, + "category": { + "name": "category", + "type": "notice_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'GENERAL'" + }, + "attachment_url": { + "name": "attachment_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attachment_name": { + "name": "attachment_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "published_at": { + "name": "published_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "notices_published_by_users_id_fk": { + "name": "notices_published_by_users_id_fk", + "tableFrom": "notices", + "tableTo": "users", + "columnsFrom": [ + "published_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notice_reads": { + "name": "notice_reads", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "notice_id": { + "name": "notice_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "read_at": { + "name": "read_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "notice_reads_notice_id_notices_id_fk": { + "name": "notice_reads_notice_id_notices_id_fk", + "tableFrom": "notice_reads", + "tableTo": "notices", + "columnsFrom": [ + "notice_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "notice_reads_user_id_users_id_fk": { + "name": "notice_reads_user_id_users_id_fk", + "tableFrom": "notice_reads", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "notice_reads_notice_user_unq": { + "name": "notice_reads_notice_user_unq", + "nullsNotDistinct": false, + "columns": [ + "notice_id", + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.maintenance_tickets": { + "name": "maintenance_tickets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "raised_by": { + "name": "raised_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "ticket_category", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'OTHER'" + }, + "priority": { + "name": "priority", + "type": "ticket_priority", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'NORMAL'" + }, + "status": { + "name": "status", + "type": "ticket_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'OPEN'" + }, + "assigned_to": { + "name": "assigned_to", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "resolution_note": { + "name": "resolution_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "maintenance_tickets_status_idx": { + "name": "maintenance_tickets_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "maintenance_tickets_apartment_id_idx": { + "name": "maintenance_tickets_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "maintenance_tickets_category_idx": { + "name": "maintenance_tickets_category_idx", + "columns": [ + { + "expression": "category", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "maintenance_tickets_apartment_id_apartments_id_fk": { + "name": "maintenance_tickets_apartment_id_apartments_id_fk", + "tableFrom": "maintenance_tickets", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "maintenance_tickets_raised_by_users_id_fk": { + "name": "maintenance_tickets_raised_by_users_id_fk", + "tableFrom": "maintenance_tickets", + "tableTo": "users", + "columnsFrom": [ + "raised_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "maintenance_tickets_assigned_to_users_id_fk": { + "name": "maintenance_tickets_assigned_to_users_id_fk", + "tableFrom": "maintenance_tickets", + "tableTo": "users", + "columnsFrom": [ + "assigned_to" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.house_help": { + "name": "house_help", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "house_help_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'OTHER'" + }, + "photo_url": { + "name": "photo_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_proof_type": { + "name": "id_proof_type", + "type": "id_proof_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "id_proof_number": { + "name": "id_proof_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_proof_url": { + "name": "id_proof_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_verified": { + "name": "id_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "background_check": { + "name": "background_check", + "type": "background_check_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'PENDING'" + }, + "incident_count": { + "name": "incident_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "registered_by": { + "name": "registered_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "house_help_registered_by_users_id_fk": { + "name": "house_help_registered_by_users_id_fk", + "tableFrom": "house_help", + "tableTo": "users", + "columnsFrom": [ + "registered_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.house_help_entries": { + "name": "house_help_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "house_help_id": { + "name": "house_help_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "check_in_at": { + "name": "check_in_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "check_in_by": { + "name": "check_in_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "check_out_at": { + "name": "check_out_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "check_out_by": { + "name": "check_out_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "house_help_entries_house_help_id_idx": { + "name": "house_help_entries_house_help_id_idx", + "columns": [ + { + "expression": "house_help_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "house_help_entries_house_help_id_house_help_id_fk": { + "name": "house_help_entries_house_help_id_house_help_id_fk", + "tableFrom": "house_help_entries", + "tableTo": "house_help", + "columnsFrom": [ + "house_help_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_entries_apartment_id_apartments_id_fk": { + "name": "house_help_entries_apartment_id_apartments_id_fk", + "tableFrom": "house_help_entries", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_entries_check_in_by_users_id_fk": { + "name": "house_help_entries_check_in_by_users_id_fk", + "tableFrom": "house_help_entries", + "tableTo": "users", + "columnsFrom": [ + "check_in_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_entries_check_out_by_users_id_fk": { + "name": "house_help_entries_check_out_by_users_id_fk", + "tableFrom": "house_help_entries", + "tableTo": "users", + "columnsFrom": [ + "check_out_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.house_help_assignments": { + "name": "house_help_assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "house_help_id": { + "name": "house_help_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "house_help_assignments_house_help_id_house_help_id_fk": { + "name": "house_help_assignments_house_help_id_house_help_id_fk", + "tableFrom": "house_help_assignments", + "tableTo": "house_help", + "columnsFrom": [ + "house_help_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_assignments_apartment_id_apartments_id_fk": { + "name": "house_help_assignments_apartment_id_apartments_id_fk", + "tableFrom": "house_help_assignments", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_assignments_assigned_by_users_id_fk": { + "name": "house_help_assignments_assigned_by_users_id_fk", + "tableFrom": "house_help_assignments", + "tableTo": "users", + "columnsFrom": [ + "assigned_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "house_help_assignments_help_apartment_unq": { + "name": "house_help_assignments_help_apartment_unq", + "nullsNotDistinct": false, + "columns": [ + "house_help_id", + "apartment_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.house_help_reviews": { + "name": "house_help_reviews", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "house_help_id": { + "name": "house_help_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reviewer_id": { + "name": "reviewer_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "house_help_reviews_house_help_id_house_help_id_fk": { + "name": "house_help_reviews_house_help_id_house_help_id_fk", + "tableFrom": "house_help_reviews", + "tableTo": "house_help", + "columnsFrom": [ + "house_help_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "house_help_reviews_reviewer_id_users_id_fk": { + "name": "house_help_reviews_reviewer_id_users_id_fk", + "tableFrom": "house_help_reviews", + "tableTo": "users", + "columnsFrom": [ + "reviewer_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "house_help_reviews_help_reviewer_unq": { + "name": "house_help_reviews_help_reviewer_unq", + "nullsNotDistinct": false, + "columns": [ + "house_help_id", + "reviewer_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vehicles": { + "name": "vehicles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "registered_by": { + "name": "registered_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "registration_number": { + "name": "registration_number", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "vehicle_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'CAR'" + }, + "make": { + "name": "make", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "vehicles_apartment_id_apartments_id_fk": { + "name": "vehicles_apartment_id_apartments_id_fk", + "tableFrom": "vehicles", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "vehicles_registered_by_users_id_fk": { + "name": "vehicles_registered_by_users_id_fk", + "tableFrom": "vehicles", + "tableTo": "users", + "columnsFrom": [ + "registered_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "vehicles_registration_number_unq": { + "name": "vehicles_registration_number_unq", + "nullsNotDistinct": false, + "columns": [ + "registration_number" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.parking_slots": { + "name": "parking_slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "slot_number": { + "name": "slot_number", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "parking_slot_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'OPEN'" + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "is_temporary": { + "name": "is_temporary", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "assigned_until": { + "name": "assigned_until", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "assigned_by": { + "name": "assigned_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "is_visitor": { + "name": "is_visitor", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "occupied_by_entry_id": { + "name": "occupied_by_entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "occupied_at": { + "name": "occupied_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "parking_slots_apartment_id_idx": { + "name": "parking_slots_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "parking_slots_is_visitor_idx": { + "name": "parking_slots_is_visitor_idx", + "columns": [ + { + "expression": "is_visitor", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "parking_slots_apartment_id_apartments_id_fk": { + "name": "parking_slots_apartment_id_apartments_id_fk", + "tableFrom": "parking_slots", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "parking_slots_assigned_by_users_id_fk": { + "name": "parking_slots_assigned_by_users_id_fk", + "tableFrom": "parking_slots", + "tableTo": "users", + "columnsFrom": [ + "assigned_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "parking_slots_occupied_by_entry_id_visitor_entries_id_fk": { + "name": "parking_slots_occupied_by_entry_id_visitor_entries_id_fk", + "tableFrom": "parking_slots", + "tableTo": "visitor_entries", + "columnsFrom": [ + "occupied_by_entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "parking_slots_slot_number_unq": { + "name": "parking_slots_slot_number_unq", + "nullsNotDistinct": false, + "columns": [ + "slot_number" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guard_duty_sessions": { + "name": "guard_duty_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guard_id": { + "name": "guard_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "clock_in_at": { + "name": "clock_in_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "clock_in_lat": { + "name": "clock_in_lat", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "clock_in_lng": { + "name": "clock_in_lng", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "clock_out_at": { + "name": "clock_out_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "clock_out_lat": { + "name": "clock_out_lat", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "clock_out_lng": { + "name": "clock_out_lng", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "guard_duty_sessions_guard_id_guards_id_fk": { + "name": "guard_duty_sessions_guard_id_guards_id_fk", + "tableFrom": "guard_duty_sessions", + "tableTo": "guards", + "columnsFrom": [ + "guard_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guard_devices": { + "name": "guard_devices", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guard_id": { + "name": "guard_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "device_id": { + "name": "device_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bound_at": { + "name": "bound_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_active_at": { + "name": "last_active_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "guard_devices_guard_id_guards_id_fk": { + "name": "guard_devices_guard_id_guards_id_fk", + "tableFrom": "guard_devices", + "tableTo": "guards", + "columnsFrom": [ + "guard_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "guard_devices_guard_device_unq": { + "name": "guard_devices_guard_device_unq", + "nullsNotDistinct": false, + "columns": [ + "guard_id", + "device_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.bill_line_items": { + "name": "bill_line_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "bill_id": { + "name": "bill_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tax_rate_pct": { + "name": "tax_rate_pct", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tax_amount": { + "name": "tax_amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "account_id": { + "name": "account_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "bill_line_items_bill_id_idx": { + "name": "bill_line_items_bill_id_idx", + "columns": [ + { + "expression": "bill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "bill_line_items_bill_id_maintenance_bills_id_fk": { + "name": "bill_line_items_bill_id_maintenance_bills_id_fk", + "tableFrom": "bill_line_items", + "tableTo": "maintenance_bills", + "columnsFrom": [ + "bill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "bill_line_items_account_id_accounts_id_fk": { + "name": "bill_line_items_account_id_accounts_id_fk", + "tableFrom": "bill_line_items", + "tableTo": "accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.maintenance_bills": { + "name": "maintenance_bills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "bill_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'MONTHLY'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_month": { + "name": "period_month", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subtotal": { + "name": "subtotal", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tax_amount": { + "name": "tax_amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "total_amount": { + "name": "total_amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "bill_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'ISSUED'" + }, + "due_date": { + "name": "due_date", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "issued_at": { + "name": "issued_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "maintenance_bills_apartment_id_idx": { + "name": "maintenance_bills_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "maintenance_bills_period_month_idx": { + "name": "maintenance_bills_period_month_idx", + "columns": [ + { + "expression": "period_month", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "maintenance_bills_monthly_apartment_uniq": { + "name": "maintenance_bills_monthly_apartment_uniq", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_month", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"maintenance_bills\".\"type\" = 'MONTHLY' and \"maintenance_bills\".\"period_month\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "maintenance_bills_apartment_id_apartments_id_fk": { + "name": "maintenance_bills_apartment_id_apartments_id_fk", + "tableFrom": "maintenance_bills", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "maintenance_bills_created_by_users_id_fk": { + "name": "maintenance_bills_created_by_users_id_fk", + "tableFrom": "maintenance_bills", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.payments": { + "name": "payments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "bill_id": { + "name": "bill_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "payment_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "reference": { + "name": "reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "paid_at": { + "name": "paid_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "recorded_by": { + "name": "recorded_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "payments_bill_id_idx": { + "name": "payments_bill_id_idx", + "columns": [ + { + "expression": "bill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payments_apartment_id_idx": { + "name": "payments_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "payments_bill_id_maintenance_bills_id_fk": { + "name": "payments_bill_id_maintenance_bills_id_fk", + "tableFrom": "payments", + "tableTo": "maintenance_bills", + "columnsFrom": [ + "bill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "payments_apartment_id_apartments_id_fk": { + "name": "payments_apartment_id_apartments_id_fk", + "tableFrom": "payments", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "payments_recorded_by_users_id_fk": { + "name": "payments_recorded_by_users_id_fk", + "tableFrom": "payments", + "tableTo": "users", + "columnsFrom": [ + "recorded_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.bill_config": { + "name": "bill_config", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "due_day_of_month": { + "name": "due_day_of_month", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "line_items": { + "name": "line_items", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "interest_enabled": { + "name": "interest_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "interest_rate_pct": { + "name": "interest_rate_pct", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 18 + }, + "grace_period_days": { + "name": "grace_period_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 15 + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "bill_config_updated_by_users_id_fk": { + "name": "bill_config_updated_by_users_id_fk", + "tableFrom": "bill_config", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.accounts": { + "name": "accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "account_type", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "is_group": { + "name": "is_group", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_mutual": { + "name": "is_mutual", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "accounts_type_idx": { + "name": "accounts_type_idx", + "columns": [ + { + "expression": "type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "accounts_parent_id_idx": { + "name": "accounts_parent_id_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "accounts_parent_id_accounts_id_fk": { + "name": "accounts_parent_id_accounts_id_fk", + "tableFrom": "accounts", + "tableTo": "accounts", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "accounts_code_unique": { + "name": "accounts_code_unique", + "nullsNotDistinct": false, + "columns": [ + "code" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.journal_entries": { + "name": "journal_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "entry_date": { + "name": "entry_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "narration": { + "name": "narration", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_type": { + "name": "source_type", + "type": "journal_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "period": { + "name": "period", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_reversal": { + "name": "is_reversal", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "reverses_id": { + "name": "reverses_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "journal_entries_period_idx": { + "name": "journal_entries_period_idx", + "columns": [ + { + "expression": "period", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "journal_entries_source_type_idx": { + "name": "journal_entries_source_type_idx", + "columns": [ + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "journal_entries_source_uniq": { + "name": "journal_entries_source_uniq", + "columns": [ + { + "expression": "source_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"journal_entries\".\"source_type\" in ('BILL', 'PAYMENT', 'EXPENSE', 'INTEREST')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "journal_entries_reverses_id_journal_entries_id_fk": { + "name": "journal_entries_reverses_id_journal_entries_id_fk", + "tableFrom": "journal_entries", + "tableTo": "journal_entries", + "columnsFrom": [ + "reverses_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "journal_entries_created_by_users_id_fk": { + "name": "journal_entries_created_by_users_id_fk", + "tableFrom": "journal_entries", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.journal_lines": { + "name": "journal_lines", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "entry_id": { + "name": "entry_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "debit": { + "name": "debit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credit": { + "name": "credit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "apartment_id": { + "name": "apartment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "vendor_id": { + "name": "vendor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "memo": { + "name": "memo", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "journal_lines_entry_id_idx": { + "name": "journal_lines_entry_id_idx", + "columns": [ + { + "expression": "entry_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "journal_lines_account_id_idx": { + "name": "journal_lines_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "journal_lines_apartment_id_idx": { + "name": "journal_lines_apartment_id_idx", + "columns": [ + { + "expression": "apartment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "journal_lines_entry_id_journal_entries_id_fk": { + "name": "journal_lines_entry_id_journal_entries_id_fk", + "tableFrom": "journal_lines", + "tableTo": "journal_entries", + "columnsFrom": [ + "entry_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "journal_lines_account_id_accounts_id_fk": { + "name": "journal_lines_account_id_accounts_id_fk", + "tableFrom": "journal_lines", + "tableTo": "accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "journal_lines_apartment_id_apartments_id_fk": { + "name": "journal_lines_apartment_id_apartments_id_fk", + "tableFrom": "journal_lines", + "tableTo": "apartments", + "columnsFrom": [ + "apartment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.expenses": { + "name": "expenses", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "vendor_id": { + "name": "vendor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tax_amount": { + "name": "tax_amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "expense_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'PAID'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bill_ref": { + "name": "bill_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "payment_method", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "paid_at": { + "name": "paid_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "attachment_url": { + "name": "attachment_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recorded_by": { + "name": "recorded_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "expenses_account_id_idx": { + "name": "expenses_account_id_idx", + "columns": [ + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "expenses_vendor_id_idx": { + "name": "expenses_vendor_id_idx", + "columns": [ + { + "expression": "vendor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "expenses_created_at_idx": { + "name": "expenses_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "expenses_vendor_id_vendors_id_fk": { + "name": "expenses_vendor_id_vendors_id_fk", + "tableFrom": "expenses", + "tableTo": "vendors", + "columnsFrom": [ + "vendor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "expenses_account_id_accounts_id_fk": { + "name": "expenses_account_id_accounts_id_fk", + "tableFrom": "expenses", + "tableTo": "accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "expenses_recorded_by_users_id_fk": { + "name": "expenses_recorded_by_users_id_fk", + "tableFrom": "expenses", + "tableTo": "users", + "columnsFrom": [ + "recorded_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tds_entries": { + "name": "tds_entries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "expense_id": { + "name": "expense_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "section": { + "name": "section", + "type": "tds_section", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "rate_pct": { + "name": "rate_pct", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "deducted_at": { + "name": "deducted_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tds_entries_expense_id_idx": { + "name": "tds_entries_expense_id_idx", + "columns": [ + { + "expression": "expense_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tds_entries_section_idx": { + "name": "tds_entries_section_idx", + "columns": [ + { + "expression": "section", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tds_entries_expense_id_expenses_id_fk": { + "name": "tds_entries_expense_id_expenses_id_fk", + "tableFrom": "tds_entries", + "tableTo": "expenses", + "columnsFrom": [ + "expense_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vendors": { + "name": "vendors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pan": { + "name": "pan", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gstin": { + "name": "gstin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contact": { + "name": "contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "bank_account": { + "name": "bank_account", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.push_deliveries": { + "name": "push_deliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "ticket_id": { + "name": "ticket_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "push_deliveries_event_device_idx": { + "name": "push_deliveries_event_device_idx", + "columns": [ + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "push_deliveries_pending_idx": { + "name": "push_deliveries_pending_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "push_deliveries_token_push_devices_token_fk": { + "name": "push_deliveries_token_push_devices_token_fk", + "tableFrom": "push_deliveries", + "tableTo": "push_devices", + "columnsFrom": [ + "token" + ], + "columnsTo": [ + "token" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "push_deliveries_user_id_users_id_fk": { + "name": "push_deliveries_user_id_users_id_fk", + "tableFrom": "push_deliveries", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.push_devices": { + "name": "push_devices", + "schema": "", + "columns": { + "token": { + "name": "token", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "push_devices_user_idx": { + "name": "push_devices_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "push_devices_user_id_users_id_fk": { + "name": "push_devices_user_id_users_id_fk", + "tableFrom": "push_devices", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.account_type": { + "name": "account_type", + "schema": "public", + "values": [ + "ASSET", + "LIABILITY", + "INCOME", + "EXPENSE", + "FUND" + ] + }, + "public.background_check_status": { + "name": "background_check_status", + "schema": "public", + "values": [ + "PENDING", + "CLEARED", + "FLAGGED" + ] + }, + "public.bhk_type": { + "name": "bhk_type", + "schema": "public", + "values": [ + "STUDIO", + "1BHK", + "2BHK", + "3BHK", + "4BHK", + "5BHK", + "PENTHOUSE" + ] + }, + "public.bill_status": { + "name": "bill_status", + "schema": "public", + "values": [ + "ISSUED", + "PARTIALLY_PAID", + "PAID", + "CANCELLED" + ] + }, + "public.bill_type": { + "name": "bill_type", + "schema": "public", + "values": [ + "MONTHLY", + "ONE_TIME" + ] + }, + "public.expense_status": { + "name": "expense_status", + "schema": "public", + "values": [ + "PAID", + "PAYABLE" + ] + }, + "public.house_help_type": { + "name": "house_help_type", + "schema": "public", + "values": [ + "MAID", + "COOK", + "DRIVER", + "NANNY", + "GARDENER", + "CARETAKER", + "OTHER" + ] + }, + "public.id_proof_type": { + "name": "id_proof_type", + "schema": "public", + "values": [ + "AADHAAR", + "PAN", + "VOTER_ID", + "DRIVING_LICENSE", + "PASSPORT", + "OTHER" + ] + }, + "public.journal_source": { + "name": "journal_source", + "schema": "public", + "values": [ + "BILL", + "PAYMENT", + "EXPENSE", + "INTEREST", + "WAIVER", + "MANUAL", + "OPENING", + "ADJUSTMENT" + ] + }, + "public.notice_category": { + "name": "notice_category", + "schema": "public", + "values": [ + "GENERAL", + "MAINTENANCE", + "EVENT", + "SECURITY", + "BILLING", + "EMERGENCY" + ] + }, + "public.notice_priority": { + "name": "notice_priority", + "schema": "public", + "values": [ + "LOW", + "NORMAL", + "HIGH", + "URGENT" + ] + }, + "public.parking_slot_type": { + "name": "parking_slot_type", + "schema": "public", + "values": [ + "COVERED", + "OPEN" + ] + }, + "public.payment_method": { + "name": "payment_method", + "schema": "public", + "values": [ + "CASH", + "CHEQUE", + "UPI", + "BANK_TRANSFER", + "ONLINE" + ] + }, + "public.pre_approval_type": { + "name": "pre_approval_type", + "schema": "public", + "values": [ + "ALWAYS", + "SCHEDULED", + "ONE_TIME" + ] + }, + "public.residency_relation": { + "name": "residency_relation", + "schema": "public", + "values": [ + "OWNER", + "TENANT", + "FAMILY" + ] + }, + "public.tds_section": { + "name": "tds_section", + "schema": "public", + "values": [ + "SEC_194C", + "SEC_194J", + "SEC_194I" + ] + }, + "public.ticket_category": { + "name": "ticket_category", + "schema": "public", + "values": [ + "PLUMBING", + "ELECTRICAL", + "CARPENTRY", + "HOUSEKEEPING", + "SECURITY", + "OTHER" + ] + }, + "public.ticket_priority": { + "name": "ticket_priority", + "schema": "public", + "values": [ + "LOW", + "NORMAL", + "HIGH", + "URGENT" + ] + }, + "public.ticket_status": { + "name": "ticket_status", + "schema": "public", + "values": [ + "OPEN", + "IN_PROGRESS", + "RESOLVED", + "CLOSED", + "CANCELLED" + ] + }, + "public.user_role": { + "name": "user_role", + "schema": "public", + "values": [ + "RESIDENT", + "GUARD", + "ADMIN", + "STAFF" + ] + }, + "public.user_status": { + "name": "user_status", + "schema": "public", + "values": [ + "PENDING", + "APPROVED", + "SUSPENDED" + ] + }, + "public.vehicle_type": { + "name": "vehicle_type", + "schema": "public", + "values": [ + "CAR", + "BIKE", + "SCOOTER", + "BICYCLE", + "OTHER" + ] + }, + "public.visitor_status": { + "name": "visitor_status", + "schema": "public", + "values": [ + "PENDING", + "APPROVED", + "DENIED", + "ENTERED", + "EXITED", + "CANCELLED", + "EXPIRED" + ] + }, + "public.visitor_type": { + "name": "visitor_type", + "schema": "public", + "values": [ + "GUEST", + "DELIVERY", + "SERVICE", + "CAB", + "OTHER" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index a2bd01e..5d1ed23 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -169,6 +169,13 @@ "when": 1790936419384, "tag": "0023_push_delivery", "breakpoints": true + }, + { + "idx": 24, + "version": "7", + "when": 1790945943441, + "tag": "0024_monthly_bill_uniqueness", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/finance.ts b/packages/db/src/schema/finance.ts index 80505be..ef11d1d 100644 --- a/packages/db/src/schema/finance.ts +++ b/packages/db/src/schema/finance.ts @@ -1,4 +1,5 @@ -import { pgTable, uuid, text, integer, timestamp, index } from 'drizzle-orm/pg-core' +import { pgTable, uuid, text, integer, timestamp, index, uniqueIndex } from 'drizzle-orm/pg-core' +import { sql } from 'drizzle-orm' import { apartments } from './apartments' import { users } from './users' import { accounts } from './ledger' @@ -29,6 +30,8 @@ export const maintenanceBills = pgTable('maintenance_bills', { }, (t) => [ index('maintenance_bills_apartment_id_idx').on(t.apartmentId), index('maintenance_bills_period_month_idx').on(t.periodMonth), + uniqueIndex('maintenance_bills_monthly_apartment_uniq').on(t.apartmentId, t.periodMonth) + .where(sql`${t.type} = 'MONTHLY' and ${t.periodMonth} is not null`), ]) // A single charge on a bill, with its own GST rate (percent). taxAmount is the diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dc26d9b..6b1e364 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -21,9 +21,15 @@ importers: apps/api: dependencies: + '@aws-sdk/client-s3': + specifier: ^3.1145.0 + version: 3.1145.0 '@clerk/backend': specifier: ^1.21.0 version: 1.34.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(svix@1.96.1) + '@hono/node-server': + specifier: ^2.1.3 + version: 2.1.3(hono@4.10.1) '@hono/zod-validator': specifier: ^0.4.2 version: 0.4.3(hono@4.10.1)(zod@3.25.76) @@ -58,9 +64,18 @@ importers: '@opensociety/eslint-config': specifier: workspace:* version: link:../../packages/eslint-config + '@types/node': + specifier: ^22.10.2 + version: 22.20.5 + esbuild: + specifier: ^0.28.2 + version: 0.28.2 eslint: specifier: ^9.18.0 version: 9.39.4(jiti@2.7.0) + tsx: + specifier: ^4.19.2 + version: 4.20.6 typescript: specifier: ^5.7.2 version: 5.9.2 @@ -218,6 +233,9 @@ importers: '@clerk/tanstack-react-start': specifier: ^1.4.12 version: 1.4.12(@tanstack/react-router@1.160.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(@tanstack/react-start@1.160.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vite@7.1.10(@types/node@22.20.5)(jiti@2.7.0)(lightningcss@1.30.1)(terser@5.51.2)(tsx@4.20.6)(yaml@2.9.1)))(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + '@hono/node-server': + specifier: ^2.1.3 + version: 2.1.3(hono@4.10.1) '@opensociety/shared': specifier: workspace:* version: link:../../packages/shared @@ -260,6 +278,9 @@ importers: clsx: specifier: ^2.1.1 version: 2.1.1 + hono: + specifier: ^4.10.1 + version: 4.10.1 lucide-react: specifier: ^0.545.0 version: 0.545.0(react@19.2.3) @@ -395,6 +416,78 @@ packages: '@asamuzakjp/nwsapi@2.3.9': resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} + '@aws-sdk/checksums@3.1001.1': + resolution: {integrity: sha512-x12Q17KYlJAd3nKf8LV5LV0vt8sh8/6YfQLGPtrGnQf/tW4jqxPGq5GPpuVitpQYM3eUR4XB7CbxZf751NMbLw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/client-s3@3.1145.0': + resolution: {integrity: sha512-MPKAQdx8qCZW1/ChDPILNehtAn/BMP4GNTnaH/xhGCWg3v50ADVq1K2WzxIrFfeANdWUyjwiY0CXDBhclsNWgQ==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/core@3.978.1': + resolution: {integrity: sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-env@3.972.72': + resolution: {integrity: sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-http@3.972.74': + resolution: {integrity: sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-ini@3.973.17': + resolution: {integrity: sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-login@3.972.79': + resolution: {integrity: sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-node@3.972.84': + resolution: {integrity: sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-process@3.972.72': + resolution: {integrity: sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-sso@3.973.16': + resolution: {integrity: sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-web-identity@3.972.78': + resolution: {integrity: sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/middleware-sdk-s3@3.972.77': + resolution: {integrity: sha512-E7W2UOeUoc+lg3uIfR/dM7ZwusHwhBQrKMnlkRv4EXRR+C0YtV1pg25xC7GdZIhXH+NAMgZPCbE7o5to2cjFiw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/nested-clients@3.997.46': + resolution: {integrity: sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/signature-v4-multi-region@3.996.47': + resolution: {integrity: sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/token-providers@3.1138.0': + resolution: {integrity: sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/types@3.974.6': + resolution: {integrity: sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/xml-builder@3.972.41': + resolution: {integrity: sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==} + engines: {node: '>=20.0.0'} + + '@aws/lambda-invoke-store@0.3.0': + resolution: {integrity: sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==} + engines: {node: '>=18.0.0'} + '@babel/code-frame@7.27.1': resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==} engines: {node: '>=6.9.0'} @@ -1072,6 +1165,12 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + '@esbuild/android-arm64@0.17.19': resolution: {integrity: sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==} engines: {node: '>=12'} @@ -1096,6 +1195,12 @@ packages: cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm@0.17.19': resolution: {integrity: sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==} engines: {node: '>=12'} @@ -1120,6 +1225,12 @@ packages: cpu: [arm] os: [android] + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + '@esbuild/android-x64@0.17.19': resolution: {integrity: sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==} engines: {node: '>=12'} @@ -1144,6 +1255,12 @@ packages: cpu: [x64] os: [android] + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + '@esbuild/darwin-arm64@0.17.19': resolution: {integrity: sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==} engines: {node: '>=12'} @@ -1168,6 +1285,12 @@ packages: cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-x64@0.17.19': resolution: {integrity: sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==} engines: {node: '>=12'} @@ -1192,6 +1315,12 @@ packages: cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + '@esbuild/freebsd-arm64@0.17.19': resolution: {integrity: sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==} engines: {node: '>=12'} @@ -1216,6 +1345,12 @@ packages: cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-x64@0.17.19': resolution: {integrity: sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==} engines: {node: '>=12'} @@ -1240,6 +1375,12 @@ packages: cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + '@esbuild/linux-arm64@0.17.19': resolution: {integrity: sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==} engines: {node: '>=12'} @@ -1264,6 +1405,12 @@ packages: cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm@0.17.19': resolution: {integrity: sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==} engines: {node: '>=12'} @@ -1288,6 +1435,12 @@ packages: cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + '@esbuild/linux-ia32@0.17.19': resolution: {integrity: sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==} engines: {node: '>=12'} @@ -1312,6 +1465,12 @@ packages: cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-loong64@0.17.19': resolution: {integrity: sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==} engines: {node: '>=12'} @@ -1336,6 +1495,12 @@ packages: cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-mips64el@0.17.19': resolution: {integrity: sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==} engines: {node: '>=12'} @@ -1360,6 +1525,12 @@ packages: cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-ppc64@0.17.19': resolution: {integrity: sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==} engines: {node: '>=12'} @@ -1384,6 +1555,12 @@ packages: cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-riscv64@0.17.19': resolution: {integrity: sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==} engines: {node: '>=12'} @@ -1408,6 +1585,12 @@ packages: cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-s390x@0.17.19': resolution: {integrity: sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==} engines: {node: '>=12'} @@ -1432,6 +1615,12 @@ packages: cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-x64@0.17.19': resolution: {integrity: sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==} engines: {node: '>=12'} @@ -1456,12 +1645,24 @@ packages: cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/netbsd-arm64@0.25.5': resolution: {integrity: sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + '@esbuild/netbsd-x64@0.17.19': resolution: {integrity: sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==} engines: {node: '>=12'} @@ -1486,12 +1687,24 @@ packages: cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/openbsd-arm64@0.25.5': resolution: {integrity: sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + '@esbuild/openbsd-x64@0.17.19': resolution: {integrity: sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==} engines: {node: '>=12'} @@ -1516,6 +1729,18 @@ packages: cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + '@esbuild/sunos-x64@0.17.19': resolution: {integrity: sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==} engines: {node: '>=12'} @@ -1540,6 +1765,12 @@ packages: cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + '@esbuild/win32-arm64@0.17.19': resolution: {integrity: sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==} engines: {node: '>=12'} @@ -1564,6 +1795,12 @@ packages: cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-ia32@0.17.19': resolution: {integrity: sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==} engines: {node: '>=12'} @@ -1588,6 +1825,12 @@ packages: cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-x64@0.17.19': resolution: {integrity: sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==} engines: {node: '>=12'} @@ -1612,6 +1855,12 @@ packages: cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@eslint-community/eslint-utils@4.9.1': resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -1875,6 +2124,12 @@ packages: '@formkit/auto-animate@0.8.4': resolution: {integrity: sha512-DHHC01EJ1p70Q0z/ZFRBIY8NDnmfKccQoyoM84Tgb6omLMat6jivCdf272Y8k3nf4Lzdin/Y4R9q8uFtU0GbnA==} + '@hono/node-server@2.1.3': + resolution: {integrity: sha512-TA//nWMqPhbfdfneACk6t5a9eqbS9lABEPyKn0/xZTah3H3U2XaVg85rJFl0/Fyit0I552YDHgXGVSf3GwqbUw==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 + '@hono/zod-validator@0.4.3': resolution: {integrity: sha512-xIgMYXDyJ4Hj6ekm9T9Y27s080Nl9NXHcJkOvkXPhubOLj8hZkOL8pDnnXfvCf5xEE8Q4oMFenQUZZREUY2gqQ==} peerDependencies: @@ -2835,6 +3090,30 @@ packages: '@sinclair/typebox@0.27.8': resolution: {integrity: sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==} + '@smithy/core@3.35.1': + resolution: {integrity: sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w==} + engines: {node: '>=18.0.0'} + + '@smithy/credential-provider-imds@4.5.2': + resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==} + engines: {node: '>=18.0.0'} + + '@smithy/fetch-http-handler@5.8.0': + resolution: {integrity: sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==} + engines: {node: '>=18.0.0'} + + '@smithy/node-http-handler@4.12.1': + resolution: {integrity: sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==} + engines: {node: '>=18.0.0'} + + '@smithy/signature-v4@5.7.4': + resolution: {integrity: sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==} + engines: {node: '>=18.0.0'} + + '@smithy/types@4.19.0': + resolution: {integrity: sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==} + engines: {node: '>=18.0.0'} + '@solana-mobile/mobile-wallet-adapter-protocol-web3js@2.2.9': resolution: {integrity: sha512-TAMItAuOb7duwYQ+PZ6JNqw/6TEhCWLObHF5uOBGV9tjCozHGVunxa7lTeuHAWIgO68IAo86MZdE5kethDATpw==} peerDependencies: @@ -4380,6 +4659,9 @@ packages: borsh@0.7.0: resolution: {integrity: sha512-CLCsZGIBCFnPtkNnieW/a8wmreDmfUtjU2m9yHrzPXIlNbqVs0AQrSatSG6vdNYUqdc83tkQi2eHfF98ubzQLA==} + bowser@2.14.1: + resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==} + bplist-creator@0.1.0: resolution: {integrity: sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==} @@ -5026,6 +5308,11 @@ packages: engines: {node: '>=18'} hasBin: true + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -8168,6 +8455,171 @@ snapshots: '@asamuzakjp/nwsapi@2.3.9': {} + '@aws-sdk/checksums@3.1001.1': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/client-s3@3.1145.0': + dependencies: + '@aws-sdk/checksums': 3.1001.1 + '@aws-sdk/core': 3.978.1 + '@aws-sdk/credential-provider-node': 3.972.84 + '@aws-sdk/middleware-sdk-s3': 3.972.77 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/core@3.978.1': + dependencies: + '@aws-sdk/types': 3.974.6 + '@aws-sdk/xml-builder': 3.972.41 + '@aws/lambda-invoke-store': 0.3.0 + '@smithy/core': 3.35.1 + '@smithy/signature-v4': 5.7.4 + '@smithy/types': 4.19.0 + bowser: 2.14.1 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-env@3.972.72': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-http@3.972.74': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-ini@3.973.17': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/credential-provider-env': 3.972.72 + '@aws-sdk/credential-provider-http': 3.972.74 + '@aws-sdk/credential-provider-login': 3.972.79 + '@aws-sdk/credential-provider-process': 3.972.72 + '@aws-sdk/credential-provider-sso': 3.973.16 + '@aws-sdk/credential-provider-web-identity': 3.972.78 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/credential-provider-imds': 4.5.2 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-login@3.972.79': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-node@3.972.84': + dependencies: + '@aws-sdk/credential-provider-env': 3.972.72 + '@aws-sdk/credential-provider-http': 3.972.74 + '@aws-sdk/credential-provider-ini': 3.973.17 + '@aws-sdk/credential-provider-process': 3.972.72 + '@aws-sdk/credential-provider-sso': 3.973.16 + '@aws-sdk/credential-provider-web-identity': 3.972.78 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/credential-provider-imds': 4.5.2 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-process@3.972.72': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-sso@3.973.16': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/token-providers': 3.1138.0 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-web-identity@3.972.78': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/middleware-sdk-s3@3.972.77': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/nested-clients@3.997.46': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/signature-v4-multi-region@3.996.47': + dependencies: + '@aws-sdk/types': 3.974.6 + '@smithy/signature-v4': 5.7.4 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/token-providers@3.1138.0': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/types@3.974.6': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/xml-builder@3.972.41': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws/lambda-invoke-store@0.3.0': {} + '@babel/code-frame@7.27.1': dependencies: '@babel/helper-validator-identifier': 7.29.7 @@ -9039,6 +9491,9 @@ snapshots: '@esbuild/aix-ppc64@0.25.5': optional: true + '@esbuild/aix-ppc64@0.28.2': + optional: true + '@esbuild/android-arm64@0.17.19': optional: true @@ -9051,6 +9506,9 @@ snapshots: '@esbuild/android-arm64@0.25.5': optional: true + '@esbuild/android-arm64@0.28.2': + optional: true + '@esbuild/android-arm@0.17.19': optional: true @@ -9063,6 +9521,9 @@ snapshots: '@esbuild/android-arm@0.25.5': optional: true + '@esbuild/android-arm@0.28.2': + optional: true + '@esbuild/android-x64@0.17.19': optional: true @@ -9075,6 +9536,9 @@ snapshots: '@esbuild/android-x64@0.25.5': optional: true + '@esbuild/android-x64@0.28.2': + optional: true + '@esbuild/darwin-arm64@0.17.19': optional: true @@ -9087,6 +9551,9 @@ snapshots: '@esbuild/darwin-arm64@0.25.5': optional: true + '@esbuild/darwin-arm64@0.28.2': + optional: true + '@esbuild/darwin-x64@0.17.19': optional: true @@ -9099,6 +9566,9 @@ snapshots: '@esbuild/darwin-x64@0.25.5': optional: true + '@esbuild/darwin-x64@0.28.2': + optional: true + '@esbuild/freebsd-arm64@0.17.19': optional: true @@ -9111,6 +9581,9 @@ snapshots: '@esbuild/freebsd-arm64@0.25.5': optional: true + '@esbuild/freebsd-arm64@0.28.2': + optional: true + '@esbuild/freebsd-x64@0.17.19': optional: true @@ -9123,6 +9596,9 @@ snapshots: '@esbuild/freebsd-x64@0.25.5': optional: true + '@esbuild/freebsd-x64@0.28.2': + optional: true + '@esbuild/linux-arm64@0.17.19': optional: true @@ -9135,6 +9611,9 @@ snapshots: '@esbuild/linux-arm64@0.25.5': optional: true + '@esbuild/linux-arm64@0.28.2': + optional: true + '@esbuild/linux-arm@0.17.19': optional: true @@ -9147,6 +9626,9 @@ snapshots: '@esbuild/linux-arm@0.25.5': optional: true + '@esbuild/linux-arm@0.28.2': + optional: true + '@esbuild/linux-ia32@0.17.19': optional: true @@ -9159,6 +9641,9 @@ snapshots: '@esbuild/linux-ia32@0.25.5': optional: true + '@esbuild/linux-ia32@0.28.2': + optional: true + '@esbuild/linux-loong64@0.17.19': optional: true @@ -9171,6 +9656,9 @@ snapshots: '@esbuild/linux-loong64@0.25.5': optional: true + '@esbuild/linux-loong64@0.28.2': + optional: true + '@esbuild/linux-mips64el@0.17.19': optional: true @@ -9183,6 +9671,9 @@ snapshots: '@esbuild/linux-mips64el@0.25.5': optional: true + '@esbuild/linux-mips64el@0.28.2': + optional: true + '@esbuild/linux-ppc64@0.17.19': optional: true @@ -9195,6 +9686,9 @@ snapshots: '@esbuild/linux-ppc64@0.25.5': optional: true + '@esbuild/linux-ppc64@0.28.2': + optional: true + '@esbuild/linux-riscv64@0.17.19': optional: true @@ -9207,6 +9701,9 @@ snapshots: '@esbuild/linux-riscv64@0.25.5': optional: true + '@esbuild/linux-riscv64@0.28.2': + optional: true + '@esbuild/linux-s390x@0.17.19': optional: true @@ -9219,6 +9716,9 @@ snapshots: '@esbuild/linux-s390x@0.25.5': optional: true + '@esbuild/linux-s390x@0.28.2': + optional: true + '@esbuild/linux-x64@0.17.19': optional: true @@ -9231,9 +9731,15 @@ snapshots: '@esbuild/linux-x64@0.25.5': optional: true + '@esbuild/linux-x64@0.28.2': + optional: true + '@esbuild/netbsd-arm64@0.25.5': optional: true + '@esbuild/netbsd-arm64@0.28.2': + optional: true + '@esbuild/netbsd-x64@0.17.19': optional: true @@ -9246,9 +9752,15 @@ snapshots: '@esbuild/netbsd-x64@0.25.5': optional: true + '@esbuild/netbsd-x64@0.28.2': + optional: true + '@esbuild/openbsd-arm64@0.25.5': optional: true + '@esbuild/openbsd-arm64@0.28.2': + optional: true + '@esbuild/openbsd-x64@0.17.19': optional: true @@ -9261,6 +9773,12 @@ snapshots: '@esbuild/openbsd-x64@0.25.5': optional: true + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + '@esbuild/sunos-x64@0.17.19': optional: true @@ -9273,6 +9791,9 @@ snapshots: '@esbuild/sunos-x64@0.25.5': optional: true + '@esbuild/sunos-x64@0.28.2': + optional: true + '@esbuild/win32-arm64@0.17.19': optional: true @@ -9285,6 +9806,9 @@ snapshots: '@esbuild/win32-arm64@0.25.5': optional: true + '@esbuild/win32-arm64@0.28.2': + optional: true + '@esbuild/win32-ia32@0.17.19': optional: true @@ -9297,6 +9821,9 @@ snapshots: '@esbuild/win32-ia32@0.25.5': optional: true + '@esbuild/win32-ia32@0.28.2': + optional: true + '@esbuild/win32-x64@0.17.19': optional: true @@ -9309,6 +9836,9 @@ snapshots: '@esbuild/win32-x64@0.25.5': optional: true + '@esbuild/win32-x64@0.28.2': + optional: true + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4(jiti@2.7.0))': dependencies: eslint: 9.39.4(jiti@2.7.0) @@ -9770,6 +10300,10 @@ snapshots: '@formkit/auto-animate@0.8.4': {} + '@hono/node-server@2.1.3(hono@4.10.1)': + dependencies: + hono: 4.10.1 + '@hono/zod-validator@0.4.3(hono@4.10.1)(zod@3.25.76)': dependencies: hono: 4.10.1 @@ -10657,6 +11191,39 @@ snapshots: '@sinclair/typebox@0.27.8': {} + '@smithy/core@3.35.1': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/credential-provider-imds@4.5.2': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/fetch-http-handler@5.8.0': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/node-http-handler@4.12.1': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/signature-v4@5.7.4': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/types@4.19.0': + dependencies: + tslib: 2.8.1 + '@solana-mobile/mobile-wallet-adapter-protocol-web3js@2.2.9(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@6.0.3)(utf-8-validate@6.0.6))(bufferutil@4.1.0)(react-native@0.86.3(@babel/core@7.29.0)(@react-native/metro-config@0.86.0(@babel/core@7.29.0))(@types/react@19.2.18)(bufferutil@4.1.0)(react@19.2.3)(utf-8-validate@6.0.6))(typescript@6.0.3)(utf-8-validate@6.0.6)': dependencies: '@solana-mobile/mobile-wallet-adapter-protocol': 2.2.9(bufferutil@4.1.0)(react-native@0.86.3(@babel/core@7.29.0)(@react-native/metro-config@0.86.0(@babel/core@7.29.0))(@types/react@19.2.18)(bufferutil@4.1.0)(react@19.2.3)(utf-8-validate@6.0.6))(typescript@6.0.3)(utf-8-validate@6.0.6) @@ -12530,6 +13097,8 @@ snapshots: bs58: 4.0.1 text-encoding-utf-8: 1.0.2 + bowser@2.14.1: {} + bplist-creator@0.1.0: dependencies: stream-buffers: 2.2.0 @@ -13284,6 +13853,35 @@ snapshots: '@esbuild/win32-ia32': 0.25.5 '@esbuild/win32-x64': 0.25.5 + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escalade@3.2.0: {} escape-html@1.0.3: {} diff --git a/scripts/hosting-smoke.test.mjs b/scripts/hosting-smoke.test.mjs new file mode 100644 index 0000000..2397a6e --- /dev/null +++ b/scripts/hosting-smoke.test.mjs @@ -0,0 +1,61 @@ +import { after, before, test } from 'node:test' +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { setTimeout } from 'node:timers/promises' + +const containers = [] +const docker = (...args) => execFileSync('docker', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() +async function start(image, port, environment = {}) { + const id = docker('run', '-d', '--read-only', '--tmpfs', '/tmp', '--cap-drop=ALL', '--security-opt=no-new-privileges', + '--memory=384m', '-p', `127.0.0.1::${port}`, + ...Object.entries(environment).flatMap(([key, value]) => ['-e', `${key}=${value}`]), image) + containers.push(id) + const address = docker('port', id, `${port}/tcp`) + const base = `http://${address}` + for (let attempt = 0; attempt < 60; attempt++) { + try { if ((await fetch(`${base}/health`)).ok) return base } catch { /* wait for startup */ } + await setTimeout(250) + } + throw new Error(`Container failed to start: ${docker('logs', id)}`) +} + +let api, web +before(async () => { + api = await start('opensociety-api:test', 8787, { + DATABASE_URL: 'postgresql://test:test@localhost/test', APP_ENV: 'staging', + CLERK_SECRET_KEY: 'sk_test_placeholder', WEB_ORIGINS: 'https://society.example.com', + R2_ACCOUNT_ID: 'example', R2_BUCKET_NAME: 'test', R2_ACCESS_KEY_ID: 'test', R2_SECRET_ACCESS_KEY: 'test', + BILLING_ENABLED: 'false', PUSH_ENABLED: 'false', + }) + web = await start('opensociety-web:test', 3000) +}) +after(() => { for (const id of containers) docker('rm', '-f', id) }) + +test('production API serves health and enforces the browser allowlist', async () => { + const response = await fetch(`${api}/health`, { headers: { Origin: 'https://society.example.com' } }) + assert.deepEqual(await response.json(), { status: 'ok' }) + assert.equal(response.headers.get('access-control-allow-origin'), 'https://society.example.com') + const rejected = await fetch(`${api}/health`, { headers: { Origin: 'https://unexpected.example.com' } }) + assert.equal(rejected.headers.get('access-control-allow-origin'), null) +}) + +test('web image renders HTML and serves immutable CSS from its packaged dependencies', async () => { + const response = await fetch(web) + assert.equal(response.status, 200) + const html = await response.text() + assert.match(html, /OpenSociety/) + const cssPath = html.match(/\/assets\/[^"\s]+\.css/)?.[0] + assert.ok(cssPath) + const css = await fetch(`${web}${cssPath}`) + assert.equal(css.status, 200) + assert.match(css.headers.get('content-type'), /text\/css/) + assert.equal(css.headers.get('cache-control'), 'public, max-age=31536000, immutable') +}) + +test('both images run without root and shut down cleanly', () => { + for (const id of containers) { + assert.equal(docker('exec', id, 'id', '-u'), '1000') + docker('stop', '-t', '30', id) + assert.equal(docker('inspect', '--format', '{{.State.ExitCode}}', id), '0') + } +}) diff --git a/turbo.json b/turbo.json index f5a3865..2b63340 100644 --- a/turbo.json +++ b/turbo.json @@ -17,8 +17,15 @@ "dependsOn": ["^build"] }, "dev": { + "dependsOn": ["^build"], "cache": false, - "persistent": true + "persistent": true, + "interruptible": true, + "passThroughEnv": [ + "DATABASE_URL", "CLERK_*", "WEB_ORIGINS", "R2_*", "S3_*", + "BILLING_ENABLED", "PUSH_ENABLED", "EXPO_ACCESS_TOKEN", + "BILL_REMINDER_DAYS", "SOCIETY_TIME_ZONE" + ] } } }