-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
274 lines (245 loc) · 7.55 KB
/
mod.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
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
import { type Signal } from "@preact/signals";
import { IS_BROWSER } from "fresh/runtime.ts";
import { qrcode } from "jsr:@libs/qrcode";
import { download, generateCsv, mkConfig } from "npm:[email protected]";
import { flatten } from "npm:[email protected]";
import { format } from "npm:[email protected]";
import { StateUpdater } from "preact/hooks";
import { OpeningHours, Organizers, Vehicles, Verifications } from "./mod.ts";
export const toQRCode = (content: string) => {
const svg = qrcode(content, { output: "svg" });
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
};
export const toTimeAgo = (value: string | number | Date) => {
return format(value, "es_ES");
};
export const toDate = (dateTime: string) => {
const date = new Date(dateTime);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
return `${year}-${month}-${day}`;
};
export const toDateTime = (dateTime: string) =>
new Date(dateTime).toLocaleString("en-GB", {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
export const toMXN = (amount: number) =>
new Intl.NumberFormat("es-MX", {
style: "currency",
currency: "MXN",
maximumFractionDigits: 2,
currencyDisplay: "symbol",
}).format(amount);
export const toUSD = (amount: number) =>
new Intl.NumberFormat("es-MX", {
style: "currency",
currency: "USD",
}).format(amount);
// export const currencyLocalProps = (amount: number) => ({
// value: (amount),
// onBlur: (e: Event) => e.currentTarget.value = toMXN(Number(e.currentTarget.value)),
// onFocus: (e: Event) => e.currentTarget.value = Number(e.currentTarget.value),
// onChangeCapture: (e: Event) => Number(e.currentTarget.value),
// });
export const toPercent = (value: number) =>
new Intl.NumberFormat("es-MX", {
style: "percent",
minimumFractionDigits: 2,
}).format(value);
export const getDateAtYearsFromToday = (years = 0) => {
const date = new Date();
date.setFullYear(date.getFullYear() + years);
return date;
};
export const getDateAtMonthsFromToday = (months = 0) => {
const date = new Date();
date.setMonth(date.getMonth() + months);
return date;
};
export const getDateAtDaysFromToday = (days = 0) => {
const date = new Date();
date.setDate(date.getDate() + days);
return date;
};
// adapted from https://stackoverflow.com/a/66494926
export const toHslColor = (
value: string,
saturation = 75,
lightness = 50,
opacity = 1,
) => {
const stringUniqueHash = [...value].reduce((acc, char) => {
return char.charCodeAt(0) + ((acc << 5) - acc);
}, 0);
const hue = Math.abs(stringUniqueHash % 360);
return `hsl(${hue} ${saturation}% ${lightness}% / ${opacity})`;
};
export const generateHexColor = () => {
// Generate a random integer between 0 and 255 for red, green, and blue
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
// Convert the integer values to hexadecimal and pad with zeros if necessary
const hexR = r.toString(16).padStart(2, "0");
const hexG = g.toString(16).padStart(2, "0");
const hexB = b.toString(16).padStart(2, "0");
// Concatenate the hex values to form a full hex color code
return `#${hexR}${hexG}${hexB}`;
};
export const getVerifications = (data?: Partial<Verifications>) => ({
owner: true,
users: false,
payments: true,
vehicles: true,
...data,
});
export const getVehicles = (data?: Partial<Vehicles>) => ({
brand: "",
model: "",
year: 2014,
color: "",
plateNumber: "",
...data,
});
export const getOrganizers = (data?: Partial<Organizers>) => ({
name: "",
userId: "",
email: "",
phone: "",
...data,
});
export const getOpeningHours = (data?: Partial<OpeningHours>) => ({
monday: "",
tuesday: "",
wednesday: "",
thursday: "",
friday: "",
saturday: "",
sunday: "",
festiveDays: "",
...data,
});
// used for `row.original.openinigHours[getDay]` to select current day opening hours
export const getDay = (index?: number) =>
({
0: "sunday",
1: "monday",
2: "tuesday",
3: "wednesday",
4: "thursday",
5: "friday",
6: "saturday",
})?.[index ?? new Date().getDay()];
export const updateSearchParam = (key: string, value: string) => {
if (!IS_BROWSER) return;
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({}, "", url.toString());
};
export function useTableUtils<
TData = { id: string; name: string; [k: string]: unknown },
>({
endpoint,
data,
setData,
active,
}: {
endpoint: string;
data: TData[];
setData: StateUpdater<TData[]>;
active?: Signal<TData>;
}) {
const create = async (value: TData) => {
const response = await fetch(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(value),
});
if (response.ok) {
const result = await response.json();
setData([result, ...data]);
if (active) active.value = result;
return result;
}
};
const update = async (value: TData) => {
const response = await fetch(`${endpoint}/${value.id}`, {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify(value),
});
const result = await response.json();
if (active) active.value = result;
setData(
data.map((value) => value.id === result.id ? result : value),
);
return result;
};
const duplicate = async ({ id: _, ...value }: TData) => {
const response = await fetch(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(value),
});
if (response.ok) {
const result = await response.json();
setData([result, ...data]);
if (active) active.value = result;
return result;
}
};
const remove = async ({ id }: TData) => {
const response = await fetch(`${endpoint}/${id}`, { method: "DELETE" });
if (response.ok) {
const result = await response.json();
if (confirm("Estas seguro de eliminar este registro?")) {
setData(data.filter((value) => value.id !== id));
if (active) active.value = undefined;
return result;
}
}
};
const copyId = ({ id }: TData) =>
globalThis?.navigator.clipboard.writeText(id as string);
// see https://medium.com/@j.lilian/how-to-export-react-tanstack-table-to-csv-file-722a22ccd9c5
const downloadAsCsv = (data: TData[], filename: string) => {
const csvConfig = mkConfig({
fieldSeparator: ",",
filename, // export file name (without .csv)
decimalSeparator: ".",
useKeysAsHeaders: true,
});
const flatData = data.map((row) => flatten(row));
// deno-lint-ignore no-explicit-any
const csv = generateCsv(csvConfig)<any>(flatData);
download(csvConfig)(csv);
};
return {
active,
create,
update,
duplicate,
remove,
copyId,
downloadAsCsv,
};
}
export * from "./datastore/accounts.ts";
export * from "./datastore/amenities.ts";
export * from "./datastore/bookings.ts";
export * from "./datastore/facilities.ts";
export * from "./datastore/items.ts";
export * from "./datastore/menus.ts";
export * from "./datastore/notices.ts";
export * from "./datastore/orders.ts";
export * from "./datastore/publications.ts";
export * from "./datastore/sessions.ts";
export * from "./datastore/slots.ts";
export * from "./datastore/statements.ts";
export * from "./datastore/users.ts";
export * from "./datastore/vehicles.ts";