create-protobase 0.53.6 → 0.53.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/templates/erp/package.json +10 -7
  2. package/dist/templates/property-portal/.env.example +18 -0
  3. package/dist/templates/property-portal/API.md +66 -0
  4. package/dist/templates/property-portal/_.gitignore +4 -0
  5. package/dist/templates/property-portal/_bunfig.toml +4 -0
  6. package/dist/templates/property-portal/config/agencies/data.ts +17 -0
  7. package/dist/templates/property-portal/config/agencies/ui.ts +20 -0
  8. package/dist/templates/property-portal/config/alerts/data.ts +20 -0
  9. package/dist/templates/property-portal/config/alerts/ui.ts +18 -0
  10. package/dist/templates/property-portal/config/bottom-bar.test.ts +30 -0
  11. package/dist/templates/property-portal/config/bottom-bar.ts +17 -0
  12. package/dist/templates/property-portal/config/config.test.ts +73 -0
  13. package/dist/templates/property-portal/config/favorites/data.ts +13 -0
  14. package/dist/templates/property-portal/config/favorites/ui.ts +26 -0
  15. package/dist/templates/property-portal/config/home/page.tsx +19 -0
  16. package/dist/templates/property-portal/config/index.ts +18 -0
  17. package/dist/templates/property-portal/config/listing_photos/data.ts +15 -0
  18. package/dist/templates/property-portal/config/listing_photos/ui.ts +20 -0
  19. package/dist/templates/property-portal/config/listings/data.ts +55 -0
  20. package/dist/templates/property-portal/config/listings/labels.ts +40 -0
  21. package/dist/templates/property-portal/config/listings/rules.test.ts +27 -0
  22. package/dist/templates/property-portal/config/listings/rules.ts +25 -0
  23. package/dist/templates/property-portal/config/listings/ui.ts +121 -0
  24. package/dist/templates/property-portal/config/map-layers.test.ts +16 -0
  25. package/dist/templates/property-portal/config/notes/data.ts +19 -0
  26. package/dist/templates/property-portal/config/notes/ui.ts +16 -0
  27. package/dist/templates/property-portal/config/photo-variants.ts +10 -0
  28. package/dist/templates/property-portal/config/places/data.ts +15 -0
  29. package/dist/templates/property-portal/config/places/ui.ts +23 -0
  30. package/dist/templates/property-portal/config/roles.test.ts +89 -0
  31. package/dist/templates/property-portal/config/roles.ts +40 -0
  32. package/dist/templates/property-portal/config/saved_searches/data.ts +25 -0
  33. package/dist/templates/property-portal/config/saved_searches/filter.ts +20 -0
  34. package/dist/templates/property-portal/config/saved_searches/rules.test.ts +14 -0
  35. package/dist/templates/property-portal/config/saved_searches/rules.ts +10 -0
  36. package/dist/templates/property-portal/config/saved_searches/ui.ts +32 -0
  37. package/dist/templates/property-portal/db/connection.ts +7 -0
  38. package/dist/templates/property-portal/db/drop.ts +15 -0
  39. package/dist/templates/property-portal/db/kysely.ts +13 -0
  40. package/dist/templates/property-portal/db/migrate.ts +31 -0
  41. package/dist/templates/property-portal/db/migrations/001_market.sql +101 -0
  42. package/dist/templates/property-portal/db/migrations/002_auth.sql +36 -0
  43. package/dist/templates/property-portal/db/migrations/003_jobs.sql +576 -0
  44. package/dist/templates/property-portal/db/migrations/004_members.sql +71 -0
  45. package/dist/templates/property-portal/db/migrations/005_listing_published.sql +14 -0
  46. package/dist/templates/property-portal/db/migrations/006_price_split.sql +61 -0
  47. package/dist/templates/property-portal/db/migrations/007_listing_position.sql +2 -0
  48. package/dist/templates/property-portal/db/migrations/007_photo_placeholders.sql +4 -0
  49. package/dist/templates/property-portal/db/migrations/008_saved_searches.sql +42 -0
  50. package/dist/templates/property-portal/db/migrations/009_listing_position_exact.sql +3 -0
  51. package/dist/templates/property-portal/db/migrations/010_saved_search_name.sql +3 -0
  52. package/dist/templates/property-portal/db/migrations/011_filter_indexes.sql +36 -0
  53. package/dist/templates/property-portal/db/migrations/012_sort_indexes.sql +4 -0
  54. package/dist/templates/property-portal/db/migrations/013_alert_mail.sql +26 -0
  55. package/dist/templates/property-portal/db/migrations/014_auth.sql +4 -0
  56. package/dist/templates/property-portal/db/migrations/015_auth.sql +319 -0
  57. package/dist/templates/property-portal/emails/alerted-listing.tsx +63 -0
  58. package/dist/templates/property-portal/emails/daily-digest.tsx +26 -0
  59. package/dist/templates/property-portal/emails/emails.test.ts +53 -0
  60. package/dist/templates/property-portal/emails/instant-alert.tsx +26 -0
  61. package/dist/templates/property-portal/jobs/alerted-listings.test.ts +19 -0
  62. package/dist/templates/property-portal/jobs/alerted-listings.ts +42 -0
  63. package/dist/templates/property-portal/jobs/daily-alerts.ts +21 -0
  64. package/dist/templates/property-portal/jobs/email-alerts.ts +44 -0
  65. package/dist/templates/property-portal/jobs/match-listing.ts +30 -0
  66. package/dist/templates/property-portal/jobs/match.test.ts +51 -0
  67. package/dist/templates/property-portal/jobs/match.ts +15 -0
  68. package/dist/templates/property-portal/jobs/offered.test.ts +9 -0
  69. package/dist/templates/property-portal/jobs/offered.ts +12 -0
  70. package/dist/templates/property-portal/map/tiles-proxy.test.ts +78 -0
  71. package/dist/templates/property-portal/map/tiles-proxy.ts +48 -0
  72. package/dist/templates/property-portal/map/tiles.ts +16 -0
  73. package/dist/templates/property-portal/node-types.d.ts +1 -0
  74. package/dist/templates/property-portal/package.json +42 -0
  75. package/dist/templates/property-portal/protobase.config.ts +57 -0
  76. package/dist/templates/property-portal/protobase.ui.tsx +21 -0
  77. package/dist/templates/property-portal/seed/builders/agency.ts +22 -0
  78. package/dist/templates/property-portal/seed/builders/distance.test.ts +14 -0
  79. package/dist/templates/property-portal/seed/builders/distance.ts +12 -0
  80. package/dist/templates/property-portal/seed/builders/listing.ts +177 -0
  81. package/dist/templates/property-portal/seed/builders/member.ts +136 -0
  82. package/dist/templates/property-portal/seed/builders/search-filter.test.ts +17 -0
  83. package/dist/templates/property-portal/seed/builders/search-filter.ts +44 -0
  84. package/dist/templates/property-portal/seed/calendar.ts +4 -0
  85. package/dist/templates/property-portal/seed/cli.ts +50 -0
  86. package/dist/templates/property-portal/seed/copy.ts +22 -0
  87. package/dist/templates/property-portal/seed/data/names.ts +61 -0
  88. package/dist/templates/property-portal/seed/data/places.ts +54 -0
  89. package/dist/templates/property-portal/seed/format.ts +20 -0
  90. package/dist/templates/property-portal/seed/maintenance.ts +65 -0
  91. package/dist/templates/property-portal/seed/photos/canvas.ts +48 -0
  92. package/dist/templates/property-portal/seed/photos/draw.ts +202 -0
  93. package/dist/templates/property-portal/seed/photos/library.ts +44 -0
  94. package/dist/templates/property-portal/seed/photos/png.ts +34 -0
  95. package/dist/templates/property-portal/seed/rng.ts +36 -0
  96. package/dist/templates/property-portal/seed/scales.ts +9 -0
  97. package/dist/templates/property-portal/seed/steps/market.ts +54 -0
  98. package/dist/templates/property-portal/seed/steps/members.ts +41 -0
  99. package/dist/templates/property-portal/seed/world.ts +98 -0
  100. package/dist/templates/property-portal/tsconfig.json +24 -0
  101. package/dist/templates/property-portal/vitest.config.ts +4 -0
  102. package/dist/templates/real-estate/package.json +10 -7
  103. package/dist/templates/scratch/package.json +10 -7
  104. package/package.json +2 -2
@@ -21,15 +21,18 @@
21
21
  "kysely": "^0.29.6",
22
22
  "pg": "^8.23.1",
23
23
  "postgres": "^3.4.9",
24
- "react": "^19.3.0"
24
+ "react": "^19.3.0",
25
+ "react-email": "^6.11.1",
26
+ "sharp": "^0.35.5",
27
+ "zod": "^4.6.5"
25
28
  },
26
29
  "devDependencies": {
27
- "@protobase/cli": "^0.53.6",
28
- "@protobase/config": "^0.53.6",
29
- "@protobase/layout": "^0.53.6",
30
- "@protobase/schema": "^0.53.6",
31
- "@protobase/server": "^0.53.6",
32
- "@protobase/ui": "^0.53.6",
30
+ "@protobase/cli": "^0.53.7",
31
+ "@protobase/config": "^0.53.7",
32
+ "@protobase/layout": "^0.53.7",
33
+ "@protobase/schema": "^0.53.7",
34
+ "@protobase/server": "^0.53.7",
35
+ "@protobase/ui": "^0.53.7",
33
36
  "@types/node": "^22.20.5",
34
37
  "@types/pg": "^8.23.1",
35
38
  "@types/react": "^19.3.0",
@@ -0,0 +1,18 @@
1
+ # The property portal example's own settings. The nearest .env wins, so this file, not the repository's, is the one
2
+ # `protobase dev`, `protobase serve` and the db:* scripts read here. The Postgres container is the repository's (`bun run db:up`).
3
+ DATABASE_URL=postgres://protobase:protobase@localhost:55432/property_portal
4
+
5
+ # Admin store (Better Auth users, sessions, signing keys): the `auth` schema of DATABASE_URL, created by `db:migrate`.
6
+ PROTOBASE_URL=http://localhost:5173
7
+ # Signs cookies and encrypts the token keys. Generate your own: openssl rand -base64 32
8
+ PROTOBASE_SECRET=change-me-generate-with-openssl-rand-base64-32
9
+ # PROTOBASE_TRUSTED_ORIGINS=
10
+
11
+ # Search alert mail and sign-up codes: the SMTP server and the sender. Without them alerts still show in the app, nothing
12
+ # is mailed, and the sign-in page offers no "Create an account".
13
+ # PROTOBASE_SMTP_URL=smtp://localhost:1025
14
+ # PROTOBASE_MAIL_FROM=alerts@portal.example.com
15
+
16
+ # The listing page's map: a MapLibre style URL. This one is `bun run map:tiles`, the development tiles (the Benelux and
17
+ # the British Isles in detail). Point it at your own self-hosted style and PMTiles; without it the app draws no map.
18
+ PROTOBASE_MAP_STYLE_URL=http://localhost:8790/style.json
@@ -0,0 +1,66 @@
1
+ # Property portal API walkthrough
2
+
3
+ Every resource of the portal is also a REST API at `/api/v1/<resource>`, described by an OpenAPI 3.1 document the server generates for the caller: `/api/openapi.json`, with an interactive reference at `/api/docs`. Both list only what the caller's role may see and do, so they need a token ([REST API](https://docs.protobase.net/reference/api/)).
4
+
5
+ Start the example as in the [README](README.md#start); the commands below use `curl` and `jq` against `http://localhost:5173`.
6
+
7
+ ```sh
8
+ BASE=http://localhost:5173
9
+ ```
10
+
11
+ ## Sign in and get a token
12
+
13
+ Sign in with a seeded account, keeping the session cookie, then exchange the session for an API token. The token lasts 15 minutes; ask for a new one the same way.
14
+
15
+ ```sh
16
+ curl -s -c cookies.txt "$BASE/api/auth/sign-in/email" \
17
+ -H 'content-type: application/json' \
18
+ -d '{"email":"admin@portal.example","password":"property-portal-demo"}' > /dev/null
19
+ TOKEN=$(curl -s -b cookies.txt "$BASE/api/auth/token" | jq -r .token)
20
+ ```
21
+
22
+ ## The OpenAPI document
23
+
24
+ ```sh
25
+ curl -s "$BASE/api/openapi.json" -H "authorization: Bearer $TOKEN" | jq '.paths | keys | map(select(startswith("/listings")))'
26
+ ```
27
+
28
+ ## List published listings
29
+
30
+ Visitors need no token: without one the request is the `anonymous` role, which reads published listings only, without the agent.
31
+
32
+ ```sh
33
+ curl -s -G "$BASE/api/v1/listings" \
34
+ --data-urlencode "filter=for_sale = true AND status = 'available'" \
35
+ --data-urlencode "order_by=published_at desc" \
36
+ --data-urlencode "fields=id,address,purchase_price,published_at" \
37
+ --data-urlencode "page_size=5" | jq .items
38
+ ```
39
+
40
+ ## Create a listing as admin and publish it
41
+
42
+ A new listing without `published_at` is a draft that only admins see. The answer carries its `id` and `etag`.
43
+
44
+ ```sh
45
+ CREATED=$(curl -s "$BASE/api/v1/listings" -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{
46
+ "agency_id": 1, "place_id": 1, "property_type": "apartment",
47
+ "address": "Prinsengracht 263", "postal_code": "1016 GV", "latitude": "52.375200", "longitude": "4.883900",
48
+ "purchase_price": "650000", "living_area": 85, "rooms": 3, "bedrooms": 2, "energy_label": "b",
49
+ "description": "Canal-side apartment with a view.", "agent_name": "Sanne Visser", "agent_phone": "+31 20 123 4567"
50
+ }')
51
+ ID=$(echo "$CREATED" | jq -r .id)
52
+ ETAG=$(echo "$CREATED" | jq -r .etag)
53
+ ```
54
+
55
+ Publishing is setting `published_at`. An update needs the record's `etag` in `If-Match`, so it never overwrites a change it has not seen. Publishing also matches the listing against the members' saved searches ([Alerts](README.md#alerts)).
56
+
57
+ ```sh
58
+ curl -s -X PATCH "$BASE/api/v1/listings/$ID" -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
59
+ -H "if-match: $ETAG" -d "{\"published_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" | jq '{id, published_at}'
60
+ ```
61
+
62
+ Now visitors see it:
63
+
64
+ ```sh
65
+ curl -s "$BASE/api/v1/listings/$ID?fields=id,address,purchase_price,published_at" | jq '{id, address, purchase_price, published_at}'
66
+ ```
@@ -0,0 +1,4 @@
1
+ node_modules
2
+ dist
3
+ /data
4
+ .env
@@ -0,0 +1,4 @@
1
+ # `bun run` runs scripts and package bins on Bun even when Node is on PATH, whose `#!/usr/bin/env node` would otherwise
2
+ # start Node.
3
+ [run]
4
+ bun = true
@@ -0,0 +1,17 @@
1
+ import { f, resource } from '@protobase/schema'
2
+
3
+ /** market.agencies: an estate agent (makelaar, inmobiliaria) that lists homes on the portal. */
4
+ export const agencies = resource('agencies')
5
+ .table('market.agencies')
6
+ .fields({
7
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
8
+ name: f.text().filterable().sortable(),
9
+ place_id: f.relation('places').filterable().sortable(),
10
+ phone: f.text(),
11
+ email: f.text().regex(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'An email address, such as info@agency.example'),
12
+ website: f.text().regex(/^https:\/\//, 'A web address starting with https://'),
13
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
14
+ updated_at: f.timestamp().readOnly().dbDefault(),
15
+ })
16
+ .primaryKey((r) => r.id)
17
+ .search((r) => [r.name])
@@ -0,0 +1,20 @@
1
+ import { l, view } from '@protobase/schema'
2
+ import type { agencies } from './data'
3
+
4
+ export const agenciesView = view<typeof agencies>('agencies')
5
+ .title((r) => r.name)
6
+ .names({ singular: 'Agency', plural: 'Agencies' })
7
+ .recordMode('read')
8
+ .helpWhen('editing')
9
+ .nav({ group: 'Browse', order: 2 })
10
+ .fields((r) => ({
11
+ place_id: r.place_id.label('Office in'),
12
+ website: r.website.label('Website'),
13
+ }))
14
+ .list((r) => ({ columns: [r.name, r.place_id, r.phone, r.website], sort: [[r.name, 'asc']], search: [r.name] }))
15
+ .filters((r, w) => [w.facets(r.place_id, { search: true })])
16
+ .layout((r) => [
17
+ l.section('Agency', [r.name, r.place_id]),
18
+ l.section('Contact', [r.phone, r.email, r.website]),
19
+ l.related('Listings', { resource: 'listings', field: 'agency_id', sort: 'published_at desc', columns: ['address', 'place_id', 'purchase_price', 'rent_price', 'status'] }),
20
+ ])
@@ -0,0 +1,20 @@
1
+ import { f, resource } from '@protobase/schema'
2
+
3
+ /**
4
+ * members.alerts: a published listing that fits one of a member's saved searches, recorded by the match-listing job.
5
+ * `emailed_at` is when it went out by mail, at once or in the daily digest; one found while its search sent no email is
6
+ * never mailed (db/migrations/013_alert_mail.sql). Theirs alone (`.own` on `user_id`), which Postgres keeps equal to the
7
+ * search's owner. Unique: (saved_search_id, listing_id).
8
+ */
9
+ export const alerts = resource('alerts')
10
+ .table('members.alerts')
11
+ .fields({
12
+ id: f.bigint().readOnly().filterable().sortable().dbDefault(),
13
+ user_id: f.text().readOnly().filterable(),
14
+ saved_search_id: f.relation('saved_searches').readOnly().filterable().sortable(),
15
+ listing_id: f.relation('listings').readOnly().filterable().sortable(),
16
+ matched_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
17
+ emailed_at: f.timestamp().readOnly().optional().filterable().sortable(),
18
+ })
19
+ .primaryKey((r) => r.id)
20
+ .owner((r) => r.user_id)
@@ -0,0 +1,18 @@
1
+ import { l, view } from '@protobase/schema'
2
+ import type { alerts } from './data'
3
+
4
+ export const alertsView = view<typeof alerts>('alerts')
5
+ .title((r) => r.listing_id)
6
+ .names({ singular: 'Alert', plural: 'Alerts' })
7
+ .nav({ group: 'Yours', order: 3 })
8
+ .help('The new listings your saved searches found, and when they were mailed.')
9
+ .fields((r) => ({
10
+ listing_id: r.listing_id.label('Listing'),
11
+ saved_search_id: r.saved_search_id.label('Search'),
12
+ matched_at: r.matched_at.label('Found'),
13
+ emailed_at: r.emailed_at.label('Mailed').help('Empty until it is mailed, while the app sends no mail, or when the search sent no email as the listing was found.'),
14
+ }))
15
+ .list((r) => ({ columns: [r.listing_id, r.saved_search_id, r.matched_at, r.emailed_at], sort: [[r.matched_at, 'desc']] }))
16
+ .filters((r, w) => [w.facets(r.saved_search_id), w.dateRange(r.matched_at, { presets: ['7d', '30d', '90d'] })])
17
+ .layout((r) => [l.section('Alert', [r.listing_id, r.saved_search_id, r.matched_at, r.emailed_at]), l.sidebar([r.matched_at, r.emailed_at])])
18
+ .actions((a) => [a.link('open_listing', { label: 'Open the listing', to: { kind: 'record', resource: 'listings', key: '{listing_id}' } })])
@@ -0,0 +1,30 @@
1
+ import sharp from 'sharp'
2
+ import { configExports, createAdmin } from '@protobase/server'
3
+ import { describe, expect, it } from 'vitest'
4
+ import * as config from './index'
5
+ import { roles } from './roles'
6
+
7
+ describe('the portal mobile bottom bars', () => {
8
+ const { resources, views, pages, bottomBars } = configExports(config)
9
+
10
+ it('gives members, admins and visitors home, listings, favorites and searches', () => {
11
+ expect(bottomBars.map((bar) => bar.toBottomBarModel())).toEqual([
12
+ expect.objectContaining({ label: 'Portal', roles: ['member', 'admin'], items: [
13
+ { kind: 'page', page: 'home', label: 'Home' },
14
+ { kind: 'resource', resource: 'listings', label: 'Listings' },
15
+ { kind: 'resource', resource: 'favorites', label: 'Favorites', icon: 'heart' },
16
+ { kind: 'resource', resource: 'saved_searches', label: 'Searches', icon: 'bookmark' },
17
+ ] }),
18
+ expect.objectContaining({ label: 'Browse', roles: ['anonymous'], items: [
19
+ { kind: 'page', page: 'home', label: 'Home' },
20
+ { kind: 'resource', resource: 'listings', label: 'Listings' },
21
+ { kind: 'resource', resource: 'favorites', label: 'Favorites', icon: 'heart' },
22
+ { kind: 'resource', resource: 'saved_searches', label: 'Searches', icon: 'bookmark' },
23
+ ] }),
24
+ ])
25
+ })
26
+
27
+ it('fits the resources, pages and roles', () => {
28
+ expect(() => createAdmin({ resources, views, pages, bottomBars, db: {} as never, files: { secret: 'config-test-secret', sharp }, authenticate: () => { throw new Error('No requests in this test') }, options: { roles } })).not.toThrow()
29
+ })
30
+ })
@@ -0,0 +1,17 @@
1
+ import { bottomBar } from '@protobase/schema'
2
+
3
+ /** The mobile bottom bar of members and admins: their main screens as tabs; "More" opens the rest, alerts, notes and the catalogue. */
4
+ export const memberBar = bottomBar({ label: 'Portal', roles: ['member', 'admin'] }, (m) => [
5
+ m.page('home', { label: 'Home' }),
6
+ m.resource('listings', { label: 'Listings' }),
7
+ m.resource('favorites', { label: 'Favorites', icon: 'heart' }),
8
+ m.resource('saved_searches', { label: 'Searches', icon: 'bookmark' }),
9
+ ])
10
+
11
+ /** The mobile bottom bar of a visitor who is not signed in: the home page, the listings, and favorites and searches, which tell them to sign in. */
12
+ export const visitorBar = bottomBar({ label: 'Browse', roles: ['anonymous'] }, (m) => [
13
+ m.page('home', { label: 'Home' }),
14
+ m.resource('listings', { label: 'Listings' }),
15
+ m.resource('favorites', { label: 'Favorites', icon: 'heart' }),
16
+ m.resource('saved_searches', { label: 'Searches', icon: 'bookmark' }),
17
+ ])
@@ -0,0 +1,73 @@
1
+ import type { LayoutItemModel } from '@protobase/schema'
2
+ import sharp from 'sharp'
3
+ import { configExports, createAdmin, MissingCredentials } from '@protobase/server'
4
+ import { describe, expect, it } from 'vitest'
5
+ import * as config from './index'
6
+ import { roles } from './roles'
7
+
8
+ describe('the portal config', () => {
9
+ const { resources, views, pages } = configExports(config)
10
+
11
+ it('passes the checks the server makes at startup: views, pages, role limits and the anonymous role', () => {
12
+ expect(() => createAdmin({ resources, views, db: {} as never, files: { secret: 'config-test-secret', sharp }, authenticate: () => { throw new Error('No requests in this test') }, options: { roles } })).not.toThrow()
13
+ })
14
+
15
+ it('has a view for every table, and more for members and admins on listings and for admins on photos', () => {
16
+ const viewed = views.map((view) => view.toModel())
17
+ expect(resources.map((source) => source.toModel().name).filter((name) => !viewed.some((view) => view.resource === name))).toEqual([])
18
+ expect(viewed.filter((view) => view.resource === 'listings').map((view) => view.roles ?? [])).toEqual([[], ['member'], ['admin']])
19
+ expect(viewed.filter((view) => view.resource === 'listing_photos').map((view) => view.roles ?? [])).toEqual([[], ['admin']])
20
+ expect(pages.map((entry) => entry.name)).toEqual(['home'])
21
+ })
22
+
23
+ it("reads a listing's page as a portal's: the photos in a gallery, the key facts and a table of features, editing help left out", () => {
24
+ const [everyone, members, admins] = views.map((view) => view.toModel()).filter((view) => view.resource === 'listings')
25
+ for (const listing of [everyone!, members!, admins!]) expect(listing).toMatchObject({ recordMode: 'read', helpWhen: 'editing' })
26
+ const titles = (layout: LayoutItemModel[]) => layout.map((item) => ('title' in item ? item.title : item.kind))
27
+ expect(titles(everyone!.layout)).toEqual(['Photos', 'Key facts', 'About this home', 'Features', 'Location', 'Address', 'Viewing', 'sidebar', 'Your notes'])
28
+ expect(everyone!.layout[0]).toEqual({ kind: 'gallery', title: 'Photos', image: 'photo', photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } })
29
+ expect(everyone!.layout.find((item) => item.kind === 'section' && item.title === 'Viewing')).toMatchObject({ helpWhen: 'always' })
30
+ // The key facts are a row of values under their icons, as on a portal
31
+ expect(everyone!.layout.find((item) => item.kind === 'section' && item.title === 'Key facts')).toMatchObject({ presentation: 'facts' })
32
+ expect(['purchase_price', 'living_area', 'bedrooms', 'bathrooms', 'energy_label'].map((name) => everyone!.fields[name]?.icon)).toEqual(['tag', 'ruler', 'bed', 'bath', 'leaf'])
33
+ // What only an editor needs is on the admins' page alone
34
+ expect(titles(admins!.layout).filter((title) => !titles(everyone!.layout).includes(title))).toEqual(['Map position', 'Publishing', 'Photo list'])
35
+ const editorFields = ['latitude', 'longitude', 'position_exact', 'photo']
36
+ const sectionFields = everyone!.layout.flatMap((item) => (item.kind === 'section' ? item.fields : []))
37
+ expect(sectionFields.filter((name) => editorFields.includes(name))).toEqual([])
38
+ })
39
+
40
+ it('opens listings as cards with their cover photo and arrows through the rest, offers them on a map, and starts a note from a listing with the listing chosen', () => {
41
+ const [everyone, members] = views.map((view) => view.toModel()).filter((view) => view.resource === 'listings')
42
+ expect(everyone!.list).toMatchObject({
43
+ default: 'cards',
44
+ displays: [
45
+ { kind: 'cards', image: 'photo', title: 'address', amount: ['purchase_price', 'rent_price'], footer: ['place_id', 'agent_name'], photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } },
46
+ { kind: 'map', name: 'map', label: 'Map', latitude: 'latitude', longitude: 'longitude' },
47
+ ],
48
+ })
49
+ expect(everyone!.actions).toEqual([])
50
+ expect(members!.actions.find((action) => action.name === 'add_note')?.run).toEqual({ kind: 'link', to: { kind: 'create', resource: 'notes', values: { listing_id: '{id}' } } })
51
+ })
52
+
53
+ it('saves a listing from its card to favorites, whose page lists the saved listings, and asks a visitor to sign in for both', async () => {
54
+ const [everyone] = views.map((view) => view.toModel()).filter((view) => view.resource === 'listings')
55
+ expect(everyone!.list?.displays?.[0]).toMatchObject({ favorite: { resource: 'favorites', field: 'listing_id' } })
56
+ const visitor = createAdmin({ resources, views, pages, bottomBars: configExports(config).bottomBars, db: {} as never, files: { secret: 'config-test-secret', sharp }, authenticate: () => { throw new MissingCredentials('No token in this test') }, options: { roles } })
57
+ const meta = (await (await visitor.request('/api/meta')).json()) as { signIn: Array<{ resource: string; signIn: { title: string } }>; views: Array<{ resource: string; list?: { displays?: unknown[] } }> }
58
+ expect(meta.signIn.map((entry) => [entry.resource, entry.signIn.title])).toEqual([['saved_searches', 'Hear of new homes first'], ['favorites', 'Keep the homes you like']])
59
+ expect(meta.views.find((view) => view.resource === 'listings')?.list?.displays?.[0]).toMatchObject({ favorite: { resource: 'favorites' } })
60
+ expect(views.map((view) => view.toModel()).find((view) => view.resource === 'favorites')?.listOf).toBe('listing_id')
61
+ })
62
+
63
+ it('saves the filtered listings as a search, whose page shows the listings new since it was last opened, and asks a visitor to sign in', async () => {
64
+ const models = views.map((view) => view.toModel())
65
+ expect(models.find((view) => view.resource === 'listings')?.saveSearch).toEqual({ resource: 'saved_searches' })
66
+ expect(models.find((view) => view.resource === 'saved_searches')?.searchesOf).toEqual({
67
+ resource: 'listings', filter: 'filter', name: 'name', controls: ['alert_frequency'], unseen: { seenAt: 'seen_at', field: 'published_at' },
68
+ })
69
+ const visitor = createAdmin({ resources, views, pages, db: {} as never, files: { secret: 'config-test-secret', sharp }, authenticate: () => { throw new MissingCredentials('No token in this test') }, options: { roles } })
70
+ const meta = (await (await visitor.request('/api/meta')).json()) as { views: Array<{ resource: string; saveSearch?: unknown }> }
71
+ expect(meta.views.find((view) => view.resource === 'listings')?.saveSearch).toEqual({ resource: 'saved_searches' })
72
+ })
73
+ })
@@ -0,0 +1,13 @@
1
+ import { f, resource } from '@protobase/schema'
2
+
3
+ /** members.favorites: a listing a member saved, theirs alone (`.own` on `user_id`). Unique: (user_id, listing_id). */
4
+ export const favorites = resource('favorites')
5
+ .table('members.favorites')
6
+ .fields({
7
+ id: f.bigint().readOnly().filterable().sortable().dbDefault(),
8
+ user_id: f.text().readOnly().filterable(),
9
+ listing_id: f.relation('listings').filterable().sortable(),
10
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
11
+ })
12
+ .primaryKey((r) => r.id)
13
+ .owner((r) => r.user_id)
@@ -0,0 +1,26 @@
1
+ import { l, view } from '@protobase/schema'
2
+ import type { favorites } from './data'
3
+
4
+ /**
5
+ * A member's favorites: the list page shows the listings they saved, in the listings' cards and map, and a visitor is
6
+ * told what signing in gives there and by the heart on a listing's card.
7
+ */
8
+ export const favoritesView = view<typeof favorites>('favorites')
9
+ .title((r) => r.listing_id)
10
+ .names({ singular: 'Favorite', plural: 'Favorites' })
11
+ .nav({ group: 'Yours', order: 1 })
12
+ .help('The listings you saved. Save one with the heart on its card, or "Save to favorites" on its page.')
13
+ .fields((r) => ({ listing_id: r.listing_id.label('Listing'), created_at: r.created_at.label('Saved') }))
14
+ .list((r) => ({ columns: [r.listing_id, r.created_at], sort: [[r.created_at, 'desc']] }))
15
+ .listOf((r) => r.listing_id)
16
+ .signIn({
17
+ title: 'Keep the homes you like',
18
+ description: 'Sign in to save listings to your favorites and find them again on any device.',
19
+ benefits: ['Save a listing with the heart on its card', 'See all your saved homes on one page, on the map too', 'Add notes only you can read'],
20
+ icon: 'heart',
21
+ })
22
+ .layout((r) => [l.section('Favorite', [r.listing_id, r.created_at])])
23
+ .actions((a) => [
24
+ a.link('open_listing', { label: 'Open the listing', to: { kind: 'record', resource: 'listings', key: '{listing_id}' } }),
25
+ a.remove('unsave', { label: 'Remove from favorites', confirm: 'Remove this listing from your favorites?' }),
26
+ ])
@@ -0,0 +1,19 @@
1
+ /** @jsxImportSource @protobase/layout */
2
+ import { Page, RecordRow, page } from '@protobase/layout'
3
+
4
+ /**
5
+ * Where the portal opens: rows of the listings on offer, each with its filters and how many there are, and the newest,
6
+ * for everyone; and a member's favorites and what each of their searches finds below them. A visitor's page leaves out
7
+ * what they cannot read, the member's parts.
8
+ */
9
+ export const home = page(
10
+ 'home',
11
+ <Page title="Find a home" description="Houses and apartments for sale and for rent in the Netherlands and Spain, from the agencies on the portal.">
12
+ <RecordRow title="For sale" resource="listings" filter="for_sale = true AND status = 'available'" sort="published_at desc" />
13
+ <RecordRow title="For rent" resource="listings" filter="for_rent = true AND status = 'available'" sort="published_at desc" />
14
+ <RecordRow title="Newest listings" resource="listings" sort="published_at desc" limit={24} />
15
+ <RecordRow title="Your searches" resource="saved_searches" empty="Nothing yet. Filter the listings and save the search to hear of new ones." />
16
+ <RecordRow title="Your favorites" resource="favorites" empty="Save a listing with the heart on its card." />
17
+ </Page>,
18
+ { nav: { group: 'Browse', order: 0 }, icon: 'layout-dashboard' },
19
+ )
@@ -0,0 +1,18 @@
1
+ export { places } from './places/data'
2
+ export { placesView } from './places/ui'
3
+ export { agencies } from './agencies/data'
4
+ export { agenciesView } from './agencies/ui'
5
+ export { listings } from './listings/data'
6
+ export { listingsView, memberListingsView, adminListingsView } from './listings/ui'
7
+ export { listingPhotos } from './listing_photos/data'
8
+ export { listingPhotosView, adminListingPhotosView } from './listing_photos/ui'
9
+ export { savedSearches } from './saved_searches/data'
10
+ export { savedSearchesView } from './saved_searches/ui'
11
+ export { alerts } from './alerts/data'
12
+ export { alertsView } from './alerts/ui'
13
+ export { favorites } from './favorites/data'
14
+ export { favoritesView } from './favorites/ui'
15
+ export { notes } from './notes/data'
16
+ export { notesView } from './notes/ui'
17
+ export { home } from './home/page'
18
+ export { memberBar, visitorBar } from './bottom-bar'
@@ -0,0 +1,15 @@
1
+ import { f, resource } from '@protobase/schema'
2
+ import { photoVariants } from '../photo-variants'
3
+
4
+ /** market.listing_photos: the photos of a listing, in order. Unique: (listing_id, position). */
5
+ export const listingPhotos = resource('listing_photos')
6
+ .table('market.listing_photos')
7
+ .fields({
8
+ id: f.bigint().readOnly().filterable().sortable().dbDefault(),
9
+ listing_id: f.relation('listings').filterable().sortable(),
10
+ position: f.integer().min(1).sortable(),
11
+ photo: f.file().accept(['image/*']).public().placeholder('photo_placeholder').variants(photoVariants),
12
+ photo_placeholder: f.text().readOnly().optional(),
13
+ caption: f.text().optional(),
14
+ })
15
+ .primaryKey((r) => r.id)
@@ -0,0 +1,20 @@
1
+ import { l, view } from '@protobase/schema'
2
+ import type { listingPhotos } from './data'
3
+
4
+ /**
5
+ * Reached from a listing's page, where the lightbox shows a photo's caption beside it; the sidebar leaves the photos
6
+ * out. Its own page shows the photo, then its caption and listing.
7
+ */
8
+ export const listingPhotosView = view<typeof listingPhotos>('listing_photos')
9
+ .names({ singular: 'Photo', plural: 'Photos' })
10
+ .nav({ hidden: true })
11
+ .recordMode('read')
12
+ .helpWhen('editing')
13
+ .fields((r) => ({ listing_id: r.listing_id.label('Listing'), position: r.position.help('1 is shown first.') }))
14
+ .list((r, d) => ({ columns: [r.listing_id, r.position, r.caption, r.photo], sort: [[r.listing_id, 'asc'], [r.position, 'asc']], displays: [d.cards({ image: r.photo, title: r.caption, subtitle: r.listing_id })] }))
15
+ .layout((r) => [l.gallery('Photo', { image: r.photo }), l.section('Photo details', [r.caption, r.listing_id])])
16
+
17
+ /** Admins also place the photo among the listing's and upload its file. */
18
+ export const adminListingPhotosView = listingPhotosView
19
+ .layout((r) => [l.gallery('Photo', { image: r.photo }), l.section('Photo details', [r.caption, r.listing_id]), l.section('Order and file', [r.position, r.photo])])
20
+ .forRoles(['admin'])
@@ -0,0 +1,55 @@
1
+ import { f, resource } from '@protobase/schema'
2
+ import { photoVariants } from '../photo-variants'
3
+ import { listingIssues } from './rules'
4
+
5
+ export const energyLabels = ['a_plus_4', 'a_plus_3', 'a_plus_2', 'a_plus', 'a', 'b', 'c', 'd', 'e', 'f', 'g'] as const
6
+ export const propertyTypes = ['apartment', 'house', 'townhouse', 'villa', 'studio', 'penthouse'] as const
7
+ export const listingStatuses = ['available', 'under_offer', 'sold', 'let'] as const
8
+
9
+ /**
10
+ * market.listings: a home for sale, for rent, or both, as a Dutch home for sale is often let in the meantime
11
+ * (leegstandswet). `purchase_price` is the asking price and `rent_price` the rent per month; at least one is set, and
12
+ * Postgres computes from them whether it is `for_sale` and `for_rent`, and `price_per_m2` from the purchase price. A
13
+ * listing is public from `published_at`, a draft while that is empty; publishing one asks the match-listing job for the
14
+ * saved searches it fits (db/migrations/005_listing_published.sql).
15
+ */
16
+ export const listings = resource('listings')
17
+ .table('market.listings')
18
+ .fields({
19
+ id: f.bigint().readOnly().filterable().sortable().dbDefault(),
20
+ agency_id: f.relation('agencies').filterable().sortable(),
21
+ place_id: f.relation('places').filterable().sortable(),
22
+ property_type: f.enum(propertyTypes).filterable().sortable(),
23
+ status: f.enum(listingStatuses).default('available').filterable().sortable(),
24
+ address: f.text().filterable().sortable(),
25
+ postal_code: f.text().filterable(),
26
+ latitude: f.decimal({ precision: 8, scale: 6 }).filterable(),
27
+ longitude: f.decimal({ precision: 9, scale: 6 }).filterable(),
28
+ position_exact: f.boolean().default(true),
29
+ purchase_price: f.decimal({ precision: 12, scale: 2 }).optional().filterable().sortable(),
30
+ rent_price: f.decimal({ precision: 12, scale: 2 }).optional().filterable().sortable(),
31
+ for_sale: f.boolean().readOnly().filterable().sortable(),
32
+ for_rent: f.boolean().readOnly().filterable().sortable(),
33
+ living_area: f.integer().min(1).filterable().sortable(),
34
+ price_per_m2: f.decimal({ precision: 10, scale: 2 }).readOnly().optional().filterable().sortable(),
35
+ plot_area: f.integer().min(1).optional().filterable().sortable(),
36
+ rooms: f.integer().min(1).filterable().sortable(),
37
+ bedrooms: f.integer().min(0).filterable().sortable(),
38
+ bathrooms: f.integer().min(0).default(1),
39
+ built_year: f.integer().min(1500).max(2100).optional().filterable().sortable(),
40
+ energy_label: f.enum(energyLabels).optional().filterable().sortable(),
41
+ garden: f.boolean().default(false).filterable(),
42
+ balcony: f.boolean().default(false).filterable(),
43
+ parking: f.boolean().default(false).filterable(),
44
+ description: f.text(),
45
+ photo: f.file().accept(['image/*']).public().optional().placeholder('photo_placeholder').variants(photoVariants),
46
+ photo_placeholder: f.text().readOnly().optional(),
47
+ agent_name: f.text(),
48
+ agent_phone: f.text(),
49
+ published_at: f.timestamp().optional().filterable().sortable(),
50
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
51
+ updated_at: f.timestamp().readOnly().dbDefault(),
52
+ })
53
+ .primaryKey((r) => r.id)
54
+ .search((r) => [r.address, r.postal_code])
55
+ .validate(listingIssues)
@@ -0,0 +1,40 @@
1
+ import type { energyLabels, propertyTypes } from './data'
2
+
3
+ /** How the listing's values read. */
4
+ export const propertyTypeLabels: Record<(typeof propertyTypes)[number], string> = {
5
+ apartment: 'Apartment',
6
+ house: 'House',
7
+ townhouse: 'Townhouse',
8
+ villa: 'Villa',
9
+ studio: 'Studio',
10
+ penthouse: 'Penthouse',
11
+ }
12
+
13
+ export const energyLabelLabels: Record<(typeof energyLabels)[number], string> = {
14
+ a_plus_4: 'A++++',
15
+ a_plus_3: 'A+++',
16
+ a_plus_2: 'A++',
17
+ a_plus: 'A+',
18
+ a: 'A',
19
+ b: 'B',
20
+ c: 'C',
21
+ d: 'D',
22
+ e: 'E',
23
+ f: 'F',
24
+ g: 'G',
25
+ }
26
+
27
+ /** The colours of the EU energy label for buildings, from dark green for the best label to red for G. */
28
+ export const energyLabelColors: Record<(typeof energyLabels)[number], string> = {
29
+ a_plus_4: '#00612e',
30
+ a_plus_3: '#006f35',
31
+ a_plus_2: '#007d3c',
32
+ a_plus: '#008c43',
33
+ a: '#00a651',
34
+ b: '#50b848',
35
+ c: '#bed630',
36
+ d: '#fff200',
37
+ e: '#fdb913',
38
+ f: '#f37021',
39
+ g: '#ed1c24',
40
+ }
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { listingIssues } from './rules'
3
+
4
+ // A flat for sale, as a write would store it.
5
+ const flat = { purchase_price: '450000.00', rent_price: null, status: 'available', rooms: 3, bedrooms: 2 }
6
+
7
+ describe('listingIssues', () => {
8
+ it('takes a purchase price, a rent or both', () => {
9
+ expect(listingIssues(flat)).toBeUndefined()
10
+ expect(listingIssues({ ...flat, purchase_price: null, rent_price: '1450.00' })).toBeUndefined()
11
+ expect(listingIssues({ ...flat, rent_price: '1450.00' })).toBeUndefined()
12
+ expect(listingIssues({ ...flat, purchase_price: null })).toEqual([{ field: 'purchase_price', message: 'A purchase price, a rent or both' }])
13
+ expect(listingIssues({ ...flat, purchase_price: '', rent_price: undefined })).toEqual([{ field: 'purchase_price', message: 'A purchase price, a rent or both' }])
14
+ })
15
+
16
+ it('is sold only with a purchase price and let only with a rent', () => {
17
+ expect(listingIssues({ ...flat, status: 'sold' })).toBeUndefined()
18
+ expect(listingIssues({ ...flat, status: 'let' })).toEqual([{ field: 'status', message: 'Let needs a rent' }])
19
+ expect(listingIssues({ ...flat, purchase_price: null, rent_price: '1450.00', status: 'sold' })).toEqual([{ field: 'status', message: 'Sold needs a purchase price' }])
20
+ expect(listingIssues({ ...flat, rent_price: '1450.00', status: 'let' })).toBeUndefined()
21
+ })
22
+
23
+ it('has fewer bedrooms than rooms', () => {
24
+ expect(listingIssues({ ...flat, bedrooms: 3 })).toEqual([{ field: 'bedrooms', message: 'Fewer bedrooms than rooms: the living room is a room too' }])
25
+ expect(listingIssues({ ...flat, bedrooms: undefined })).toBeUndefined()
26
+ })
27
+ })
@@ -0,0 +1,25 @@
1
+ /** The fields of a listing its rules read, as a write gives them: the record as it would be stored. */
2
+ export type ListingRecord = {
3
+ purchase_price?: string | number | null
4
+ rent_price?: string | number | null
5
+ status?: string | null
6
+ rooms?: string | number | null
7
+ bedrooms?: string | number | null
8
+ }
9
+
10
+ const missing = (value: unknown) => value === undefined || value === null || value === ''
11
+
12
+ /**
13
+ * What is wrong with a listing, by field, before Postgres refuses it: it needs a price to buy or to rent it for, can be
14
+ * sold only with a purchase price and let only with a rent, and has fewer bedrooms than rooms.
15
+ */
16
+ export const listingIssues = (record: ListingRecord) => {
17
+ const issues: Array<{ field: keyof ListingRecord; message: string }> = []
18
+ if (missing(record.purchase_price) && missing(record.rent_price)) issues.push({ field: 'purchase_price', message: 'A purchase price, a rent or both' })
19
+ if (record.status === 'sold' && missing(record.purchase_price)) issues.push({ field: 'status', message: 'Sold needs a purchase price' })
20
+ if (record.status === 'let' && missing(record.rent_price)) issues.push({ field: 'status', message: 'Let needs a rent' })
21
+ if (!missing(record.bedrooms) && !missing(record.rooms) && Number(record.bedrooms) >= Number(record.rooms)) {
22
+ issues.push({ field: 'bedrooms', message: 'Fewer bedrooms than rooms: the living room is a room too' })
23
+ }
24
+ return issues.length > 0 ? issues : undefined
25
+ }