@rivil-solutions/site-kit 0.0.0-stage → 0.1.0

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 (76) hide show
  1. package/README.md +97 -2
  2. package/bin/rivil.mjs +118 -0
  3. package/blocks/booking/block.json +7 -0
  4. package/blocks/booking/files/src/components/rivil/BookingForm.tsx +187 -0
  5. package/blocks/booking/files/src/pages/programare.astro +18 -0
  6. package/blocks/careers/block.json +7 -0
  7. package/blocks/careers/files/src/components/rivil/ApplyForm.tsx +62 -0
  8. package/blocks/careers/files/src/pages/cariere/[job].astro +49 -0
  9. package/blocks/careers/files/src/pages/cariere/index.astro +32 -0
  10. package/blocks/events/block.json +7 -0
  11. package/blocks/events/files/src/components/rivil/EventCheckout.tsx +93 -0
  12. package/blocks/events/files/src/pages/evenimente/[code].astro +35 -0
  13. package/blocks/events/files/src/pages/evenimente/comanda.astro +36 -0
  14. package/blocks/events/files/src/pages/evenimente/index.astro +30 -0
  15. package/blocks/newsletter/block.json +4 -0
  16. package/blocks/newsletter/files/src/components/rivil/Newsletter.astro +35 -0
  17. package/blocks/reviews/block.json +7 -0
  18. package/blocks/reviews/files/src/components/rivil/ReviewForm.tsx +73 -0
  19. package/blocks/reviews/files/src/pages/recenzii.astro +39 -0
  20. package/blocks/stay/block.json +7 -0
  21. package/blocks/stay/files/src/components/rivil/StayBooking.tsx +121 -0
  22. package/blocks/stay/files/src/pages/rezervare.astro +11 -0
  23. package/blocks/ui/block.json +1 -0
  24. package/blocks/ui/files/src/components/rivil/ui.tsx +99 -0
  25. package/blocks/ui/files/src/styles/rivil-blocks.css +47 -0
  26. package/dist/account.d.ts +84 -0
  27. package/dist/account.js +104 -0
  28. package/dist/astro-image.d.ts +29 -0
  29. package/dist/astro-image.js +12 -0
  30. package/dist/client.d.ts +58 -0
  31. package/dist/client.js +153 -0
  32. package/dist/consent.d.ts +6 -0
  33. package/dist/consent.js +10 -0
  34. package/dist/content.d.ts +93 -0
  35. package/dist/content.js +85 -0
  36. package/dist/i18n.d.ts +30 -0
  37. package/dist/i18n.js +69 -0
  38. package/dist/images.d.ts +13 -0
  39. package/dist/images.js +26 -0
  40. package/dist/index.d.ts +13 -0
  41. package/dist/index.js +13 -0
  42. package/dist/modules.d.ts +288 -0
  43. package/dist/modules.js +49 -0
  44. package/dist/proxy.d.ts +47 -0
  45. package/dist/proxy.js +82 -0
  46. package/dist/react/index.d.ts +6 -0
  47. package/dist/react/index.js +6 -0
  48. package/dist/react/texts.d.ts +17 -0
  49. package/dist/react/texts.js +28 -0
  50. package/dist/react/useApplication.d.ts +67 -0
  51. package/dist/react/useApplication.js +94 -0
  52. package/dist/react/useBooking.d.ts +81 -0
  53. package/dist/react/useBooking.js +151 -0
  54. package/dist/react/useEventCheckout.d.ts +48 -0
  55. package/dist/react/useEventCheckout.js +104 -0
  56. package/dist/react/useReview.d.ts +58 -0
  57. package/dist/react/useReview.js +69 -0
  58. package/dist/react/useStay.d.ts +82 -0
  59. package/dist/react/useStay.js +105 -0
  60. package/dist/seo.d.ts +27 -0
  61. package/dist/seo.js +36 -0
  62. package/dist/shop.d.ts +111 -0
  63. package/dist/shop.js +167 -0
  64. package/dist/visitor.d.ts +7 -0
  65. package/dist/visitor.js +17 -0
  66. package/dist/web.d.ts +83 -0
  67. package/dist/web.js +131 -0
  68. package/dist/webhook.d.ts +20 -0
  69. package/dist/webhook.js +39 -0
  70. package/package.json +62 -4
  71. package/themes/aer.css +12 -0
  72. package/themes/cabana.css +12 -0
  73. package/themes/curte.css +12 -0
  74. package/themes/lumen.css +12 -0
  75. package/themes/miez.css +12 -0
  76. package/themes/solvar.css +12 -0
package/dist/shop.js ADDED
@@ -0,0 +1,167 @@
1
+ const enc = encodeURIComponent;
2
+ const UUID = /^[0-9a-f-]{36}$/i;
3
+ const SESSION = 'X-Shop-Session';
4
+ /**
5
+ * Magazinul online (`/api/site/v1/shop`), cu cheia canalului. Citirile de catalog trec prin memoria clientului (separat pe limbă),
6
+ * coșul și cotele de livrare au o memorie scurtă proprie, iar tot ce ține de un cont cere sesiunea clientului (`session`).
7
+ */
8
+ export function createShopApi(client, o = {}) {
9
+ const def = o.defaultLang ?? 'ro';
10
+ const withLang = (path) => {
11
+ const l = o.lang?.();
12
+ if (!l || l === def)
13
+ return path;
14
+ return `${path}${path.includes('?') ? '&' : '?'}lang=${enc(l)}`;
15
+ };
16
+ const p = (path) => withLang(`/shop${path}`);
17
+ const read = (path) => client.get(p(path));
18
+ const send = (path, r = {}) => {
19
+ const { session, ...rest } = r;
20
+ return client.call(p(path), { ...rest, headers: { ...rest.headers, ...(session ? { [SESSION]: session } : {}) } });
21
+ };
22
+ const query = (params) => {
23
+ const sp = new URLSearchParams();
24
+ for (const [k, v] of Object.entries(params))
25
+ if (v !== undefined && v !== null && v !== '')
26
+ sp.set(k, String(v));
27
+ const s = sp.toString();
28
+ return s ? `?${s}` : '';
29
+ };
30
+ /** Coșul se ține 15 s pe token: pagina de coș și checkout-ul, una după alta, nu întreabă ERP-ul de două ori. Orice schimbare îl înlocuiește. */
31
+ const carts = new Map();
32
+ /** Cota de livrare ține 60 s pe coș și adresă (ERP-ul o calculează în 1-3 s); orice schimbare în coș o șterge. */
33
+ const ships = new Map();
34
+ const dropCart = (token) => {
35
+ carts.delete(token);
36
+ for (const k of [...ships.keys()])
37
+ if (k.startsWith(`${token}|`))
38
+ ships.delete(k);
39
+ };
40
+ /** Mutațiile coșului întorc coșul actualizat: îl păstrăm, iar cotele de livrare se șterg. */
41
+ const mutate = async (token, run) => {
42
+ dropCart(token);
43
+ const cart = await run();
44
+ if (cart?.lines)
45
+ carts.set(token, { at: Date.now(), p: Promise.resolve(cart) });
46
+ return cart;
47
+ };
48
+ const json = (body, method = 'POST') => ({ method, json: body });
49
+ return {
50
+ channel: () => read('/channel'),
51
+ paymentMethods: () => read('/payment-methods'),
52
+ menus: () => read('/menus'),
53
+ pages: () => read('/pages'),
54
+ page: (slug) => read(`/pages/${enc(slug)}`),
55
+ redirects: () => read('/redirects'),
56
+ /** O pagină de produse (`collection`, `limit`, `cursor`, filtre). */
57
+ products: (params = {}) => read(`/products${query(params)}`),
58
+ /** Toate produsele unei liste, urmând `next_cursor` (de obicei o singură cerere), ca filtrele și paginarea să lucreze pe tot catalogul. */
59
+ async allProducts(params = {}) {
60
+ const items = [];
61
+ let cursor;
62
+ for (let i = 0; i < 20; i++) {
63
+ const r = await read(`/products${query({ ...params, limit: 500, cursor })}`);
64
+ items.push(...(r?.items ?? []));
65
+ if (!r?.next_cursor)
66
+ break;
67
+ cursor = r.next_cursor;
68
+ }
69
+ return { items };
70
+ },
71
+ product: (slug) => read(`/products/${enc(slug)}`),
72
+ productReviews: (slug) => read(`/products/${enc(slug)}/reviews`),
73
+ recentReviews: (params = { limit: 12, min_rating: 5 }) => read(`/reviews${query(params)}`),
74
+ collections: () => read('/collections'),
75
+ collection: (slug) => read(`/collections/${enc(slug)}`),
76
+ /** Căutarea nu trece prin memorie: interogările sunt prea variate. */
77
+ search: (q) => send(`/search${query({ q: q.slice(0, 120) })}`),
78
+ counties: () => read('/geo/counties'),
79
+ cities: (county, q) => send(`/geo/cities${query({ county, q, limit: 12 })}`),
80
+ streets: (a) => send(`/geo/streets${query({ ...a, limit: 8 })}`),
81
+ /** Verificarea adresei de livrare: un ajutor pentru client, nu un blocaj. */
82
+ addressCheck: (a) => send(`/geo/address-check${query(a)}`),
83
+ createCart: (body = {}) => send('/carts', json(body)),
84
+ cart(token) {
85
+ const hit = carts.get(token);
86
+ if (hit && Date.now() - hit.at < 15_000)
87
+ return hit.p;
88
+ const pr = send(`/carts/${enc(token)}`);
89
+ carts.set(token, { at: Date.now(), p: pr });
90
+ pr.catch(() => carts.delete(token));
91
+ return pr;
92
+ },
93
+ addLine: (token, productId, qty = 1) => mutate(token, () => send(`/carts/${enc(token)}/lines`, json({ product_id: productId, qty }))),
94
+ setLineQty: (token, lineId, qty) => mutate(token, () => send(`/carts/${enc(token)}/lines/${enc(lineId)}`, json({ qty }, 'PATCH'))),
95
+ removeLine: (token, lineId) => mutate(token, () => send(`/carts/${enc(token)}/lines/${enc(lineId)}`, { method: 'DELETE' })),
96
+ applyDiscount: (token, code) => mutate(token, () => send(`/carts/${enc(token)}/discount`, json({ code }))),
97
+ clearDiscount: (token) => mutate(token, () => send(`/carts/${enc(token)}/discount`, { method: 'DELETE' })),
98
+ shippingQuote(token, a) {
99
+ const city = a.city?.trim() ?? '';
100
+ const postal = a.postalCode?.trim() ?? '';
101
+ const k = `${token}|${a.county.toLowerCase()}|${city.toLowerCase()}|${postal}`;
102
+ const hit = ships.get(k);
103
+ if (hit && Date.now() - hit.at < 60_000)
104
+ return hit.p;
105
+ const pr = send(`/shipping/quote${query({ cart_token: token, county: a.county, city, postal_code: postal })}`);
106
+ ships.set(k, { at: Date.now(), p: pr });
107
+ pr.catch(() => ships.delete(k));
108
+ return pr;
109
+ },
110
+ /** `idempotencyKey`: același pentru reîncercările aceleiași comenzi (de exemplu un id generat când se deschide checkout-ul). */
111
+ checkout(token, body, idempotencyKey, session) {
112
+ dropCart(token);
113
+ return send(`/carts/${enc(token)}/checkout`, { ...json(body), session, headers: { 'Idempotency-Key': idempotencyKey } });
114
+ },
115
+ trackOrder: (params) => send(`/orders/track${query(params)}`),
116
+ register: (body) => send('/accounts', json(body)),
117
+ login: (body) => send('/accounts/login', json(body)),
118
+ me: (session) => send('/me', { session }),
119
+ updateMe: (session, body) => send('/me', { ...json(body, 'PATCH'), session }),
120
+ loyalty: (session) => send('/me/loyalty', { session }),
121
+ orders: (session, limit = 50) => send(`/me/orders${query({ limit })}`, { session }),
122
+ order: (session, number) => send(`/me/orders/${enc(number)}`, { session }),
123
+ addresses: (session) => send('/me/addresses', { session }),
124
+ addAddress: (session, body) => send('/me/addresses', { ...json(body), session }),
125
+ deleteAddress: (session, id) => send(`/me/addresses/${enc(id)}`, { method: 'DELETE', session }),
126
+ wishlist: (session) => send('/me/wishlist', { session }),
127
+ wishAdd: (session, productId) => send('/me/wishlist', { ...json({ product_id: productId }), session }),
128
+ wishRemove: (session, productId) => send(`/me/wishlist/${enc(productId)}`, { method: 'DELETE', session }),
129
+ orderReviews: (session, number) => send(`/me/orders/${enc(number)}/reviews`, { session }),
130
+ pendingReviews: (session) => send('/me/reviews/pending', { session }),
131
+ async submitReview(slug, body) {
132
+ const r = await send(`/products/${enc(slug)}/reviews`, json(body));
133
+ client.forget((path) => path.startsWith(`/shop/products/${enc(slug)}/reviews`) || path.startsWith('/shop/reviews'));
134
+ return r;
135
+ },
136
+ giftOffer: () => send('/gift-cards'),
137
+ buyGiftCard: (body) => send('/gift-cards', json(body)),
138
+ giftStatus: (token) => send(`/gift-cards/${enc(token)}`),
139
+ requestQuote: (body) => send('/quote-requests', json(body)),
140
+ requestReturn: (body) => send('/returns', json(body)),
141
+ /**
142
+ * Webhook-ul `shop.changed`: reîmprospătează în fundal doar ce s-a schimbat. Cu `product_ids`, intrările care conțin acele produse
143
+ * (fișa, listele, colecțiile); cu `prefixes`, părțile din vitrină numite de ERP (`page:`, `menus`, `redirects`...); fără ele, tot magazinul.
144
+ */
145
+ purgeChanged(e = {}) {
146
+ carts.clear();
147
+ ships.clear();
148
+ const ids = (e.product_ids ?? []).filter((x) => UUID.test(x));
149
+ const paths = (e.prefixes ?? []).filter((x) => typeof x === 'string' && x.length < 40).map(prefixPath);
150
+ const shopOnly = (path) => path.startsWith('/shop/');
151
+ if (e.all || (!ids.length && !paths.length))
152
+ return client.purge(shopOnly);
153
+ client.purge((path, value) => {
154
+ if (!shopOnly(path))
155
+ return false;
156
+ if (paths.some((x) => path.startsWith(x)))
157
+ return true;
158
+ if (!ids.length)
159
+ return false;
160
+ const s = JSON.stringify(value);
161
+ return ids.some((id) => s.includes(id));
162
+ });
163
+ },
164
+ };
165
+ }
166
+ /** Prefixul unei chei de vitrină din `shop.changed` -> începutul căii din API: `page:` -> `/shop/pages/`, `menus` -> `/shop/menus`. */
167
+ export const prefixPath = (prefix) => `/shop/${prefix.endsWith(':') ? `${prefix.slice(0, -1)}s/` : prefix}`;
@@ -0,0 +1,7 @@
1
+ /** Antetul prin care site-ul spune ERP-ului cine e vizitatorul, ca limitele să se aplice pe el, nu pe tot site-ul. */
2
+ export declare const VISITOR_HEADER = "X-Rivil-Client-IP";
3
+ /**
4
+ * Adresa vizitatorului. Cu un singur proxy în față (Traefik), ultima valoare din `X-Forwarded-For` e cea reală;
5
+ * primele pot fi scrise de oricine. Fără antet, `fallback` (de obicei `clientAddress` din Astro).
6
+ */
7
+ export declare function visitorIp(request: Request, fallback?: () => string): string;
@@ -0,0 +1,17 @@
1
+ /** Antetul prin care site-ul spune ERP-ului cine e vizitatorul, ca limitele să se aplice pe el, nu pe tot site-ul. */
2
+ export const VISITOR_HEADER = 'X-Rivil-Client-IP';
3
+ /**
4
+ * Adresa vizitatorului. Cu un singur proxy în față (Traefik), ultima valoare din `X-Forwarded-For` e cea reală;
5
+ * primele pot fi scrise de oricine. Fără antet, `fallback` (de obicei `clientAddress` din Astro).
6
+ */
7
+ export function visitorIp(request, fallback) {
8
+ const last = request.headers.get('x-forwarded-for')?.split(',').at(-1)?.trim();
9
+ if (last)
10
+ return last;
11
+ try {
12
+ return fallback?.() ?? '';
13
+ }
14
+ catch {
15
+ return '';
16
+ }
17
+ }
package/dist/web.d.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Partea care merge și în browser: cererile prin proxy-ul site-ului (`/api/rivil/...`) și funcțiile pure folosite de formulare.
3
+ * Fără cheie și fără module Node.
4
+ */
5
+ export declare class SiteError extends Error {
6
+ readonly status: number;
7
+ readonly code: string;
8
+ readonly details?: unknown | undefined;
9
+ constructor(message: string, status: number, code: string, details?: unknown | undefined);
10
+ }
11
+ export type RivilFetch = <T = unknown>(path: string, init?: {
12
+ method?: string;
13
+ json?: unknown;
14
+ body?: BodyInit;
15
+ query?: Record<string, string | number | undefined | null>;
16
+ }) => Promise<T>;
17
+ /** Fabrica pentru `rivilFetch`, cu alt prefix sau alt `fetch` (teste). */
18
+ export declare function createRivilFetch(base?: string, doFetch?: typeof fetch): RivilFetch;
19
+ /** Cerere spre ERP prin proxy-ul site-ului; aruncă `SiteError` cu mesajul din ERP, în limba companiei. */
20
+ export declare const rivilFetch: RivilFetch;
21
+ /** Mesajul unei erori, pentru om. */
22
+ export declare const errorMessage: (e: unknown) => string;
23
+ /** Textul unui consimțământ, cu linkurile `[text](https://...)` scoase ca bucăți separate (fără HTML de la ERP în pagină). */
24
+ export declare function consentParts(text: string): Array<{
25
+ text: string;
26
+ href?: string;
27
+ }>;
28
+ /** O valoare lipsă pentru un câmp obligatoriu: gol, `false` sau listă goală. */
29
+ export declare const isEmpty: (v: unknown) => boolean;
30
+ /** Primul câmp obligatoriu necompletat, sau `null`. */
31
+ export declare function firstMissing<T extends {
32
+ required?: boolean;
33
+ }>(items: T[], valueOf: (item: T) => unknown): T | null;
34
+ export declare const isEmail: (s: string) => boolean;
35
+ /** Ziua locală `YYYY-MM-DD` (fără fus orar: e ziua din calendarul omului). */
36
+ export declare const isoDay: (d: Date) => string;
37
+ export declare const addDays: (d: Date, n: number) => Date;
38
+ /** Orele libere pe zile, după începutul lor (`2026-12-04T10:30` merge la `2026-12-04`). */
39
+ export declare function groupByDay<T extends {
40
+ start: string;
41
+ }>(slots: T[]): Map<string, T[]>;
42
+ export declare function money(n: number, currency: string, lang: string): string;
43
+ /** Text simplu din ERP (rânduri, liste cu `-` sau `•`) ca HTML sigur: paragrafe și liste, fără nimic din textul original ca HTML. */
44
+ export declare function textToHtml(raw: unknown): string;
45
+ export type BookingStep = 'services' | 'location' | 'specialist' | 'time' | 'details';
46
+ type CatalogLike = {
47
+ services: Array<{
48
+ id: string;
49
+ durationMinutes: number;
50
+ price: number | null;
51
+ specialistIds: string[] | null;
52
+ locationIds: string[];
53
+ }>;
54
+ locations: Array<{
55
+ id: string;
56
+ }>;
57
+ employees: Array<{
58
+ id: string;
59
+ locationIds?: string[];
60
+ }>;
61
+ config?: {
62
+ showSpecialists?: boolean;
63
+ };
64
+ flow?: {
65
+ steps?: Array<{
66
+ type: string;
67
+ enabled?: boolean;
68
+ }>;
69
+ };
70
+ };
71
+ /**
72
+ * Pașii programării pentru alegerea de acum, ca în formularul din ERP: locația apare doar când serviciile alese se fac în mai multe locuri,
73
+ * specialistul doar când firma îi arată. Locațiile și specialiștii sunt cei care pot face toate serviciile alese.
74
+ */
75
+ export declare function bookingPlan<C extends CatalogLike>(catalog: C, picked: string[], locationId: string): {
76
+ chosen: C["services"];
77
+ locations: C["locations"];
78
+ employees: C["employees"];
79
+ steps: BookingStep[];
80
+ minutes: number;
81
+ total: number;
82
+ };
83
+ export {};
package/dist/web.js ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Partea care merge și în browser: cererile prin proxy-ul site-ului (`/api/rivil/...`) și funcțiile pure folosite de formulare.
3
+ * Fără cheie și fără module Node.
4
+ */
5
+ export class SiteError extends Error {
6
+ status;
7
+ code;
8
+ details;
9
+ constructor(message, status, code, details) {
10
+ super(message);
11
+ this.status = status;
12
+ this.code = code;
13
+ this.details = details;
14
+ this.name = 'SiteError';
15
+ }
16
+ }
17
+ /** Fabrica pentru `rivilFetch`, cu alt prefix sau alt `fetch` (teste). */
18
+ export function createRivilFetch(base = '/api/rivil', doFetch = (...a) => fetch(...a)) {
19
+ return async (path, init = {}) => {
20
+ const sp = new URLSearchParams();
21
+ for (const [k, v] of Object.entries(init.query ?? {}))
22
+ if (v !== undefined && v !== null && v !== '')
23
+ sp.set(k, String(v));
24
+ const qs = sp.toString();
25
+ const res = await doFetch(`${base}/${path.replace(/^\/+/, '')}${qs ? `?${qs}` : ''}`, {
26
+ method: init.method ?? (init.json !== undefined || init.body ? 'POST' : 'GET'),
27
+ headers: init.json !== undefined ? { 'content-type': 'application/json' } : undefined,
28
+ body: init.json !== undefined ? JSON.stringify(init.json) : init.body,
29
+ });
30
+ if (res.status === 204)
31
+ return null;
32
+ const out = (await res.json().catch(() => ({})));
33
+ if (!res.ok) {
34
+ const e = typeof out.error === 'string' ? { message: out.error } : (out.error ?? {});
35
+ throw new SiteError(e.message || `HTTP ${res.status}`, res.status, ('code' in e && e.code) || 'error', 'details' in e ? e.details : undefined);
36
+ }
37
+ return out;
38
+ };
39
+ }
40
+ /** Cerere spre ERP prin proxy-ul site-ului; aruncă `SiteError` cu mesajul din ERP, în limba companiei. */
41
+ export const rivilFetch = createRivilFetch();
42
+ /** Mesajul unei erori, pentru om. */
43
+ export const errorMessage = (e) => (e instanceof Error ? e.message : String(e));
44
+ /** Textul unui consimțământ, cu linkurile `[text](https://...)` scoase ca bucăți separate (fără HTML de la ERP în pagină). */
45
+ export function consentParts(text) {
46
+ return text
47
+ .split(/(\[[^\]]+\]\(https?:\/\/[^)\s]+\))/g)
48
+ .filter(Boolean)
49
+ .map((p) => {
50
+ const m = /^\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)$/.exec(p);
51
+ return m ? { text: m[1], href: m[2] } : { text: p.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') };
52
+ });
53
+ }
54
+ /** O valoare lipsă pentru un câmp obligatoriu: gol, `false` sau listă goală. */
55
+ export const isEmpty = (v) => v === undefined || v === null || v === '' || v === false || (Array.isArray(v) && v.length === 0);
56
+ /** Primul câmp obligatoriu necompletat, sau `null`. */
57
+ export function firstMissing(items, valueOf) {
58
+ return items.find((i) => i.required && isEmpty(valueOf(i))) ?? null;
59
+ }
60
+ export const isEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim());
61
+ /** Ziua locală `YYYY-MM-DD` (fără fus orar: e ziua din calendarul omului). */
62
+ export const isoDay = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
63
+ export const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
64
+ /** Orele libere pe zile, după începutul lor (`2026-12-04T10:30` merge la `2026-12-04`). */
65
+ export function groupByDay(slots) {
66
+ const m = new Map();
67
+ for (const s of slots)
68
+ m.set(s.start.slice(0, 10), [...(m.get(s.start.slice(0, 10)) ?? []), s]);
69
+ return m;
70
+ }
71
+ export function money(n, currency, lang) {
72
+ return new Intl.NumberFormat(lang === 'ro' ? 'ro-RO' : lang === 'en' ? 'en-GB' : lang, { style: 'currency', currency, maximumFractionDigits: n % 1 ? 2 : 0 }).format(n);
73
+ }
74
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
75
+ /** Text simplu din ERP (rânduri, liste cu `-` sau `•`) ca HTML sigur: paragrafe și liste, fără nimic din textul original ca HTML. */
76
+ export function textToHtml(raw) {
77
+ const out = [];
78
+ let list = [];
79
+ let para = [];
80
+ const flush = () => {
81
+ if (para.length)
82
+ out.push(`<p>${para.join('<br>')}</p>`);
83
+ if (list.length)
84
+ out.push(`<ul>${list.map((l) => `<li>${l}</li>`).join('')}</ul>`);
85
+ para = [];
86
+ list = [];
87
+ };
88
+ for (const line of String(raw ?? '').split(/\r?\n/)) {
89
+ const t = line.trim();
90
+ const item = /^[-•*]\s+(.*)$/.exec(t);
91
+ if (!t)
92
+ flush();
93
+ else if (item) {
94
+ if (para.length)
95
+ flush();
96
+ list.push(esc(item[1]));
97
+ }
98
+ else {
99
+ if (list.length)
100
+ flush();
101
+ para.push(esc(t));
102
+ }
103
+ }
104
+ flush();
105
+ return out.join('');
106
+ }
107
+ /**
108
+ * Pașii programării pentru alegerea de acum, ca în formularul din ERP: locația apare doar când serviciile alese se fac în mai multe locuri,
109
+ * specialistul doar când firma îi arată. Locațiile și specialiștii sunt cei care pot face toate serviciile alese.
110
+ */
111
+ export function bookingPlan(catalog, picked, locationId) {
112
+ const chosen = catalog.services.filter((s) => picked.includes(s.id));
113
+ const locations = catalog.locations.filter((l) => chosen.every((s) => s.locationIds.includes(l.id)));
114
+ const employees = catalog.employees.filter((e) => chosen.every((s) => !s.specialistIds || s.specialistIds.includes(e.id)) && (!locationId || !e.locationIds || e.locationIds.includes(locationId)));
115
+ const on = (type) => catalog.flow?.steps?.find((s) => s.type === type)?.enabled !== false;
116
+ const steps = [
117
+ 'services',
118
+ ...(on('location') && locations.length > 1 ? ['location'] : []),
119
+ ...(on('specialist') && catalog.config?.showSpecialists && employees.length > 0 ? ['specialist'] : []),
120
+ 'time',
121
+ 'details',
122
+ ];
123
+ return {
124
+ chosen,
125
+ locations,
126
+ employees,
127
+ steps,
128
+ minutes: chosen.reduce((n, s) => n + s.durationMinutes, 0),
129
+ total: chosen.reduce((n, s) => n + (s.price ?? 0), 0),
130
+ };
131
+ }
@@ -0,0 +1,20 @@
1
+ export type RivilEvent<T = unknown> = {
2
+ id?: string;
3
+ type: string;
4
+ created_at?: string;
5
+ data: {
6
+ object: T;
7
+ };
8
+ };
9
+ /**
10
+ * Verifică semnătura unui webhook Rivil: antetul `X-Rivil-Signature: t=<secunde>,v1=<hex>`, HMAC-SHA256 peste `<t>.<corp>`.
11
+ * Un eveniment mai vechi de `toleranceSec` (implicit 5 minute) e refuzat, ca o cerere prinsă să nu poată fi retrimisă.
12
+ */
13
+ export declare function verifyRivilSignature(body: string, header: string | null | undefined, secret: string, toleranceSec?: number, nowSec?: number): boolean;
14
+ /** Semnătura pe care ar trimite-o ERP-ul (pentru teste și pentru verificarea locală a unui endpoint). */
15
+ export declare function signRivilPayload(body: string, secret: string, nowSec?: number): string;
16
+ /**
17
+ * Handler pentru ruta de webhook a site-ului (`POST /api/hooks/rivil`): verifică semnătura, apoi cheamă `onEvent`.
18
+ * Răspunde 401 la semnătură greșită și 204 după procesare.
19
+ */
20
+ export declare function rivilWebhookHandler(secret: string | (() => string), onEvent: (e: RivilEvent) => void | Promise<void>): (request: Request) => Promise<Response>;
@@ -0,0 +1,39 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * Verifică semnătura unui webhook Rivil: antetul `X-Rivil-Signature: t=<secunde>,v1=<hex>`, HMAC-SHA256 peste `<t>.<corp>`.
4
+ * Un eveniment mai vechi de `toleranceSec` (implicit 5 minute) e refuzat, ca o cerere prinsă să nu poată fi retrimisă.
5
+ */
6
+ export function verifyRivilSignature(body, header, secret, toleranceSec = 300, nowSec = Date.now() / 1000) {
7
+ if (!secret || !header)
8
+ return false;
9
+ const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header.trim());
10
+ if (!m || Math.abs(nowSec - Number(m[1])) > toleranceSec)
11
+ return false;
12
+ const want = createHmac('sha256', secret).update(`${m[1]}.${body}`).digest();
13
+ return timingSafeEqual(want, Buffer.from(m[2], 'hex'));
14
+ }
15
+ /** Semnătura pe care ar trimite-o ERP-ul (pentru teste și pentru verificarea locală a unui endpoint). */
16
+ export function signRivilPayload(body, secret, nowSec = Math.floor(Date.now() / 1000)) {
17
+ return `t=${nowSec},v1=${createHmac('sha256', secret).update(`${nowSec}.${body}`).digest('hex')}`;
18
+ }
19
+ /**
20
+ * Handler pentru ruta de webhook a site-ului (`POST /api/hooks/rivil`): verifică semnătura, apoi cheamă `onEvent`.
21
+ * Răspunde 401 la semnătură greșită și 204 după procesare.
22
+ */
23
+ export function rivilWebhookHandler(secret, onEvent) {
24
+ return async (request) => {
25
+ const body = await request.text();
26
+ const key = typeof secret === 'function' ? secret() : secret;
27
+ if (!verifyRivilSignature(body, request.headers.get('x-rivil-signature'), key))
28
+ return new Response(null, { status: 401 });
29
+ let event;
30
+ try {
31
+ event = JSON.parse(body);
32
+ }
33
+ catch {
34
+ return new Response(null, { status: 400 });
35
+ }
36
+ await onEvent(event);
37
+ return new Response(null, { status: 204 });
38
+ };
39
+ }
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@rivil-solutions/site-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Client pentru API-ul de site Rivil (/api/site/v1): conținut, module, memorie cu golire prin webhook, imagini, limbi, sitemap, blocuri pentru starter.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist",
10
+ "blocks",
11
+ "themes",
12
+ "bin",
13
+ "README.md"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ },
20
+ "./astro-image": {
21
+ "types": "./dist/astro-image.d.ts",
22
+ "import": "./dist/astro-image.js"
23
+ },
24
+ "./web": {
25
+ "types": "./dist/web.d.ts",
26
+ "import": "./dist/web.js"
27
+ },
28
+ "./react": {
29
+ "types": "./dist/react/index.d.ts",
30
+ "import": "./dist/react/index.js"
31
+ }
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "check": "tsc --noEmit -p tsconfig.json",
36
+ "test": "vitest run",
37
+ "prepublishOnly": "pnpm check && pnpm test && pnpm build"
38
+ },
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
42
+ "devDependencies": {
43
+ "@testing-library/react": "^16.3.3",
44
+ "@types/node": "^24.19.2",
45
+ "@types/react": "^19.3.3",
46
+ "@types/react-dom": "^19.3.0",
47
+ "happy-dom": "^21.0.4",
48
+ "react": "^19.3.1",
49
+ "react-dom": "^19.3.1",
50
+ "typescript": "^5.8.2",
51
+ "vitest": "^5.1.0"
52
+ },
53
+ "peerDependencies": {
54
+ "react": ">=18"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "react": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "bin": {
62
+ "rivil": "bin/rivil.mjs"
63
+ }
64
+ }
package/themes/aer.css ADDED
@@ -0,0 +1,12 @@
1
+ /* Aer Studio: programări (salon, wellness), luminos, butoane rotunde. */
2
+ :root {
3
+ --bg: #fbf8f2;
4
+ --fg: #1e2b24;
5
+ --muted: #57635b;
6
+ --line: #ebe3d4;
7
+ --accent: #c9472a;
8
+ --accent-fg: #ffffff;
9
+ --radius: 18px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: system-ui, -apple-system, 'Segoe UI', sans-serif;
12
+ }
@@ -0,0 +1,12 @@
1
+ /* Cabana Măgura: cazare la munte, cald, cu titluri serif. */
2
+ :root {
3
+ --bg: #fbf8f2;
4
+ --fg: #2b2620;
5
+ --muted: #6b6155;
6
+ --line: #e9e1d2;
7
+ --accent: #a8571f;
8
+ --accent-fg: #ffffff;
9
+ --radius: 6px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: Georgia, 'Times New Roman', serif;
12
+ }
@@ -0,0 +1,12 @@
1
+ /* Atelierul din Curte: evenimente și ateliere, cald, accent cărămiziu. */
2
+ :root {
3
+ --bg: #fffdf9;
4
+ --fg: #231a2e;
5
+ --muted: #665c6e;
6
+ --line: #efe4d4;
7
+ --accent: #b8452e;
8
+ --accent-fg: #ffffff;
9
+ --radius: 16px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: Georgia, 'Times New Roman', serif;
12
+ }
@@ -0,0 +1,12 @@
1
+ /* Casa Lumen: magazin de obiecte pentru casă, verde închis și auriu. */
2
+ :root {
3
+ --bg: #f7f3ec;
4
+ --fg: #16221c;
5
+ --muted: #66685d;
6
+ --line: #ddd5c5;
7
+ --accent: #1f4d3a;
8
+ --accent-fg: #ffffff;
9
+ --radius: 12px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: Georgia, 'Times New Roman', serif;
12
+ }
@@ -0,0 +1,12 @@
1
+ /* Școala Miez: cursuri, clar, accent albastru. */
2
+ :root {
3
+ --bg: #ffffff;
4
+ --fg: #17181c;
5
+ --muted: #5b5d66;
6
+ --line: #f1ecdf;
7
+ --accent: #2f46d6;
8
+ --accent-fg: #ffffff;
9
+ --radius: 8px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: system-ui, -apple-system, 'Segoe UI', sans-serif;
12
+ }
@@ -0,0 +1,12 @@
1
+ /* Solvar: firmă, cariere, sobru, colțuri drepte. */
2
+ :root {
3
+ --bg: #f7f8f3;
4
+ --fg: #0d1f1b;
5
+ --muted: #55635e;
6
+ --line: #dfe3da;
7
+ --accent: #0b1f1c;
8
+ --accent-fg: #c8f169;
9
+ --radius: 0px;
10
+ --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
11
+ --font-display: system-ui, -apple-system, 'Segoe UI', sans-serif;
12
+ }