-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
872 lines (784 loc) · 26.8 KB
/
server.ts
File metadata and controls
872 lines (784 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
import "jsr:@std/dotenv/load";
import { type Context, Hono } from "npm:hono";
import { cors } from "npm:hono/cors";
import { dbPool } from "./config/postgres.ts";
import { getKvInstance, listenQueue, sendMessage } from "./config/deno-kv.ts";
import { openaiAssistant } from "./services/openai-assistant.ts";
const app = new Hono();
const kv = await getKvInstance();
app.use("*", cors({ origin: "*" }));
app.get("/api/properties", async (c: Context) => {
using client = await dbPool.connect();
const query = c.req.query() as unknown as {
page?: string;
page_size?: string;
property_type_id?: string;
listing_type_id?: string;
listing_city_id?: string; // Added listing_city_id
search_longitude?: string;
search_latitude?: string;
bounding_box?: string;
max_distance_km?: string;
building_size_min?: string;
building_size_max?: string;
floor_size_min?: string;
floor_size_max?: string;
lot_size_min?: string;
lot_size_max?: string;
ceiling_height_min?: string;
ceiling_height_max?: string;
no_of_bedrooms_min?: string;
no_of_bedrooms_max?: string;
no_of_bathrooms_min?: string;
no_of_bathrooms_max?: string;
no_of_parking_spaces_min?: string;
no_of_parking_spaces_max?: string;
price_min?: string;
price_max?: string;
sort_by?: string;
sort_order?: string;
search?: string;
};
if (!query.page) {
query.page = "1";
}
if (!query.page_size) {
query.page_size = "10";
}
if (!query.property_type_id) {
query.property_type_id = "1";
}
if (!query.listing_type_id) {
query.listing_type_id = "1";
}
if (!query.sort_by) {
query.sort_by = "created_at"; // Default sort field
}
if (!query.sort_order) {
query.sort_order = "DESC"; // Default sort order
}
const offset = (parseInt(query.page) - 1) * parseInt(query.page_size);
let boundingBoxCoords: number[] | null[] = [null, null, null, null];
if (query?.bounding_box) {
boundingBoxCoords = query.bounding_box.split("::").map((coord) =>
parseFloat(coord)
);
}
const searchLongitude = parseFloat(query?.search_longitude || "0");
const searchLatitude = parseFloat(query?.search_latitude || "0");
// Initialize the SQL WHERE clause with base conditions
let sqlWhereClause = `
pt.property_type_id = $1
AND lt.listing_type_id = $2
`;
// Initialize the SQL parameters array with base parameters
const sqlParams = [
parseInt(query.property_type_id),
parseInt(query.listing_type_id),
];
// Initialize the parameter counter for dynamic parameter numbering
let paramCounter = 3;
// Function to add a new condition to the WHERE clause
// deno-lint-ignore no-explicit-any
const addWhereCondition = (condition: string, ...params: any[]) => {
sqlWhereClause += ` AND ${condition}`;
sqlParams.push(...params);
paramCounter += params.length;
};
// Add listing_city_id condition if provided
if (query.listing_city_id) {
addWhereCondition(
`p.listing_city_id = $${paramCounter}`,
parseInt(query.listing_city_id)
);
}
// Add text search condition if search query is provided
if (query.search) {
addWhereCondition(
`to_tsvector('english', l.title || ' ' || l.description) @@ plainto_tsquery($${paramCounter})`,
query.search,
);
}
// Add bounding box condition if all coordinates are provided
if (boundingBoxCoords.every((coord) => coord !== null)) {
addWhereCondition(
`
p.latitude BETWEEN $${paramCounter} AND $${paramCounter + 1}
AND p.longitude BETWEEN $${paramCounter + 2} AND $${paramCounter + 3}
`,
...boundingBoxCoords as number[],
);
}
// Add max distance condition if required parameters are provided
if (query.max_distance_km && searchLongitude !== 0 && searchLatitude !== 0) {
addWhereCondition(
`
ST_DWithin(p.geog, ST_SetSRID(ST_MakePoint($${paramCounter}, $${
paramCounter + 1
}), 4326)::geography, ${parseFloat(query.max_distance_km)} * 1000)
`,
searchLongitude,
searchLatitude,
);
}
// Add price range condition if both min and max are provided
if (query.price_min && query.price_max) {
addWhereCondition(
`l.price BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseFloat(query.price_min),
parseFloat(query.price_max),
);
}
// Add building size range condition if both min and max are provided
if (query.building_size_min && query.building_size_max) {
addWhereCondition(
`p.building_size BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseFloat(query.building_size_min),
parseFloat(query.building_size_max),
);
}
// Add floor size range condition if both min and max are provided
if (query.floor_size_min && query.floor_size_max) {
addWhereCondition(
`p.floor_size BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseFloat(query.floor_size_min),
parseFloat(query.floor_size_max),
);
}
// Add lot size range condition if both min and max are provided
if (query.lot_size_min && query.lot_size_max) {
addWhereCondition(
`p.lot_size BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseFloat(query.lot_size_min),
parseFloat(query.lot_size_max),
);
}
// Add ceiling height range condition if both min and max are provided
if (query.ceiling_height_min && query.ceiling_height_max) {
addWhereCondition(
`p.ceiling_height BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseFloat(query.ceiling_height_min),
parseFloat(query.ceiling_height_max),
);
}
// Add number of bedrooms range condition if both min and max are provided
if (query.no_of_bedrooms_min && query.no_of_bedrooms_max) {
addWhereCondition(
`p.no_of_bedrooms BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseInt(query.no_of_bedrooms_min),
parseInt(query.no_of_bedrooms_max),
);
}
// Add number of bathrooms range condition if both min and max are provided
if (query.no_of_bathrooms_min && query.no_of_bathrooms_max) {
addWhereCondition(
`p.no_of_bathrooms BETWEEN $${paramCounter} AND $${paramCounter + 1}`,
parseInt(query.no_of_bathrooms_min),
parseInt(query.no_of_bathrooms_max),
);
}
// Add number of parking spaces range condition if both min and max are provided
if (query.no_of_parking_spaces_min && query.no_of_parking_spaces_max) {
addWhereCondition(
`p.no_of_parking_spaces BETWEEN $${paramCounter} AND $${
paramCounter + 1
}`,
parseInt(query.no_of_parking_spaces_min),
parseInt(query.no_of_parking_spaces_max),
);
}
// Validate and construct ORDER BY clause
let orderByClause = "";
const validSortFields = ["id", "created_at", "price"];
const validSortOrders = ["ASC", "DESC"];
if (
validSortFields.includes(query.sort_by) &&
validSortOrders.includes(query.sort_order.toUpperCase())
) {
orderByClause =
`ORDER BY l.${query.sort_by} ${query.sort_order.toUpperCase()}`;
} else {
orderByClause = "ORDER BY l.created_at DESC";
}
console.log({ sqlWhereClause, sqlParams, nextParamCounter: paramCounter });
const postgres = await client.queryObject({
args: [...sqlParams, parseInt(query.page_size), offset],
text: `
WITH User_Likes AS (
SELECT
uf.property_id
FROM
user_favorites uf
WHERE
uf.user_id = 1 -- Replace with user's actual ID or parameter
)
SELECT
l.id AS listing_id,
l.title,
l.url,
l.description,
l.is_scraped,
l.price,
l.price_formatted,
l.price_not_shown,
p.id AS property_id,
p.user_id,
p.floor_size,
p.lot_size,
p.building_size,
p.ceiling_height,
p.no_of_bedrooms,
p.no_of_bathrooms,
p.no_of_parking_spaces,
p.longitude,
p.latitude,
p.year_built,
p.primary_image_url,
p.images,
p.amenities,
p.property_features,
p.indoor_features,
p.outdoor_features,
p.ai_generated_description,
p.ai_generated_basic_features,
p.project_name AS property_project_name,
p.agent_name,
p.product_owner_name,
pt.type_name AS property_type_name,
lt.type_name AS listing_type_name,
wt.type_name AS warehouse_type_name,
l.address AS listing_address,
rg.region AS listing_region_name,
ct.city AS listing_city_name,
ar.area AS listing_area_name,
p.created_at AS property_created_at,
p.updated_at AS property_updated_at,
l.created_at AS listing_created_at,
l.updated_at AS listing_updated_at,
-- Price change log as an array ordered by latest changes
(
SELECT json_agg(
json_build_object(
'id', pcl.id,
'old_price', pcl.old_price,
'new_price', pcl.new_price,
'change_timestamp', pcl.change_timestamp
) ORDER BY pcl.change_timestamp DESC
)
FROM Price_Change_Log pcl
WHERE pcl.listing_id = l.id
) AS price_change_log,
CASE
WHEN ull.property_id IS NOT NULL THEN TRUE
ELSE FALSE
END AS is_liked
FROM
Listing l
JOIN Property p ON l.property_id = p.id
LEFT JOIN Property_Type pt ON p.property_type_id = pt.property_type_id
LEFT JOIN Listing_Type lt ON l.offer_type_id = lt.listing_type_id
LEFT JOIN Warehouse_Type wt ON p.warehouse_type_id = wt.warehouse_type_id
LEFT JOIN Listing_Region rg ON p.listing_region_id = rg.id
LEFT JOIN Listing_City ct ON p.listing_city_id = ct.id
LEFT JOIN Listing_Area ar ON p.listing_area_id = ar.id
LEFT JOIN User_Likes ull ON p.id = ull.property_id
WHERE
${sqlWhereClause}
${orderByClause} LIMIT $${paramCounter} OFFSET $${paramCounter + 1};
`,
});
const recordCount = await client.queryObject({
args: sqlParams,
text: `
SELECT COUNT(*)::integer
FROM
Listing l
JOIN Property p ON l.property_id = p.id
LEFT JOIN Property_Type pt ON p.property_type_id = pt.property_type_id
LEFT JOIN Listing_Type lt ON l.offer_type_id = lt.listing_type_id
LEFT JOIN Warehouse_Type wt ON p.warehouse_type_id = wt.warehouse_type_id
LEFT JOIN Listing_Region rg ON p.listing_region_id = rg.id
LEFT JOIN Listing_City ct ON p.listing_city_id = ct.id
LEFT JOIN Listing_Area ar ON p.listing_area_id = ar.id
WHERE
${sqlWhereClause}
`,
});
const counterResult = recordCount.rows[0] as { count: number };
const totalListingRecords = counterResult.count;
const pageNo = parseInt(query.page);
const pageSize = parseInt(query.page_size);
const totalPages = Math.ceil(totalListingRecords / pageSize);
const nextPage = pageNo < totalPages ? pageNo + 1 : null;
const previousPage = pageNo > 1 ? pageNo - 1 : null;
return c.json({
data: postgres.rows,
pagination: {
total: totalListingRecords,
page: pageNo,
page_size: pageSize,
total_pages: totalPages,
next_page: nextPage,
previous_page: previousPage,
},
});
});
app.get("/api/properties/valuation", async (c: Context) => {
const data = c.req.query();
if (!data.property_type_id || !data.size_in_sqm) {
return c.json({ error: "Property type and size are required" }, 400);
}
const propertyTypeId = parseInt(data.property_type_id);
if (propertyTypeId < 1 || propertyTypeId > 4) {
return c.json({
error: "Invalid property type ID. Must be between 1 and 4",
}, 400);
}
using client = await dbPool.connect();
const sizeInSqm = parseFloat(data.size_in_sqm);
if (isNaN(sizeInSqm) || sizeInSqm <= 0) {
return c.json({ error: "Invalid size value" }, 400);
}
const queryParams: (number)[] = [propertyTypeId, sizeInSqm];
let cityClause = "";
let propertyFeaturesClause = "";
let paramCounter = 3;
if (data.city_id) {
const cityId = parseInt(data.city_id);
if (isNaN(cityId) || cityId < 1) {
return c.json({ error: "Invalid city ID" }, 400);
}
queryParams.push(cityId);
cityClause = `AND p.listing_city_id = $${paramCounter}`;
paramCounter++;
}
// Only allow bedroom, bathroom, and parking filters for residential properties
if (propertyTypeId === 1 || propertyTypeId === 2) {
if (data.no_of_bedrooms) {
const bedrooms = parseInt(data.no_of_bedrooms);
if (isNaN(bedrooms) || bedrooms < 0) {
return c.json({ error: "Invalid number of bedrooms" }, 400);
}
queryParams.push(bedrooms);
propertyFeaturesClause += `AND p.no_of_bedrooms = $${paramCounter} `;
paramCounter++;
}
if (data.no_of_bathrooms) {
const bathrooms = parseInt(data.no_of_bathrooms);
if (isNaN(bathrooms) || bathrooms < 0) {
return c.json({ error: "Invalid number of bathrooms" }, 400);
}
queryParams.push(bathrooms);
propertyFeaturesClause += `AND p.no_of_bathrooms = $${paramCounter} `;
paramCounter++;
}
if (data.no_of_parking_spaces) {
const parkingSpaces = parseInt(data.no_of_parking_spaces);
if (isNaN(parkingSpaces) || parkingSpaces < 0) {
return c.json({ error: "Invalid number of parking spaces" }, 400);
}
queryParams.push(parkingSpaces);
propertyFeaturesClause +=
`AND p.no_of_parking_spaces = $${paramCounter} `;
paramCounter++;
}
}
interface PropertyStats {
offer_type_id: number;
average_price: number;
total_comparable_properties: number;
}
const properties = await client.queryObject<PropertyStats>({
args: queryParams,
text: `
WITH PropertyStats AS (
SELECT
l.price,
l.offer_type_id
FROM Property p
JOIN Listing l ON p.id = l.property_id
WHERE
p.property_type_id = $1
${cityClause}
${propertyFeaturesClause}
AND CASE
WHEN p.property_type_id IN (1, 3) THEN p.building_size BETWEEN $2 * 0.8 AND $2 * 1.2
ELSE p.lot_size BETWEEN $2 * 0.8 AND $2 * 1.2
END
AND l.price > 0
)
SELECT
l.offer_type_id,
ROUND(AVG(price)::numeric, 2) as average_price,
COUNT(*) as total_comparable_properties
FROM PropertyStats l
GROUP BY l.offer_type_id
`,
});
if (!properties.rows.length) {
return c.json({
error: "Not enough data to generate valuation for the specified criteria",
}, 404);
}
const valuationData = properties.rows.reduce(
(acc, row) => {
const type = row.offer_type_id === 1 ? "buy" : "rent";
const formattedPrice = new Intl.NumberFormat("en-PH", {
style: "currency",
currency: "PHP",
minimumFractionDigits: 2,
}).format(row.average_price);
acc[type] = {
average_price: row.average_price.toString(),
formatted_price: formattedPrice,
total_comparable_properties: row.total_comparable_properties.toString(),
};
return acc;
},
{} as Record<
string,
{
average_price: string;
formatted_price: string;
total_comparable_properties: string;
}
>,
);
return c.json({ data: valuationData });
});
app.get("/api/properties/cities", async (c: Context) => {
using client = await dbPool.connect();
const query = c.req.query();
const search = query.search || "";
if (!query.property_type_id) {
return c.json({ error: "Property type ID is required" }, 400);
}
const cities = await client.queryObject({
args: [`%${search}%`, query.property_type_id],
text: `
SELECT DISTINCT
ct.id::text,
ct.city,
ct.listing_city_id,
rg.id::text as region_id,
rg.region as region_name,
rg.listing_region_id,
pt.type_name as property_type_name,
COUNT(DISTINCT CASE
WHEN p.property_type_id = $2::int
THEN p.id
END)::text as property_count
FROM Listing_City ct
JOIN Listing_Region rg ON ct.listing_region_id = rg.id
LEFT JOIN Property p ON p.listing_city_id = ct.id
LEFT JOIN Property_Type pt ON pt.property_type_id = $2::int
WHERE LOWER(ct.city) LIKE LOWER($1)
GROUP BY ct.id, ct.city, ct.listing_city_id, rg.id, rg.region, rg.listing_region_id, pt.type_name
ORDER BY ct.city ASC
LIMIT 5
`,
});
return c.json({
data: cities.rows,
});
});
app.post("/api/properties/favorites/:propertyId", async (c: Context) => {
using client = await dbPool.connect();
const propertyId = c.req.param("propertyId");
const { userId } = await c.req.json();
if (!propertyId || !userId) {
return c.json({ error: "Property ID and User ID are required" }, 400);
}
// First check if favorite already exists
const existingFavorite = await client.queryObject({
args: [userId, propertyId],
text: `
SELECT id, user_id, property_id, added_at
FROM User_Favorites
WHERE user_id = $1 AND property_id = $2
`,
});
if (existingFavorite?.rowCount && existingFavorite.rowCount > 0) {
return c.json({
data: existingFavorite.rows[0],
});
}
// Create new favorite if it doesn't exist
const result = await client.queryObject({
args: [userId, propertyId],
text: `
INSERT INTO User_Favorites (user_id, property_id)
VALUES ($1, $2)
RETURNING id, user_id, property_id, added_at
`,
});
return c.json({
data: result.rows[0],
});
});
app.delete("/api/properties/favorites/:propertyId", async (c: Context) => {
using client = await dbPool.connect();
const propertyId = c.req.param("propertyId");
const { userId } = await c.req.json();
if (!propertyId || !userId) {
return c.json({ error: "Property ID and User ID are required" }, 400);
}
const result = await client.queryObject({
args: [userId, propertyId],
text: `
DELETE FROM User_Favorites
WHERE user_id = $1 AND property_id = $2
RETURNING id
`,
});
if (result.rowCount === 0) {
return c.json({ error: "Favorite not found" }, 404);
}
return c.json({
data: { success: true },
});
});
app.get("/api/properties/:userId/favorites", async (c: Context) => {
using client = await dbPool.connect();
const userId = c.req.param("userId");
if (!userId) {
return c.json({ error: "User ID is required" }, 400);
}
const favorites = await client.queryObject({
args: [userId],
text: `
SELECT
pt.type_name AS property_type,
json_agg(json_build_object(
'listing_id', l.id, -- Adding listing_id
'formatted_price', l.price_formatted,
'images', p.images,
'title', l.title,
'listing_address', json_build_object(
'address', l.address,
'region', r.region,
'city', c.city,
'area', a.area
),
'offer_type', lt.type_name
) ORDER BY l.title) AS favorites
FROM User_Favorites uf
JOIN Property p ON uf.property_id = p.id
JOIN Property_Type pt ON p.property_type_id = pt.property_type_id
JOIN Listing l ON p.id = l.id
JOIN Listing_Region r ON p.listing_region_id = r.id
JOIN Listing_City c ON p.listing_city_id = c.id
LEFT JOIN Listing_Area a ON p.listing_area_id = a.id
JOIN Listing_Type lt ON l.offer_type_id = lt.listing_type_id
WHERE uf.user_id = 1 -- Replace with the actual user ID
GROUP BY pt.type_name
ORDER BY pt.type_name;
`,
});
return c.json({
data: favorites.rows,
});
});
app.patch("/api/properties/:id/generate-ai-description", async (c: Context) => {
using client = await dbPool.connect();
const id = c.req.param("id");
if (!id) {
return c.json({ error: "Property ID is required" }, 400);
}
const property = await client.queryObject({
args: [id],
text: `
SELECT
l.id AS listing_id,
l.title,
l.url,
l.description,
l.is_scraped,
l.price,
l.price_formatted,
l.price_not_shown,
p.id AS property_id,
p.user_id,
p.floor_size,
p.lot_size,
p.building_size,
p.ceiling_height,
p.no_of_bedrooms,
p.no_of_bathrooms,
p.no_of_parking_spaces,
p.longitude,
p.latitude,
p.year_built,
p.primary_image_url,
p.images,
p.amenities,
p.property_features,
p.indoor_features,
p.outdoor_features,
p.ai_generated_description,
p.ai_generated_basic_features,
p.project_name AS property_project_name,
p.agent_name,
p.product_owner_name,
pt.type_name AS property_type_name,
lt.type_name AS listing_type_name,
wt.type_name AS warehouse_type_name,
l.address AS listing_address,
rg.region AS listing_region_name,
ct.city AS listing_city_name,
ar.area AS listing_area_name,
p.created_at AS property_created_at,
p.updated_at AS property_updated_at,
l.created_at AS listing_created_at,
l.updated_at AS listing_updated_at,
-- Price change log as an array ordered by latest changes
(
SELECT json_agg(
json_build_object(
'id', pcl.id,
'old_price', pcl.old_price,
'new_price', pcl.new_price,
'change_timestamp', pcl.change_timestamp
) ORDER BY pcl.change_timestamp DESC
)
FROM Price_Change_Log pcl
WHERE pcl.listing_id = l.id
) AS price_change_log
FROM
Listing l
JOIN Property p ON l.property_id = p.id
LEFT JOIN Property_Type pt ON p.property_type_id = pt.property_type_id
LEFT JOIN Listing_Type lt ON l.offer_type_id = lt.listing_type_id
LEFT JOIN Warehouse_Type wt ON p.warehouse_type_id = wt.warehouse_type_id
LEFT JOIN Listing_Region rg ON p.listing_region_id = rg.id
LEFT JOIN Listing_City ct ON p.listing_city_id = ct.id
LEFT JOIN Listing_Area ar ON p.listing_area_id = ar.id
WHERE
l.id = $1
`,
});
if (property.rowCount === 0) {
return c.json({ data: null });
}
const aiGeneratedDescription = await openaiAssistant(
JSON.stringify(property.rows[0]),
);
const propertyData = property.rows[0] as {
property_id: number;
};
try {
JSON.parse(
aiGeneratedDescription.includes("```json")
? aiGeneratedDescription
.replace("```json", "")
.replace("```", "")
: aiGeneratedDescription,
);
} catch {
throw Error("Invalid AI description format");
}
if (aiGeneratedDescription) {
await client.queryObject({
args: [
JSON.stringify(aiGeneratedDescription),
propertyData.property_id,
],
text: `UPDATE Property SET ai_generated_description = $1 WHERE id = $2`,
});
}
return c.json({
property_id: propertyData.property_id,
ai_generated_description: aiGeneratedDescription,
});
});
app.get("/api/properties/:id", async (c: Context) => {
using client = await dbPool.connect();
const id = c.req.param("id");
if (!id) {
return c.json({ error: "Property ID is required" }, 400);
}
const property = await client.queryObject({
args: [id],
text: `
SELECT
l.id AS listing_id,
l.title,
l.url,
l.description,
l.is_scraped,
l.price,
l.price_formatted,
l.price_not_shown,
p.id AS property_id,
p.user_id,
p.floor_size,
p.lot_size,
p.building_size,
p.ceiling_height,
p.no_of_bedrooms,
p.no_of_bathrooms,
p.no_of_parking_spaces,
p.longitude,
p.latitude,
p.year_built,
p.primary_image_url,
p.images,
p.amenities,
p.property_features,
p.indoor_features,
p.outdoor_features,
p.ai_generated_description,
p.ai_generated_basic_features,
p.project_name AS property_project_name,
p.agent_name,
p.product_owner_name,
pt.type_name AS property_type_name,
lt.type_name AS listing_type_name,
wt.type_name AS warehouse_type_name,
l.address AS listing_address,
rg.region AS listing_region_name,
ct.city AS listing_city_name,
ar.area AS listing_area_name,
p.created_at AS property_created_at,
p.updated_at AS property_updated_at,
l.created_at AS listing_created_at,
l.updated_at AS listing_updated_at,
-- Price change log as an array ordered by latest changes
(
SELECT json_agg(
json_build_object(
'id', pcl.id,
'old_price', pcl.old_price,
'new_price', pcl.new_price,
'change_timestamp', pcl.change_timestamp
) ORDER BY pcl.change_timestamp DESC
)
FROM Price_Change_Log pcl
WHERE pcl.listing_id = l.id
) AS price_change_log
FROM
Listing l
JOIN Property p ON l.property_id = p.id
LEFT JOIN Property_Type pt ON p.property_type_id = pt.property_type_id
LEFT JOIN Listing_Type lt ON l.offer_type_id = lt.listing_type_id
LEFT JOIN Warehouse_Type wt ON p.warehouse_type_id = wt.warehouse_type_id
LEFT JOIN Listing_Region rg ON p.listing_region_id = rg.id
LEFT JOIN Listing_City ct ON p.listing_city_id = ct.id
LEFT JOIN Listing_Area ar ON p.listing_area_id = ar.id
WHERE
l.id = $1
`,
});
if (property.rowCount === 0) {
return c.json({ data: null });
}
return c.json({ data: property.rows[0] });
});
app.post("/", async (c: Context) => {
const data = await c.req.json();
console.info("Received message:", data.type);
await sendMessage({ kv, data, options: { delay: 5000 } });
return c.text("Hono!");
});
listenQueue(kv).catch((error) => console.error(error));
Deno.serve({ port: parseInt(Deno.env.get("PORT") || "8000") }, app.fetch);