-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathNext30Days.projector.ts
59 lines (56 loc) · 1.73 KB
/
Next30Days.projector.ts
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
import { client, Projector } from "@rotorsoft/eventually";
import { z } from "zod";
import { Room } from "./Room.aggregate";
import * as models from "./Room.models";
import * as schemas from "./Room.schemas";
import { addDays } from "./utils";
export const DaySalesSchema = z.object({
id: z.string(),
total: z.number(),
reserved: z.array(z.number())
});
export type DaySales = z.infer<typeof DaySalesSchema>;
export const Next30Days = (): Projector<
DaySales,
Pick<models.RoomEvents, "RoomBooked">
> => ({
description: "Next 30 day reservations",
schemas: {
state: DaySalesSchema,
events: {
RoomBooked: schemas.BookRoom
}
},
on: {
RoomBooked: async ({ data }) => {
const days: string[] = [];
const today = new Date();
const last_day = addDays(today, 30);
let day = data.checkin;
while (day >= today && day <= last_day && day <= data.checkout) {
days.push(day.toISOString().substring(0, 10));
day = addDays(day, 1);
}
if (days.length) {
const room = await client().load(Room, data.number.toString());
const sales = Object.fromEntries(
(await client().read(Next30Days, days)).map((r) => [
r.state.id,
r.state
])
);
const upserts = days.map((day) => {
const record =
sales[day] || ({ id: day, total: 0, reserved: [] } as DaySales);
const total = record.total + room.state.price;
const reserved = record.reserved;
if (reserved.includes(room.state.number)) return { id: day, total };
reserved.push(room.state.number);
return { id: day, total, reserved };
});
return upserts;
}
return [];
}
}
});