create-protobase 0.53.6 → 0.53.8
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.
- package/dist/templates/erp/package.json +10 -7
- package/dist/templates/property-portal/.env.example +18 -0
- package/dist/templates/property-portal/API.md +66 -0
- package/dist/templates/property-portal/_.gitignore +4 -0
- package/dist/templates/property-portal/_bunfig.toml +4 -0
- package/dist/templates/property-portal/config/agencies/data.ts +17 -0
- package/dist/templates/property-portal/config/agencies/ui.ts +20 -0
- package/dist/templates/property-portal/config/alerts/data.ts +20 -0
- package/dist/templates/property-portal/config/alerts/ui.ts +18 -0
- package/dist/templates/property-portal/config/bottom-bar.test.ts +30 -0
- package/dist/templates/property-portal/config/bottom-bar.ts +17 -0
- package/dist/templates/property-portal/config/config.test.ts +73 -0
- package/dist/templates/property-portal/config/favorites/data.ts +13 -0
- package/dist/templates/property-portal/config/favorites/ui.ts +26 -0
- package/dist/templates/property-portal/config/home/page.tsx +19 -0
- package/dist/templates/property-portal/config/index.ts +18 -0
- package/dist/templates/property-portal/config/listing_photos/data.ts +15 -0
- package/dist/templates/property-portal/config/listing_photos/ui.ts +20 -0
- package/dist/templates/property-portal/config/listings/data.ts +55 -0
- package/dist/templates/property-portal/config/listings/labels.ts +40 -0
- package/dist/templates/property-portal/config/listings/rules.test.ts +27 -0
- package/dist/templates/property-portal/config/listings/rules.ts +25 -0
- package/dist/templates/property-portal/config/listings/ui.ts +121 -0
- package/dist/templates/property-portal/config/map-layers.test.ts +16 -0
- package/dist/templates/property-portal/config/notes/data.ts +19 -0
- package/dist/templates/property-portal/config/notes/ui.ts +16 -0
- package/dist/templates/property-portal/config/photo-variants.ts +10 -0
- package/dist/templates/property-portal/config/places/data.ts +15 -0
- package/dist/templates/property-portal/config/places/ui.ts +23 -0
- package/dist/templates/property-portal/config/roles.test.ts +89 -0
- package/dist/templates/property-portal/config/roles.ts +40 -0
- package/dist/templates/property-portal/config/saved_searches/data.ts +25 -0
- package/dist/templates/property-portal/config/saved_searches/filter.ts +20 -0
- package/dist/templates/property-portal/config/saved_searches/rules.test.ts +14 -0
- package/dist/templates/property-portal/config/saved_searches/rules.ts +10 -0
- package/dist/templates/property-portal/config/saved_searches/ui.ts +32 -0
- package/dist/templates/property-portal/db/connection.ts +7 -0
- package/dist/templates/property-portal/db/drop.ts +15 -0
- package/dist/templates/property-portal/db/kysely.ts +13 -0
- package/dist/templates/property-portal/db/migrate.ts +31 -0
- package/dist/templates/property-portal/db/migrations/001_market.sql +101 -0
- package/dist/templates/property-portal/db/migrations/002_auth.sql +36 -0
- package/dist/templates/property-portal/db/migrations/003_jobs.sql +576 -0
- package/dist/templates/property-portal/db/migrations/004_members.sql +71 -0
- package/dist/templates/property-portal/db/migrations/005_listing_published.sql +14 -0
- package/dist/templates/property-portal/db/migrations/006_price_split.sql +61 -0
- package/dist/templates/property-portal/db/migrations/007_listing_position.sql +2 -0
- package/dist/templates/property-portal/db/migrations/007_photo_placeholders.sql +4 -0
- package/dist/templates/property-portal/db/migrations/008_saved_searches.sql +42 -0
- package/dist/templates/property-portal/db/migrations/009_listing_position_exact.sql +3 -0
- package/dist/templates/property-portal/db/migrations/010_saved_search_name.sql +3 -0
- package/dist/templates/property-portal/db/migrations/011_filter_indexes.sql +36 -0
- package/dist/templates/property-portal/db/migrations/012_sort_indexes.sql +4 -0
- package/dist/templates/property-portal/db/migrations/013_alert_mail.sql +26 -0
- package/dist/templates/property-portal/db/migrations/014_auth.sql +4 -0
- package/dist/templates/property-portal/db/migrations/015_auth.sql +319 -0
- package/dist/templates/property-portal/emails/alerted-listing.tsx +63 -0
- package/dist/templates/property-portal/emails/daily-digest.tsx +26 -0
- package/dist/templates/property-portal/emails/emails.test.ts +53 -0
- package/dist/templates/property-portal/emails/instant-alert.tsx +26 -0
- package/dist/templates/property-portal/jobs/alerted-listings.test.ts +19 -0
- package/dist/templates/property-portal/jobs/alerted-listings.ts +42 -0
- package/dist/templates/property-portal/jobs/daily-alerts.ts +21 -0
- package/dist/templates/property-portal/jobs/email-alerts.ts +44 -0
- package/dist/templates/property-portal/jobs/match-listing.ts +30 -0
- package/dist/templates/property-portal/jobs/match.test.ts +51 -0
- package/dist/templates/property-portal/jobs/match.ts +15 -0
- package/dist/templates/property-portal/jobs/offered.test.ts +9 -0
- package/dist/templates/property-portal/jobs/offered.ts +12 -0
- package/dist/templates/property-portal/map/tiles-proxy.test.ts +78 -0
- package/dist/templates/property-portal/map/tiles-proxy.ts +48 -0
- package/dist/templates/property-portal/map/tiles.ts +16 -0
- package/dist/templates/property-portal/node-types.d.ts +1 -0
- package/dist/templates/property-portal/package.json +42 -0
- package/dist/templates/property-portal/protobase.config.ts +57 -0
- package/dist/templates/property-portal/protobase.ui.tsx +21 -0
- package/dist/templates/property-portal/seed/builders/agency.ts +22 -0
- package/dist/templates/property-portal/seed/builders/distance.test.ts +14 -0
- package/dist/templates/property-portal/seed/builders/distance.ts +12 -0
- package/dist/templates/property-portal/seed/builders/listing.ts +177 -0
- package/dist/templates/property-portal/seed/builders/member.ts +136 -0
- package/dist/templates/property-portal/seed/builders/search-filter.test.ts +17 -0
- package/dist/templates/property-portal/seed/builders/search-filter.ts +44 -0
- package/dist/templates/property-portal/seed/calendar.ts +4 -0
- package/dist/templates/property-portal/seed/cli.ts +50 -0
- package/dist/templates/property-portal/seed/copy.ts +22 -0
- package/dist/templates/property-portal/seed/data/names.ts +61 -0
- package/dist/templates/property-portal/seed/data/places.ts +54 -0
- package/dist/templates/property-portal/seed/format.ts +20 -0
- package/dist/templates/property-portal/seed/maintenance.ts +65 -0
- package/dist/templates/property-portal/seed/photos/canvas.ts +48 -0
- package/dist/templates/property-portal/seed/photos/draw.ts +202 -0
- package/dist/templates/property-portal/seed/photos/library.ts +44 -0
- package/dist/templates/property-portal/seed/photos/png.ts +34 -0
- package/dist/templates/property-portal/seed/rng.ts +36 -0
- package/dist/templates/property-portal/seed/scales.ts +9 -0
- package/dist/templates/property-portal/seed/steps/market.ts +54 -0
- package/dist/templates/property-portal/seed/steps/members.ts +41 -0
- package/dist/templates/property-portal/seed/world.ts +98 -0
- package/dist/templates/property-portal/tsconfig.json +24 -0
- package/dist/templates/property-portal/vitest.config.ts +4 -0
- package/dist/templates/real-estate/package.json +10 -7
- package/dist/templates/scratch/package.json +10 -7
- package/package.json +2 -2
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { l, view } from '@protobase/schema'
|
|
2
|
+
import type { listings } from './data'
|
|
3
|
+
import { energyLabelColors, energyLabelLabels, propertyTypeLabels } from './labels'
|
|
4
|
+
|
|
5
|
+
// A listing's further photos, after its cover: on its cards and in its page's gallery.
|
|
6
|
+
const photos = { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' }
|
|
7
|
+
|
|
8
|
+
const keyFactsHelp = 'A purchase price, a rent or both: a home for sale can be let in the meantime.'
|
|
9
|
+
const viewingHelp = 'Call the agency or the agent to plan a viewing.'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What everyone sees of a listing: the cards with their photos first, arrows through the rest and a heart to save it,
|
|
13
|
+
* the table and the filters of a portal, and "Save search" to keep the filters set as one of the member's searches. Its
|
|
14
|
+
* page reads as a listing on a portal: the photos, a row of key facts under their icons, the description and a table of
|
|
15
|
+
* its features, without the help lines meant for whoever edits it.
|
|
16
|
+
*/
|
|
17
|
+
export const listingsView = view<typeof listings>('listings')
|
|
18
|
+
.title((r) => r.address)
|
|
19
|
+
.names({ singular: 'Listing', plural: 'Listings' })
|
|
20
|
+
.nav({ group: 'Browse', order: 1 })
|
|
21
|
+
.searchResult((r) => ({ title: r.address, subtitle: r.place_id }))
|
|
22
|
+
.fields((r) => ({
|
|
23
|
+
agency_id: r.agency_id.label('Agency'),
|
|
24
|
+
postal_code: r.postal_code.label('Postal code'),
|
|
25
|
+
place_id: r.place_id.label('Place'),
|
|
26
|
+
property_type: r.property_type.label('Type').valueLabels(propertyTypeLabels).icon('house'),
|
|
27
|
+
status: r.status.format('badge').valueLabels({ available: 'Available', under_offer: 'Under offer', sold: 'Sold', let: 'Let' }),
|
|
28
|
+
purchase_price: r.purchase_price.label('Purchase price').prefix('€').decimals(0).help('The asking price. Empty when the home is not for sale.').icon('tag'),
|
|
29
|
+
rent_price: r.rent_price.label('Rent').prefix('€').suffix(' /month').decimals(0).help('The rent per month. Empty when the home is not for rent.').icon('key'),
|
|
30
|
+
for_sale: r.for_sale.label('For sale'),
|
|
31
|
+
for_rent: r.for_rent.label('For rent'),
|
|
32
|
+
price_per_m2: r.price_per_m2.label('Price per m²').prefix('€').decimals(0).help('From the purchase price.'),
|
|
33
|
+
living_area: r.living_area.label('Living area').suffix(' m²').icon('ruler'),
|
|
34
|
+
plot_area: r.plot_area.label('Plot').suffix(' m²').icon('land-plot'),
|
|
35
|
+
rooms: r.rooms.icon('door-open'),
|
|
36
|
+
bedrooms: r.bedrooms.icon('bed'),
|
|
37
|
+
bathrooms: r.bathrooms.icon('bath'),
|
|
38
|
+
built_year: r.built_year.label('Built'),
|
|
39
|
+
energy_label: r.energy_label.label('Energy label').format('badge').valueLabels(energyLabelLabels).valueColors(energyLabelColors).badgeShape('arrow').icon('leaf'),
|
|
40
|
+
latitude: r.latitude.help('Decimal degrees, WGS84.').decimals(6),
|
|
41
|
+
longitude: r.longitude.help('Decimal degrees, WGS84.').decimals(6),
|
|
42
|
+
position_exact: r.position_exact.label('Exact position').help('Off when the listing gives its position only roughly: the map marks it as approximate.'),
|
|
43
|
+
photo: r.photo.label('Cover photo'),
|
|
44
|
+
description: r.description.multiline(),
|
|
45
|
+
agent_name: r.agent_name.label('Agent'),
|
|
46
|
+
agent_phone: r.agent_phone.label('Agent phone'),
|
|
47
|
+
published_at: r.published_at.label('Published').help('Empty while the listing is a draft that only admins see.'),
|
|
48
|
+
}))
|
|
49
|
+
.list((r, d) => ({
|
|
50
|
+
columns: [r.address, r.place_id, r.property_type, r.purchase_price, r.rent_price, r.living_area, r.rooms, r.energy_label, r.status, r.published_at],
|
|
51
|
+
sort: [[r.published_at, 'desc']],
|
|
52
|
+
search: [r.address, r.postal_code],
|
|
53
|
+
displays: [
|
|
54
|
+
d.cards(
|
|
55
|
+
{ image: r.photo, title: r.address, amount: [r.purchase_price, r.rent_price], badge: r.status, meta: [r.living_area, r.bedrooms, r.energy_label], footer: [r.place_id, r.agent_name], flags: [r.garden, r.balcony, r.parking] },
|
|
56
|
+
{ label: 'Photos', photos, favorite: { resource: 'favorites', field: 'listing_id', label: 'Save to favorites' } },
|
|
57
|
+
),
|
|
58
|
+
d.map({ latitude: r.latitude, longitude: r.longitude, exact: r.position_exact }, { label: 'Map' }),
|
|
59
|
+
],
|
|
60
|
+
default: 'cards',
|
|
61
|
+
}))
|
|
62
|
+
.filters((r, w) => [
|
|
63
|
+
w.flags([r.for_sale, r.for_rent], { label: 'Offer' }),
|
|
64
|
+
w.facets(r.place_id, { search: true }),
|
|
65
|
+
w.facets(r.property_type),
|
|
66
|
+
w.range(r.purchase_price, { histogram: true }),
|
|
67
|
+
w.range(r.rent_price, { histogram: true }),
|
|
68
|
+
w.range(r.living_area),
|
|
69
|
+
w.facets(r.bedrooms),
|
|
70
|
+
w.facets(r.energy_label),
|
|
71
|
+
w.facets(r.status),
|
|
72
|
+
w.toggle(r.garden),
|
|
73
|
+
w.toggle(r.balcony),
|
|
74
|
+
w.toggle(r.parking),
|
|
75
|
+
])
|
|
76
|
+
.saveSearch({ resource: 'saved_searches' })
|
|
77
|
+
.recordMode('read')
|
|
78
|
+
.helpWhen('editing')
|
|
79
|
+
.layout((r) => [
|
|
80
|
+
l.gallery('Photos', { image: r.photo, photos }),
|
|
81
|
+
l.section('Key facts', [r.purchase_price, r.rent_price, r.price_per_m2, r.property_type, r.living_area, r.plot_area, r.rooms, r.bedrooms, r.bathrooms, r.energy_label], { help: keyFactsHelp, presentation: 'facts' }),
|
|
82
|
+
l.section('About this home', [r.description]),
|
|
83
|
+
l.section('Features', [r.built_year, r.garden, r.balcony, r.parking]),
|
|
84
|
+
l.map('Location', { latitude: r.latitude, longitude: r.longitude }),
|
|
85
|
+
l.section('Address', [r.address, r.postal_code, r.place_id]),
|
|
86
|
+
l.section('Viewing', [r.agency_id, r.agent_name, r.agent_phone], { help: viewingHelp, helpWhen: 'always' }),
|
|
87
|
+
l.sidebar([r.published_at]),
|
|
88
|
+
l.related('Your notes', { resource: 'notes', field: 'listing_id', sort: 'updated_at desc', columns: ['body', 'updated_at'], empty: 'No notes yet: only you see the notes you add.' }),
|
|
89
|
+
])
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Signed in, a listing can be saved to favorites, taken off them again, and noted on. The note's form starts with the
|
|
93
|
+
* listing chosen; whoever writes it is its only reader.
|
|
94
|
+
*/
|
|
95
|
+
export const memberListingsView = listingsView
|
|
96
|
+
.actions((a) => [
|
|
97
|
+
a.action('save_favorite', { label: 'Save to favorites' }),
|
|
98
|
+
a.action('remove_favorite', { label: 'Remove from favorites' }),
|
|
99
|
+
a.link('add_note', { label: 'Add a note', icon: 'file-text', to: { kind: 'create', resource: 'notes', values: { listing_id: '{id}' } } }),
|
|
100
|
+
])
|
|
101
|
+
.forRoles(['member'])
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Admins edit the listings: their page is everyone's with the sections only an editor needs, the position on the map,
|
|
105
|
+
* the status, cover photo and publishing, and the photos as records to add, reorder and caption.
|
|
106
|
+
*/
|
|
107
|
+
export const adminListingsView = memberListingsView
|
|
108
|
+
.layout((r) => [
|
|
109
|
+
l.gallery('Photos', { image: r.photo, photos }),
|
|
110
|
+
l.section('Key facts', [r.purchase_price, r.rent_price, r.price_per_m2, r.property_type, r.living_area, r.plot_area, r.rooms, r.bedrooms, r.bathrooms, r.energy_label], { help: keyFactsHelp, presentation: 'facts' }),
|
|
111
|
+
l.section('About this home', [r.description]),
|
|
112
|
+
l.section('Features', [r.built_year, r.garden, r.balcony, r.parking]),
|
|
113
|
+
l.map('Location', { latitude: r.latitude, longitude: r.longitude }),
|
|
114
|
+
l.section('Address', [r.address, r.postal_code, r.place_id]),
|
|
115
|
+
l.section('Viewing', [r.agency_id, r.agent_name, r.agent_phone], { help: viewingHelp, helpWhen: 'always' }),
|
|
116
|
+
l.section('Map position', [r.latitude, r.longitude, r.position_exact]),
|
|
117
|
+
l.section('Publishing', [r.status, r.photo, r.published_at]),
|
|
118
|
+
l.related('Photo list', { resource: 'listing_photos', field: 'listing_id', sort: 'position', columns: ['position', 'caption', 'photo'] }),
|
|
119
|
+
l.related('Your notes', { resource: 'notes', field: 'listing_id', sort: 'updated_at desc', columns: ['body', 'updated_at'], empty: 'No notes yet: only you see the notes you add.' }),
|
|
120
|
+
])
|
|
121
|
+
.forRoles(['admin'])
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { mapSettings } from '@protobase/server'
|
|
2
|
+
import { describe, expect, it } from 'vitest'
|
|
3
|
+
import config from '../protobase.config'
|
|
4
|
+
|
|
5
|
+
const mapLayers = config.maps ? config.maps.layers ?? [] : []
|
|
6
|
+
|
|
7
|
+
describe('the aerial photo layers', () => {
|
|
8
|
+
it('pass the checks the server makes at startup, and /meta names them beside the style', () => {
|
|
9
|
+
const settings = mapSettings({ layers: mapLayers }, { PROTOBASE_MAP_STYLE_URL: 'http://localhost:8790/style.json' })
|
|
10
|
+
expect(settings?.layers?.map((layer) => [layer.id, layer.label])).toEqual([['aerial_nl', 'Aerial (NL)'], ['aerial_es', 'Aerial (ES)']])
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('credit each source as its CC BY 4.0 licence asks', () => {
|
|
14
|
+
expect(mapLayers.map((layer) => layer.attribution)).toEqual([expect.stringContaining('Beeldmateriaal Nederland</a>, CC BY 4.0'), expect.stringContaining('PNOA CC BY 4.0 scne.es')])
|
|
15
|
+
})
|
|
16
|
+
})
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { f, resource } from '@protobase/schema'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* members.notes: what a member writes down about a listing. Only its writer reads or changes it (`notes.*.own` on
|
|
5
|
+
* `user_id`), and a new note is theirs whatever the request says.
|
|
6
|
+
*/
|
|
7
|
+
export const notes = resource('notes')
|
|
8
|
+
.table('members.notes')
|
|
9
|
+
.fields({
|
|
10
|
+
id: f.bigint().readOnly().filterable().sortable().dbDefault(),
|
|
11
|
+
user_id: f.text().readOnly().filterable(),
|
|
12
|
+
listing_id: f.relation('listings').filterable().sortable(),
|
|
13
|
+
body: f.text().min(1),
|
|
14
|
+
created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
|
|
15
|
+
updated_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
|
|
16
|
+
})
|
|
17
|
+
.primaryKey((r) => r.id)
|
|
18
|
+
.owner((r) => r.user_id)
|
|
19
|
+
.search((r) => [r.body])
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { l, view } from '@protobase/schema'
|
|
2
|
+
import type { notes } from './data'
|
|
3
|
+
|
|
4
|
+
export const notesView = view<typeof notes>('notes')
|
|
5
|
+
.title((r) => r.body)
|
|
6
|
+
.names({ singular: 'Note', plural: 'Notes' })
|
|
7
|
+
.nav({ group: 'Yours', order: 3 })
|
|
8
|
+
.help('Only you see your notes.')
|
|
9
|
+
.fields((r) => ({
|
|
10
|
+
listing_id: r.listing_id.label('Listing'),
|
|
11
|
+
body: r.body.label('Note'),
|
|
12
|
+
updated_at: r.updated_at.label('Changed'),
|
|
13
|
+
}))
|
|
14
|
+
.list((r) => ({ columns: [r.listing_id, r.body, r.updated_at], sort: [[r.updated_at, 'desc']], search: [r.body] }))
|
|
15
|
+
.filters((r, w) => [w.facets(r.listing_id, { search: true })])
|
|
16
|
+
.layout((r) => [l.section('Note', [r.listing_id, r.body]), l.sidebar([r.listing_id, r.created_at, r.updated_at])])
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ImageVariant } from '@protobase/schema'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The sizes a listing photo is stored in besides the upload: a card's picture across a list card (two device pixels
|
|
5
|
+
* per pixel of a card up to 400 wide), and a square thumbnail for tables.
|
|
6
|
+
*/
|
|
7
|
+
export const photoVariants: Record<string, ImageVariant> = {
|
|
8
|
+
card: { width: 800, height: 600, fit: 'cover', format: 'webp', quality: 75 },
|
|
9
|
+
thumb: { width: 96, height: 96, fit: 'cover', format: 'webp', quality: 70 },
|
|
10
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { f, resource } from '@protobase/schema'
|
|
2
|
+
|
|
3
|
+
/** market.places: a town or city homes are listed in, with its centre for searching around it. Unique: (country, name). */
|
|
4
|
+
export const places = resource('places')
|
|
5
|
+
.table('market.places')
|
|
6
|
+
.fields({
|
|
7
|
+
id: f.integer().readOnly().filterable().sortable().dbDefault(),
|
|
8
|
+
name: f.text().filterable().sortable(),
|
|
9
|
+
region: f.text().filterable().sortable(),
|
|
10
|
+
country: f.enum(['NL', 'ES']).filterable().sortable(),
|
|
11
|
+
latitude: f.decimal({ precision: 8, scale: 6 }),
|
|
12
|
+
longitude: f.decimal({ precision: 9, scale: 6 }),
|
|
13
|
+
})
|
|
14
|
+
.primaryKey((r) => r.id)
|
|
15
|
+
.search((r) => [r.name, r.region])
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { l, view } from '@protobase/schema'
|
|
2
|
+
import type { places } from './data'
|
|
3
|
+
|
|
4
|
+
export const placesView = view<typeof places>('places')
|
|
5
|
+
.title((r) => r.name)
|
|
6
|
+
.names({ singular: 'Place', plural: 'Places' })
|
|
7
|
+
.recordMode('read')
|
|
8
|
+
.helpWhen('editing')
|
|
9
|
+
.nav({ group: 'Browse', order: 3 })
|
|
10
|
+
.fields((r) => ({
|
|
11
|
+
region: r.region.help('The province in the Netherlands, the autonomous community in Spain.'),
|
|
12
|
+
country: r.country.format('badge').valueLabels({ NL: 'Netherlands', ES: 'Spain' }),
|
|
13
|
+
latitude: r.latitude.help('The centre, in decimal degrees (WGS84), that a search around the place measures from.').decimals(6),
|
|
14
|
+
longitude: r.longitude.help('Decimal degrees, WGS84.').decimals(6),
|
|
15
|
+
}))
|
|
16
|
+
.list((r) => ({ columns: [r.name, r.region, r.country], sort: [[r.name, 'asc']], search: [r.name, r.region] }))
|
|
17
|
+
.filters((r, w) => [w.facets(r.country), w.facets(r.region, { search: true })])
|
|
18
|
+
.layout((r) => [
|
|
19
|
+
l.section('Place', [r.name, r.region, r.country]),
|
|
20
|
+
l.section('Centre', [r.latitude, r.longitude]),
|
|
21
|
+
l.related('Listings', { resource: 'listings', field: 'place_id', sort: 'published_at desc', columns: ['address', 'property_type', 'purchase_price', 'rent_price', 'status'] }),
|
|
22
|
+
l.related('Agencies', { resource: 'agencies', field: 'place_id', columns: ['name', 'phone', 'website'] }),
|
|
23
|
+
])
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { printFilter, resolveAccess } from '@protobase/schema'
|
|
2
|
+
import { describe, expect, it } from 'vitest'
|
|
3
|
+
import { alerts, favorites, listingPhotos, listings, notes, savedSearches } from './index'
|
|
4
|
+
import { publicListingFields, roles } from './roles'
|
|
5
|
+
|
|
6
|
+
// Two members, an admin and a visitor, as the server's sessions carry them.
|
|
7
|
+
const anna = { user: { id: 'user-anna', roles: ['member'] } }
|
|
8
|
+
const bram = { user: { id: 'user-bram', roles: ['member'] } }
|
|
9
|
+
const admin = { user: { id: 'user-admin', roles: ['admin'] } }
|
|
10
|
+
const visitor = { user: { id: '', roles: ['anonymous'] } }
|
|
11
|
+
|
|
12
|
+
const access = (source: Parameters<typeof resolveAccess>[0], ctx: Parameters<typeof resolveAccess>[1]) => resolveAccess(source, ctx, { roles })
|
|
13
|
+
const rows = (filter: unknown) => (filter && typeof filter === 'object' ? printFilter(filter as never) : filter)
|
|
14
|
+
|
|
15
|
+
const ownData = [['saved_searches', savedSearches], ['alerts', alerts], ['favorites', favorites], ['notes', notes]] as const
|
|
16
|
+
|
|
17
|
+
describe('a member\'s own data', () => {
|
|
18
|
+
it.each(ownData)('limits every operation on %s to the rows of the member asking', async (_, source) => {
|
|
19
|
+
for (const [who, id] of [[anna, 'user-anna'], [bram, 'user-bram']] as const) {
|
|
20
|
+
const resolved = await access(source, who)
|
|
21
|
+
for (const operation of ['read', 'update', 'delete'] as const) {
|
|
22
|
+
if (!resolved.operations[operation]) continue
|
|
23
|
+
expect(rows(resolved.rowFilter[operation]), `${source.toModel().name} ${operation}`).toBe(`user_id = "${id}"`)
|
|
24
|
+
}
|
|
25
|
+
expect(resolved.operations.read).toBe(true)
|
|
26
|
+
}
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it.each(ownData)('keeps %s from admins as from everyone else', async (_, source) => {
|
|
30
|
+
expect(rows((await access(source, admin)).rowFilter.read)).toBe('user_id = "user-admin"')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it.each(ownData)('shows nothing of %s to a visitor', async (_, source) => {
|
|
34
|
+
const resolved = await access(source, visitor)
|
|
35
|
+
expect(resolved.operations).toEqual({ list: false, read: false, create: false, update: false, delete: false })
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('lets a member write notes, searches and favorites as their own, and only read or remove their alerts', async () => {
|
|
39
|
+
for (const source of [notes, savedSearches, favorites]) {
|
|
40
|
+
const resolved = await access(source, anna)
|
|
41
|
+
expect(resolved.operations.create).toBe(true)
|
|
42
|
+
expect(rows(resolved.rowFilter.create)).toBe('user_id = "user-anna"')
|
|
43
|
+
}
|
|
44
|
+
expect((await access(alerts, anna)).operations).toMatchObject({ create: false, update: false, delete: true })
|
|
45
|
+
expect((await access(favorites, anna)).operations.update).toBe(false)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('lets a member change how a search mails them and when they last looked, not whose it is', async () => {
|
|
49
|
+
const resolved = await access(savedSearches, anna)
|
|
50
|
+
expect(resolved.writableFields.update).toEqual(expect.arrayContaining(['name', 'filter', 'alert_frequency', 'seen_at']))
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('never lets anyone write the owner', async () => {
|
|
54
|
+
for (const [, source] of ownData) {
|
|
55
|
+
for (const who of [anna, admin]) {
|
|
56
|
+
const resolved = await access(source, who)
|
|
57
|
+
expect(resolved.writableFields.create ?? []).not.toContain('user_id')
|
|
58
|
+
expect(resolved.writableFields.update ?? []).not.toContain('user_id')
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
describe('listings', () => {
|
|
65
|
+
it('shows a visitor the published listings, without the agent to call', async () => {
|
|
66
|
+
const resolved = await access(listings, visitor)
|
|
67
|
+
expect(resolved.operations).toEqual({ list: true, read: true, create: false, update: false, delete: false })
|
|
68
|
+
expect(rows(resolved.rowFilter.read)).toBe('published_at:*')
|
|
69
|
+
expect([...resolved.readableFields].sort()).toEqual([...publicListingFields].sort())
|
|
70
|
+
expect(resolved.readableFields).not.toContain('agent_phone')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('shows members the agent too, still of published listings only, and admins the drafts', async () => {
|
|
74
|
+
const member = await access(listings, anna)
|
|
75
|
+
expect(member.readableFields).toContain('agent_phone')
|
|
76
|
+
expect(rows(member.rowFilter.read)).toBe('published_at:*')
|
|
77
|
+
expect(member.operations.update).toBe(false)
|
|
78
|
+
const catalogue = await access(listings, admin)
|
|
79
|
+
expect(catalogue.rowFilter.read).toBeUndefined()
|
|
80
|
+
expect(catalogue.operations).toMatchObject({ create: true, update: true, delete: true })
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('shows a visitor the photos with their placeholders', async () => {
|
|
84
|
+
const photos = await access(listingPhotos, visitor)
|
|
85
|
+
expect(photos.operations.read).toBe(true)
|
|
86
|
+
expect(photos.readableFields).toEqual(expect.arrayContaining(['photo', 'photo_placeholder']))
|
|
87
|
+
expect((await access(listings, visitor)).readableFields).toEqual(expect.arrayContaining(['photo', 'photo_placeholder']))
|
|
88
|
+
})
|
|
89
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { defineRoles } from '@protobase/schema'
|
|
2
|
+
|
|
3
|
+
/** The resources of the portal. */
|
|
4
|
+
export type PortalName = 'places' | 'agencies' | 'listings' | 'listing_photos' | 'saved_searches' | 'alerts' | 'favorites' | 'notes'
|
|
5
|
+
|
|
6
|
+
/** What a listing shows to someone who is not signed in: everything but the agent to call, and only once published. */
|
|
7
|
+
export const publicListingFields = [
|
|
8
|
+
'agency_id', 'place_id', 'property_type', 'status', 'address', 'postal_code', 'latitude', 'longitude',
|
|
9
|
+
'purchase_price', 'rent_price', 'for_sale', 'for_rent', 'living_area', 'price_per_m2', 'plot_area', 'rooms', 'bedrooms', 'bathrooms', 'built_year', 'energy_label',
|
|
10
|
+
'garden', 'balcony', 'parking', 'description', 'photo', 'photo_placeholder', 'published_at',
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
const published = 'published_at:*'
|
|
14
|
+
|
|
15
|
+
// A member's own saved searches, alerts, favorites and notes: `.own` limits each to the rows whose `user_id` is theirs,
|
|
16
|
+
// and a create is owned by whoever makes it. Alerts are made by the matching job; a member reads or removes them.
|
|
17
|
+
const ownData = [
|
|
18
|
+
'saved_searches.*.own', 'favorites.read.own', 'favorites.create.own', 'favorites.delete.own', 'notes.*.own',
|
|
19
|
+
'alerts.read.own', 'alerts.delete.own',
|
|
20
|
+
] as const
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Capabilities are `<resource>.<action>[.own]`. Visitors read the published listings, their photos, agencies and places
|
|
24
|
+
* through the fields listed here; members also see who to call, and keep their own searches, alerts, favorites and
|
|
25
|
+
* notes, which nobody else sees, admins included. Admins run the catalogue: places, agencies and listings, drafts too.
|
|
26
|
+
* Passed to the server, they decide every operation: no resource has rules of its own.
|
|
27
|
+
*/
|
|
28
|
+
export const roles = defineRoles<PortalName>({
|
|
29
|
+
admin: ['places.*', 'agencies.*', 'listings.*', 'listing_photos.*', ...ownData],
|
|
30
|
+
member: [
|
|
31
|
+
'places.read', 'agencies.read', { 'listings.read': { filter: published } }, 'listing_photos.read',
|
|
32
|
+
...ownData,
|
|
33
|
+
],
|
|
34
|
+
anonymous: [
|
|
35
|
+
{ 'places.read': ['name', 'region', 'country', 'latitude', 'longitude'] },
|
|
36
|
+
{ 'agencies.read': ['name', 'place_id', 'phone', 'email', 'website'] },
|
|
37
|
+
{ 'listings.read': { fields: publicListingFields, filter: published } },
|
|
38
|
+
{ 'listing_photos.read': ['id', 'listing_id', 'position', 'photo', 'photo_placeholder', 'caption'] },
|
|
39
|
+
],
|
|
40
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { f, resource } from '@protobase/schema'
|
|
2
|
+
import { searchIssues } from './rules'
|
|
3
|
+
|
|
4
|
+
export const alertFrequencies = ['instant', 'daily', 'none'] as const
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* members.saved_searches: a filter of the listings page a member saved, with the name they gave it, if any, and whether they hear of new listings that fit
|
|
8
|
+
* it at once, in the morning digest or not at all. Theirs alone (`.own` on `user_id`). `seen_at` is when they last
|
|
9
|
+
* opened its results: the listings published since are new to them. Unique: (user_id, filter).
|
|
10
|
+
*/
|
|
11
|
+
export const savedSearches = resource('saved_searches')
|
|
12
|
+
.table('members.saved_searches')
|
|
13
|
+
.fields({
|
|
14
|
+
id: f.bigint().readOnly().filterable().sortable().dbDefault(),
|
|
15
|
+
user_id: f.text().readOnly().filterable(),
|
|
16
|
+
name: f.text().min(1).optional().sortable(),
|
|
17
|
+
filter: f.text(),
|
|
18
|
+
alert_frequency: f.enum(alertFrequencies).default('daily').filterable().sortable(),
|
|
19
|
+
seen_at: f.timestamp().filterable().sortable().dbDefault(),
|
|
20
|
+
created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
|
|
21
|
+
})
|
|
22
|
+
.primaryKey((r) => r.id)
|
|
23
|
+
.owner((r) => r.user_id)
|
|
24
|
+
.search((r) => [r.name])
|
|
25
|
+
.validate(searchIssues)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { checkFilter, parseFilter, type CheckedFilter } from '@protobase/schema'
|
|
2
|
+
import { listings } from '../listings/data'
|
|
3
|
+
|
|
4
|
+
/** The listings' model, which a saved search's filter is read against and matched by. */
|
|
5
|
+
export const listingsModel = listings.toModel()
|
|
6
|
+
|
|
7
|
+
/** A saved search's filter, read and checked against the listings: `filter` empty when it takes every listing. */
|
|
8
|
+
export type SearchFilter = { ok: true; filter: CheckedFilter | undefined } | { ok: false; problems: string[] }
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Reads a saved search's filter as the listings page's address holds it, such as
|
|
12
|
+
* `for_sale = true AND place_id = 1 AND purchase_price <= 500000`, the way the API's list reads it.
|
|
13
|
+
*/
|
|
14
|
+
export const readSearchFilter = (text: string): SearchFilter => {
|
|
15
|
+
const parsed = parseFilter(text)
|
|
16
|
+
if (!parsed.ok) return { ok: false, problems: parsed.errors.map((error) => error.message) }
|
|
17
|
+
if (!parsed.ast) return { ok: true, filter: undefined }
|
|
18
|
+
const checked = checkFilter(listingsModel, parsed.ast)
|
|
19
|
+
return checked.ok ? { ok: true, filter: checked.filter } : { ok: false, problems: checked.errors.map((error) => error.message) }
|
|
20
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { searchIssues } from './rules'
|
|
3
|
+
|
|
4
|
+
describe('searchIssues', () => {
|
|
5
|
+
it('takes a filter of the listings, or none', () => {
|
|
6
|
+
expect(searchIssues({ filter: 'for_sale = true AND in(place_id, 1, 2) AND purchase_price <= 500000 AND search("gracht")' })).toBeUndefined()
|
|
7
|
+
expect(searchIssues({ filter: '' })).toBeUndefined()
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
it('refuses one that does not read, or names what the listings do not have', () => {
|
|
11
|
+
expect(searchIssues({ filter: 'purchase_price <=' })).toEqual([{ field: 'filter', message: expect.stringContaining('Not a filter of the listings') }])
|
|
12
|
+
expect(searchIssues({ filter: 'swimming_pool = true' })).toEqual([{ field: 'filter', message: expect.stringContaining('swimming_pool') }])
|
|
13
|
+
})
|
|
14
|
+
})
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { readSearchFilter } from './filter'
|
|
2
|
+
|
|
3
|
+
/** The fields of a saved search its rules read, as a write gives them: the record as it would be stored. */
|
|
4
|
+
export type SearchRecord = { filter?: string | null }
|
|
5
|
+
|
|
6
|
+
/** What is wrong with a saved search, by field: its filter is one the listings can be filtered by. */
|
|
7
|
+
export const searchIssues = (record: SearchRecord) => {
|
|
8
|
+
const read = readSearchFilter(record.filter ?? '')
|
|
9
|
+
return read.ok ? undefined : [{ field: 'filter' as const, message: `Not a filter of the listings: ${read.problems.join('; ')}` }]
|
|
10
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { l, view } from '@protobase/schema'
|
|
2
|
+
import type { savedSearches } from './data'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A member's saved searches: the list page shows each with its filters, its email setting and the listings published
|
|
6
|
+
* since they last opened its results, in a row of the listings' cards. A visitor is told what signing in gives there and
|
|
7
|
+
* by "Save search" on the listings.
|
|
8
|
+
*/
|
|
9
|
+
export const savedSearchesView = view<typeof savedSearches>('saved_searches')
|
|
10
|
+
.title((r) => r.name)
|
|
11
|
+
.names({ singular: 'Search', plural: 'Searches' })
|
|
12
|
+
.nav({ group: 'Yours', order: 2 })
|
|
13
|
+
.help('The searches you saved from the listings, with the homes published since you last looked. Save one with "Save search" on the filtered listings.')
|
|
14
|
+
.fields((r) => ({
|
|
15
|
+
filter: r.filter.help('The listings page\'s filter, as its address has it.'),
|
|
16
|
+
alert_frequency: r.alert_frequency.label('Email').format('badge').valueLabels({ instant: 'At once', daily: 'Daily digest', none: 'No email' }),
|
|
17
|
+
seen_at: r.seen_at.label('Last looked').help('Listings published after this are new to you. Opening all results moves it to now.'),
|
|
18
|
+
created_at: r.created_at.label('Saved'),
|
|
19
|
+
}))
|
|
20
|
+
.list((r) => ({ columns: [r.name, r.alert_frequency, r.seen_at, r.created_at], sort: [[r.created_at, 'desc']], search: [r.name] }))
|
|
21
|
+
.searchesOf((r) => ({ resource: 'listings', filter: r.filter, name: r.name, controls: [r.alert_frequency], unseen: { seenAt: r.seen_at, field: 'published_at' } }))
|
|
22
|
+
.signIn({
|
|
23
|
+
title: 'Hear of new homes first',
|
|
24
|
+
description: 'Sign in to save a search of the listings and get the new homes that fit it by email.',
|
|
25
|
+
benefits: ['Save the filters you set with "Save search"', 'See the homes published since you last looked', 'Get them by email at once, or in a morning digest'],
|
|
26
|
+
icon: 'bookmark',
|
|
27
|
+
})
|
|
28
|
+
.layout((r) => [
|
|
29
|
+
l.section('Search', [r.name, r.filter, r.alert_frequency]),
|
|
30
|
+
l.sidebar([r.alert_frequency, r.seen_at, r.created_at]),
|
|
31
|
+
l.related('Alerts', { resource: 'alerts', field: 'saved_search_id', sort: 'matched_at desc', columns: ['listing_id', 'matched_at', 'emailed_at'], empty: 'No listing has fit yet.' }),
|
|
32
|
+
])
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import postgres from 'postgres'
|
|
2
|
+
|
|
3
|
+
export const databaseUrl = process.env.DATABASE_URL ?? 'postgres://protobase:protobase@localhost:55432/property_portal'
|
|
4
|
+
|
|
5
|
+
export const connect = (options: postgres.Options<{}> = {}) => postgres(databaseUrl, { onnotice: () => {}, ...options })
|
|
6
|
+
|
|
7
|
+
export type Db = ReturnType<typeof connect>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { connect } from './connection'
|
|
2
|
+
|
|
3
|
+
const sql = connect({ max: 1 })
|
|
4
|
+
|
|
5
|
+
await sql.unsafe('drop schema if exists market, members, auth, jobs cascade')
|
|
6
|
+
await sql.unsafe('drop schema if exists migrations cascade')
|
|
7
|
+
await sql.unsafe('drop table if exists public.seed_info')
|
|
8
|
+
// The record an earlier Protobase kept, by its columns: a `schema_migrations` another migration tool owns stays.
|
|
9
|
+
const [earlier] = await sql`
|
|
10
|
+
select count(*) = 2 as ours from information_schema.columns
|
|
11
|
+
where table_schema = 'public' and table_name = 'schema_migrations' and column_name in ('name', 'applied_at')`
|
|
12
|
+
if (earlier!.ours) await sql.unsafe('drop table public.schema_migrations')
|
|
13
|
+
console.log('dropped all property portal schemas')
|
|
14
|
+
|
|
15
|
+
await sql.end()
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Kysely, PostgresDialect } from 'kysely'
|
|
2
|
+
import pg from 'pg'
|
|
3
|
+
import { databaseUrl } from './connection'
|
|
4
|
+
|
|
5
|
+
// date and timestamp (without zone) stay text; the API formats them itself
|
|
6
|
+
const types = {
|
|
7
|
+
getTypeParser: (oid: number, format?: 'text' | 'binary') =>
|
|
8
|
+
oid === 1082 || oid === 1114 ? (value: string) => value : pg.types.getTypeParser(oid, format as 'text'),
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Kysely over node-postgres, the way a deployment of the API would connect. */
|
|
12
|
+
export const createDb = (max = 10) =>
|
|
13
|
+
new Kysely<any>({ dialect: new PostgresDialect({ pool: new pg.Pool({ connectionString: databaseUrl, max, types }) }) })
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { connect } from './connection'
|
|
4
|
+
|
|
5
|
+
// Applies the migrations not applied yet, the app's and the auth schema's alike, in file name order and in one
|
|
6
|
+
// transaction: when one fails, none is applied and the database stays as the running version expects it. Run it before
|
|
7
|
+
// a new version serves, while nothing else writes. A statement Postgres runs only outside a transaction, such as
|
|
8
|
+
// `create index concurrently`, does not belong in these files.
|
|
9
|
+
|
|
10
|
+
const directory = fileURLToPath(new URL('./migrations/', import.meta.url))
|
|
11
|
+
// Any constant shared by every run of this script: two runs at once take turns.
|
|
12
|
+
const lockKey = 7_311_946_202
|
|
13
|
+
|
|
14
|
+
const sql = connect({ max: 1 })
|
|
15
|
+
const files = (await readdir(directory)).filter((file) => file.endsWith('.sql')).sort()
|
|
16
|
+
|
|
17
|
+
const applied = await sql.begin(async (tx) => {
|
|
18
|
+
await tx`select pg_advisory_xact_lock(${lockKey})`
|
|
19
|
+
await tx`create schema if not exists migrations`
|
|
20
|
+
await tx`create table if not exists migrations.applied (name text primary key, applied_at timestamptz not null default now())`
|
|
21
|
+
const done = new Set((await tx`select name from migrations.applied`).map((row) => row.name))
|
|
22
|
+
const pending = files.filter((file) => !done.has(file))
|
|
23
|
+
for (const file of pending) {
|
|
24
|
+
await tx.unsafe(await readFile(directory + file, 'utf8'))
|
|
25
|
+
await tx`insert into migrations.applied (name) values (${file})`
|
|
26
|
+
}
|
|
27
|
+
return pending
|
|
28
|
+
})
|
|
29
|
+
for (const file of applied) console.log(`applied ${file}`)
|
|
30
|
+
|
|
31
|
+
await sql.end()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
create extension if not exists pg_trgm;
|
|
2
|
+
|
|
3
|
+
-- What everyone browses: the places homes are in, the agencies that list them, the listings and their photos.
|
|
4
|
+
create schema market;
|
|
5
|
+
|
|
6
|
+
create table market.places (
|
|
7
|
+
id integer generated by default as identity primary key,
|
|
8
|
+
name text not null,
|
|
9
|
+
-- The province (NL) or autonomous community (ES).
|
|
10
|
+
region text not null,
|
|
11
|
+
country text not null check (country in ('NL', 'ES')),
|
|
12
|
+
latitude numeric(8, 6) not null check (latitude between -90 and 90),
|
|
13
|
+
longitude numeric(9, 6) not null check (longitude between -180 and 180),
|
|
14
|
+
unique (country, name)
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
create index places_region_idx on market.places (country, region);
|
|
18
|
+
create index places_name_trgm_idx on market.places using gin (name gin_trgm_ops);
|
|
19
|
+
|
|
20
|
+
create table market.agencies (
|
|
21
|
+
id integer generated by default as identity primary key,
|
|
22
|
+
name text not null,
|
|
23
|
+
place_id integer not null references market.places (id),
|
|
24
|
+
phone text not null,
|
|
25
|
+
email text not null,
|
|
26
|
+
website text not null,
|
|
27
|
+
created_at timestamptz not null default now(),
|
|
28
|
+
updated_at timestamptz not null default now()
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
create index agencies_place_idx on market.agencies (place_id);
|
|
32
|
+
create index agencies_name_trgm_idx on market.agencies using gin (name gin_trgm_ops);
|
|
33
|
+
|
|
34
|
+
create type market.offer_type as enum ('sale', 'rent');
|
|
35
|
+
create type market.property_type as enum ('apartment', 'house', 'townhouse', 'villa', 'studio', 'penthouse');
|
|
36
|
+
create type market.listing_status as enum ('available', 'under_offer', 'sold', 'let');
|
|
37
|
+
-- Best first, so `energy_label <= 'b'` means B or better. The Dutch scale runs from A++++; the Spanish one from A.
|
|
38
|
+
create type market.energy_label as enum ('a_plus_4', 'a_plus_3', 'a_plus_2', 'a_plus', 'a', 'b', 'c', 'd', 'e', 'f', 'g');
|
|
39
|
+
|
|
40
|
+
create table market.listings (
|
|
41
|
+
id bigint generated by default as identity primary key,
|
|
42
|
+
agency_id integer not null references market.agencies (id),
|
|
43
|
+
place_id integer not null references market.places (id),
|
|
44
|
+
offer_type market.offer_type not null,
|
|
45
|
+
property_type market.property_type not null,
|
|
46
|
+
status market.listing_status not null default 'available',
|
|
47
|
+
-- The street and number as the country writes them: "Keizersgracht 123-2", "Calle de Serrano, 45".
|
|
48
|
+
address text not null,
|
|
49
|
+
postal_code text not null,
|
|
50
|
+
latitude numeric(8, 6) not null check (latitude between -90 and 90),
|
|
51
|
+
longitude numeric(9, 6) not null check (longitude between -180 and 180),
|
|
52
|
+
-- The asking price, or the rent per month, in euros.
|
|
53
|
+
price numeric(12, 2) not null check (price > 0),
|
|
54
|
+
living_area integer not null check (living_area > 0),
|
|
55
|
+
price_per_m2 numeric(10, 2) generated always as (round(price / living_area, 2)) stored,
|
|
56
|
+
plot_area integer check (plot_area > 0),
|
|
57
|
+
rooms integer not null check (rooms > 0),
|
|
58
|
+
bedrooms integer not null check (bedrooms >= 0 and bedrooms < rooms),
|
|
59
|
+
bathrooms integer not null default 1 check (bathrooms >= 0),
|
|
60
|
+
built_year integer check (built_year between 1500 and 2100),
|
|
61
|
+
-- Null while the certificate is pending ("en trámite").
|
|
62
|
+
energy_label market.energy_label,
|
|
63
|
+
garden boolean not null default false,
|
|
64
|
+
balcony boolean not null default false,
|
|
65
|
+
parking boolean not null default false,
|
|
66
|
+
description text not null,
|
|
67
|
+
-- The cover photo, a file URI such as public:listings/house-03.png.
|
|
68
|
+
photo text,
|
|
69
|
+
-- Who to call about a viewing, shown to signed-in members.
|
|
70
|
+
agent_name text not null,
|
|
71
|
+
agent_phone text not null,
|
|
72
|
+
-- When the listing went public; null while it is a draft.
|
|
73
|
+
published_at timestamptz,
|
|
74
|
+
created_at timestamptz not null default now(),
|
|
75
|
+
updated_at timestamptz not null default now(),
|
|
76
|
+
check ((status <> 'sold' or offer_type = 'sale') and (status <> 'let' or offer_type = 'rent'))
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
create index listings_published_idx on market.listings (published_at desc);
|
|
80
|
+
create index listings_place_idx on market.listings (place_id, offer_type, price);
|
|
81
|
+
create index listings_agency_idx on market.listings (agency_id, published_at desc);
|
|
82
|
+
create index listings_offer_idx on market.listings (offer_type, status, price);
|
|
83
|
+
create index listings_type_idx on market.listings (property_type, offer_type);
|
|
84
|
+
create index listings_area_idx on market.listings (living_area);
|
|
85
|
+
create index listings_rooms_idx on market.listings (rooms, bedrooms);
|
|
86
|
+
create index listings_energy_idx on market.listings (energy_label);
|
|
87
|
+
create index listings_address_trgm_idx on market.listings using gin (address gin_trgm_ops);
|
|
88
|
+
|
|
89
|
+
create table market.listing_photos (
|
|
90
|
+
id bigint generated by default as identity primary key,
|
|
91
|
+
listing_id bigint not null references market.listings (id) on delete cascade,
|
|
92
|
+
position integer not null check (position > 0),
|
|
93
|
+
photo text not null,
|
|
94
|
+
caption text,
|
|
95
|
+
unique (listing_id, position)
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
create table public.seed_info (
|
|
99
|
+
scale text not null,
|
|
100
|
+
seeded_at timestamptz not null default now()
|
|
101
|
+
);
|