rapida-partner 8.2.0 → 8.3.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.
package/index.ts CHANGED
@@ -4,6 +4,7 @@ import { tsProjectToJsonProject } from "./src/controllers/ts_project_to_json_pro
4
4
  import { validateProjectJson } from "./src/utils/json";
5
5
  import { checkListReferences } from "./src/utils/list-references";
6
6
  import { checkFormReferences } from "./src/utils/form-references";
7
+ import { checkStoreReferences } from "./src/utils/store-references";
7
8
  import type { IProject } from "./src/interfaces/project.interface";
8
9
  import * as fs from "fs";
9
10
  import * as path from "path";
@@ -79,7 +80,7 @@ async function main() {
79
80
  process.exit(1);
80
81
  }
81
82
 
82
- for (const warning of [...checkListReferences(project), ...checkFormReferences(project)]) {
83
+ for (const warning of [...checkListReferences(project), ...checkFormReferences(project), ...checkStoreReferences(project)]) {
83
84
  console.warn("Aviso: " + warning);
84
85
  }
85
86
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapida-partner",
3
- "version": "8.2.0",
3
+ "version": "8.3.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "index.ts",
6
6
  "files": [
@@ -5,6 +5,12 @@
5
5
  */
6
6
  export type TStoreOrderFulfillmentStatus = "received" | "preparing" | "shipped" | "delivered" | "cancelled";
7
7
 
8
+ /** Como o cliente recebe o pedido: entrega no endereço ou retirada na loja. */
9
+ export type TStoreDeliveryMethod = "delivery" | "pickup";
10
+
11
+ /** Como o cliente paga: online (Mercado Pago) ou na entrega/retirada. */
12
+ export type TStorePaymentMethod = "online" | "onDelivery";
13
+
8
14
  export interface IStoreOrderItem {
9
15
  productId: string;
10
16
  name: string;
@@ -38,6 +44,17 @@ export interface IStoreOrder {
38
44
  total: number;
39
45
  currency: string;
40
46
  status: TStoreOrderFulfillmentStatus;
47
+ // Padrão "delivery". Na retirada não há endereço, e "shipped" quer dizer
48
+ // pronto para retirar.
49
+ deliveryMethod?: TStoreDeliveryMethod;
50
+ // Bairro escolhido na entrega por bairro (funcionalidade "districtDelivery").
51
+ deliveryDistrict?: string;
52
+ // Padrão "online". Com "onDelivery", o pedido chega confirmado e sem
53
+ // pagamento: changeFor é o valor para o troco, e o vendedor marca
54
+ // paymentReceived quando receber.
55
+ paymentMethod?: TStorePaymentMethod;
56
+ changeFor?: number;
57
+ paymentReceived?: boolean;
41
58
  trackingCode?: string;
42
59
  trackingUrl?: string;
43
60
  notes?: string;
@@ -14,7 +14,11 @@ export type TStoreFeature =
14
14
  | "shipping"
15
15
  | "coupons"
16
16
  | "reviews"
17
- | "returns";
17
+ | "returns"
18
+ | "openingHours"
19
+ | "pickup"
20
+ | "districtDelivery"
21
+ | "payOnDelivery";
18
22
 
19
23
  export type TStoreFeatureToggle = `${TStoreFeature}Enabled`;
20
24
 
@@ -24,6 +28,37 @@ export type TStoreFont = "inter" | "poppins" | "nunito" | "montserrat" | "roboto
24
28
  /** Arredondamento de cartões, botões e campos: reto, suave ou arredondado. */
25
29
  export type TStoreRadius = "none" | "soft" | "rounded";
26
30
 
31
+ /** Dia da semana de um horário de funcionamento. */
32
+ export type TStoreWeekday = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";
33
+
34
+ /**
35
+ * Um período aberto num dia, em "HH:MM" no fuso da loja. Fechar antes de abrir
36
+ * (ex.: 18:00 às 02:00) é atravessar a meia-noite. Um dia pode ter vários
37
+ * períodos (ex.: almoço e jantar).
38
+ */
39
+ export interface IStoreOpeningHours {
40
+ weekday: TStoreWeekday;
41
+ opensAt: string;
42
+ closesAt: string;
43
+ }
44
+
45
+ /** Bairro atendido pela entrega local, com taxa e prazo mostrado ao cliente. */
46
+ export interface IStoreDeliveryDistrict {
47
+ name: string;
48
+ price: number;
49
+ // Texto livre do prazo (ex.: "40 a 60 min").
50
+ deliveryTime?: string;
51
+ }
52
+
53
+ /** Catálogo em grade de cartões ou em lista (foto pequena ao lado do nome). */
54
+ export type TStoreCatalogLayout = "grid" | "list";
55
+
56
+ /**
57
+ * Proporção da foto no cartão do produto: "auto" mostra a foto inteira numa
58
+ * área fixa (o padrão de sempre); as outras recortam a foto na proporção.
59
+ */
60
+ export type TStoreImageAspect = "auto" | "square" | "landscape" | "portrait";
61
+
27
62
  /**
28
63
  * Configuração da loja: identidade, visual, contato, dados legais, redes,
29
64
  * comercial e liga e desliga. É o registro único editado no Backoffice do
@@ -49,6 +84,10 @@ export interface IStoreSettings extends Partial<Record<TStoreFeatureToggle, bool
49
84
  font?: TStoreFont;
50
85
  radius?: TStoreRadius;
51
86
  pageSize?: number;
87
+ catalogLayout?: TStoreCatalogLayout;
88
+ // Colunas da grade no computador; só vale com catalogLayout "grid".
89
+ catalogColumns?: 2 | 3 | 4;
90
+ productImageAspect?: TStoreImageAspect;
52
91
 
53
92
  // Somente dígitos, com DDI (ex.: "5582999999999").
54
93
  whatsappNumber?: string;
@@ -82,6 +121,25 @@ export interface IStoreSettings extends Partial<Record<TStoreFeatureToggle, bool
82
121
  // para compra fora da loja física).
83
122
  returnWindowDays?: number;
84
123
 
124
+ // Só têm efeito com a funcionalidade "openingHours": fora dos períodos, ou
125
+ // com ordersPaused, a loja não aceita pedidos (a API recusa e a vitrine
126
+ // avisa). Sem períodos, a loja fica sempre aberta. timeZone é um fuso IANA
127
+ // (padrão "America/Sao_Paulo"). weekdayHours e saturdayHours continuam como
128
+ // texto de contato.
129
+ openingHours?: IStoreOpeningHours[];
130
+ // Só tem efeito com a funcionalidade "pickup": endereço de retirada mostrado
131
+ // ao cliente; vazio usa address.
132
+ pickupAddress?: string;
133
+ // Só tem efeito com a funcionalidade "districtDelivery": o cliente escolhe o
134
+ // bairro na lista e paga a taxa dele; bairro fora da lista não é atendido.
135
+ // Com ela ligada, o frete por faixa de CEP não é usado.
136
+ deliveryDistricts?: IStoreDeliveryDistrict[];
137
+ // Valor mínimo dos itens (subtotal) para fechar o pedido; 0 ou vazio não
138
+ // exige mínimo. Vale para toda loja com venda própria.
139
+ minimumOrderValue?: number;
140
+ timeZone?: string;
141
+ ordersPaused?: boolean;
142
+
85
143
  // Páginas institucionais e legais, em HTML (editor de texto rico). Cada
86
144
  // página só é publicada, com link no rodapé, quando tem texto. O contato usa
87
145
  // os campos de contato acima.
@@ -130,6 +188,17 @@ export interface IStoreShippingRange {
130
188
  deliveryDays: number;
131
189
  }
132
190
 
191
+ /**
192
+ * Segmento da loja. Escolhe os padrões do segmento: textos, funcionalidades
193
+ * ligadas, rótulos do andamento do pedido e etapas do checkout. Cada
194
+ * funcionalidade continua podendo ser ligada ou desligada em `features`.
195
+ * - "retail": produtos com envio (o comportamento de sempre).
196
+ * - "food": cardápio, com entrega local ou retirada.
197
+ * - "services": serviços e passeios com data.
198
+ * - "events": shows e teatro, com sessões e ingressos.
199
+ */
200
+ export type TStoreSegment = "retail" | "food" | "services" | "events";
201
+
133
202
  /**
134
203
  * Configuração da loja no projeto da própria loja (`IProject.store`).
135
204
  *
@@ -138,9 +207,13 @@ export interface IStoreShippingRange {
138
207
  * gravação e como reserva se a leitura falhar.
139
208
  */
140
209
  export interface IProjectStore {
141
- // Funcionalidades opcionais geradas. Sem a lista, nenhuma é gerada. Passe a
142
- // mesma lista para getStoreSettingsModule no Backoffice do vendedor, para o
143
- // form só mostrar o liga e desliga do que a loja tem.
210
+ // Um segmento por loja; só vale para skeleton "ecommerce"/"marketplace".
211
+ // Sem ele, a loja se comporta como "retail".
212
+ segment?: TStoreSegment;
213
+ // Funcionalidades opcionais geradas. Sem a lista, vale o padrão do segmento
214
+ // (STORE_SEGMENT_DEFAULT_FEATURES); sem segmento, nenhuma é gerada. Passe a
215
+ // mesma lista (storeFeaturesOf) para getStoreSettingsModule no Backoffice do
216
+ // vendedor, para o form só mostrar o liga e desliga do que a loja tem.
144
217
  features?: TStoreFeature[];
145
218
  defaults?: IStoreSettings;
146
219
  }
@@ -3,11 +3,15 @@
3
3
  "$schema": "http://json-schema.org/draft-07/schema#",
4
4
  "type": "object",
5
5
  "properties": {
6
+ "segment": {
7
+ "type": "string",
8
+ "enum": ["retail", "food", "services", "events"]
9
+ },
6
10
  "features": {
7
11
  "type": "array",
8
12
  "items": {
9
13
  "type": "string",
10
- "enum": ["whatsappButton", "stockAvailability", "cashDiscount", "installments", "favorites", "blog", "shipping", "coupons", "reviews", "returns"]
14
+ "enum": ["whatsappButton", "stockAvailability", "cashDiscount", "installments", "favorites", "blog", "shipping", "coupons", "reviews", "returns", "openingHours", "pickup", "districtDelivery", "payOnDelivery"]
11
15
  },
12
16
  "uniqueItems": true
13
17
  },
@@ -14,6 +14,9 @@
14
14
  },
15
15
  "radius": { "type": "string", "enum": ["none", "soft", "rounded"] },
16
16
  "pageSize": { "type": "integer", "minimum": 1 },
17
+ "catalogLayout": { "type": "string", "enum": ["grid", "list"] },
18
+ "catalogColumns": { "type": "integer", "enum": [2, 3, 4] },
19
+ "productImageAspect": { "type": "string", "enum": ["auto", "square", "landscape", "portrait"] },
17
20
  "whatsappNumber": { "type": "string", "pattern": "^[0-9]{10,15}$" },
18
21
  "phone": { "type": "string" },
19
22
  "email": { "type": "string" },
@@ -46,6 +49,36 @@
46
49
  }
47
50
  },
48
51
  "returnWindowDays": { "type": "integer", "minimum": 0 },
52
+ "openingHours": {
53
+ "type": "array",
54
+ "items": {
55
+ "type": "object",
56
+ "properties": {
57
+ "weekday": { "type": "string", "enum": ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] },
58
+ "opensAt": { "type": "string", "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$" },
59
+ "closesAt": { "type": "string", "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$" }
60
+ },
61
+ "required": ["weekday", "opensAt", "closesAt"],
62
+ "additionalProperties": false
63
+ }
64
+ },
65
+ "timeZone": { "type": "string" },
66
+ "pickupAddress": { "type": "string" },
67
+ "deliveryDistricts": {
68
+ "type": "array",
69
+ "items": {
70
+ "type": "object",
71
+ "properties": {
72
+ "name": { "type": "string", "minLength": 1 },
73
+ "price": { "type": "number", "minimum": 0 },
74
+ "deliveryTime": { "type": "string" }
75
+ },
76
+ "required": ["name", "price"],
77
+ "additionalProperties": false
78
+ }
79
+ },
80
+ "minimumOrderValue": { "type": "number", "minimum": 0 },
81
+ "ordersPaused": { "type": "boolean" },
49
82
  "aboutText": { "type": "string" },
50
83
  "privacyPolicyText": { "type": "string" },
51
84
  "termsText": { "type": "string" },
@@ -89,6 +122,10 @@
89
122
  "shippingEnabled": { "type": "boolean" },
90
123
  "couponsEnabled": { "type": "boolean" },
91
124
  "reviewsEnabled": { "type": "boolean" },
125
+ "openingHoursEnabled": { "type": "boolean" },
126
+ "pickupEnabled": { "type": "boolean" },
127
+ "districtDeliveryEnabled": { "type": "boolean" },
128
+ "payOnDeliveryEnabled": { "type": "boolean" },
92
129
  "returnsEnabled": { "type": "boolean" }
93
130
  },
94
131
  "additionalProperties": false
@@ -0,0 +1,38 @@
1
+ import type { IComponent, IModule, IProject } from "../interfaces/project.interface";
2
+
3
+ export interface IFormEntity {
4
+ component: IComponent;
5
+ endpoint: string;
6
+ ownsEntity: boolean;
7
+ }
8
+
9
+ interface IEntitySource {
10
+ id: string;
11
+ componentType: string;
12
+ contracts?: { id?: string; endpoint?: string }[];
13
+ }
14
+
15
+ // Mesma regra do kebabfy do gerador: "payableAccount" e "PayableAccount" viram "payable-account".
16
+ const kebab = (text: string): string =>
17
+ text.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)?.map((part: string) => part.toLowerCase()).join("-") ||
18
+ text.toLowerCase();
19
+
20
+ export const normalizeEndpoint = (endpoint: string): string => endpoint.replace(/^\/+|\/+$/g, "");
21
+
22
+ // O backend gerado cria uma entidade por form ou kanban, pelo id do primeiro contrato (ou do componente).
23
+ // Quando dois componentes dão a mesma entidade, só o primeiro do projeto gera o backend.
24
+ export const formEntitiesOf = (project: IProject): IFormEntity[] => {
25
+ const seen = new Set<string>();
26
+ return (project.modules ?? []).flatMap((module: IModule): IFormEntity[] =>
27
+ module.components.flatMap((component: IComponent): IFormEntity[] => {
28
+ if (component.componentType !== "form" && component.componentType !== "kanban") return [];
29
+ const source = component as unknown as IEntitySource;
30
+ const contract = source.contracts?.[0];
31
+ const key: string = kebab(contract?.id || source.id || "Unnamed");
32
+ const ownsEntity: boolean = !seen.has(key);
33
+ seen.add(key);
34
+ if (component.componentType !== "form") return [];
35
+ return [{ component, endpoint: normalizeEndpoint(contract?.endpoint || key), ownsEntity }];
36
+ }),
37
+ );
38
+ };
@@ -29,9 +29,14 @@ describe("recordTimestamp", () => {
29
29
  expect(warnings).toEqual(["f: recordTimestamp em \"terms\" está dentro de um array; só vale no nível de cima do form, e o aceite não é registrado"]);
30
30
  });
31
31
 
32
- test("num segundo form do módulo avisa que o aceite não é registrado", () => {
33
- const warnings = checkFormReferences(projectWith([form("first", [input("name")]), form("second", [consent("terms")])]));
34
- expect(warnings).toEqual(["second: recordTimestamp em \"terms\" só vale no primeiro form do módulo; neste o aceite não é registrado"]);
32
+ test("num segundo form do módulo, com entidade própria, grava normalmente", () => {
33
+ expect(checkFormReferences(projectWith([form("first", [input("name")]), form("second", [consent("terms")])]))).toEqual([]);
34
+ });
35
+
36
+ test("num form que repete a entidade de um form anterior avisa que o aceite não é registrado", () => {
37
+ const contracts = [{ id: "people", endpoint: "/people", actions: ["create"] }];
38
+ const warnings = checkFormReferences(projectWith([{ ...form("first", [input("name")]), contracts }, { ...form("second", [consent("terms")]), contracts }]));
39
+ expect(warnings).toEqual(["second: recordTimestamp em \"terms\" não grava nada: o form usa a mesma entidade (contracts[0].id) de outro form anterior, e o backend vem daquele"]);
35
40
  });
36
41
 
37
42
  test("forms de perfil (pessoa e empresa) também gravam, e a colisão é conferida", () => {
@@ -1,5 +1,6 @@
1
1
  import type { IForm } from "../interfaces/form.interface";
2
- import type { IComponent, IModule, IProject } from "../interfaces/project.interface";
2
+ import type { IProject } from "../interfaces/project.interface";
3
+ import { formEntitiesOf, type IFormEntity } from "./entities";
3
4
  import { fieldScopes, type IFlatElement } from "./form-elements";
4
5
 
5
6
  const RESERVED_FIELDS: string[] = ["createdAt", "createdBy", "updatedAt", "updatedBy", "deletedAt", "workspaceId"];
@@ -20,7 +21,7 @@ const consentWarnings = (form: IFormToCheck, fields: IFlatElement[], isRoot: boo
20
21
  return switches.map((field: IFlatElement) => form.id + ": recordTimestamp em \"" + field.name + "\" está dentro de um array; só vale no nível de cima do form, e o aceite não é registrado");
21
22
  }
22
23
  if (!form.recordsConsent) {
23
- return switches.map((field: IFlatElement) => form.id + ": recordTimestamp em \"" + field.name + "\" só vale no primeiro form do módulo; neste o aceite não é registrado");
24
+ return switches.map((field: IFlatElement) => form.id + ": recordTimestamp em \"" + field.name + "\" não grava nada: o form usa a mesma entidade (contracts[0].id) de outro form anterior, e o backend vem daquele");
24
25
  }
25
26
  const names = new Set(fields.flatMap((field: IFlatElement): string[] => (field.name ? [backendName(field.name)] : [])));
26
27
  return switches.flatMap((field: IFlatElement): string[] =>
@@ -41,14 +42,14 @@ const formWarnings = (form: IFormToCheck): string[] =>
41
42
  ...consentWarnings(form, fields, index === 0),
42
43
  ]);
43
44
 
44
- // O backend gerado grava o consentimento só no primeiro form de cada módulo; os forms de perfil viram uma
45
- // collection só, então os dois gravam.
45
+ // Cada form gera a própria entidade e grava o consentimento, menos quando repete a entidade de um form
46
+ // anterior. Os forms de perfil viram uma collection só, então os dois gravam.
46
47
  const formsOf = (project: IProject): IFormToCheck[] => [
47
- ...(project.modules ?? []).flatMap((module: IModule): IFormToCheck[] =>
48
- module.components
49
- .filter((component: IComponent) => component.componentType === "form")
50
- .map((component: IComponent, index: number) => ({ id: component.id, elements: "elements" in component ? component.elements : undefined, recordsConsent: index === 0 })),
51
- ),
48
+ ...formEntitiesOf(project).map((entity: IFormEntity) => ({
49
+ id: entity.component.id,
50
+ elements: "elements" in entity.component ? entity.component.elements : undefined,
51
+ recordsConsent: entity.ownsEntity,
52
+ })),
52
53
  ...[project.flows?.profiles?.personProfile, project.flows?.profiles?.companyProfile]
53
54
  .filter((form: IForm | undefined): form is IForm => !!form)
54
55
  .map((form: IForm) => ({ id: form.id, elements: form.elements, recordsConsent: true })),
@@ -0,0 +1,49 @@
1
+ import type { IList, IListKpi } from "../interfaces/list.interface";
2
+ import type { IComponent } from "../interfaces/project.interface";
3
+ import { normalizeEndpoint, type IFormEntity } from "./entities";
4
+ import { fieldScopes, NUMERIC_DATA_TYPES, type IFlatElement } from "./form-elements";
5
+
6
+ export type TKpiFields = Map<string, IFlatElement>;
7
+
8
+ const topLevelFields = (components: IComponent[]): TKpiFields =>
9
+ new Map(
10
+ components
11
+ .flatMap((component: IComponent): IFlatElement[] => ("elements" in component ? fieldScopes(component.elements)[0] : []))
12
+ .flatMap((field: IFlatElement): [string, IFlatElement][] => (field.name ? [[field.name, field]] : [])),
13
+ );
14
+
15
+ // A rota de soma e a contagem são da entidade da lista (dataSource.endpoint): vale só o nível de cima do
16
+ // form dessa entidade. Sem form com esse endpoint, cai nos forms do módulo.
17
+ export const kpiFieldsOf = (list: IList, entities: IFormEntity[], moduleForms: IComponent[]): { fields: TKpiFields; source: string } => {
18
+ const endpoint: string = normalizeEndpoint(list.dataSource?.endpoint ?? "");
19
+ const entity: IFormEntity | undefined = entities.find((item: IFormEntity) => item.ownsEntity && item.endpoint === endpoint);
20
+ return entity
21
+ ? { fields: topLevelFields([entity.component]), source: "no form " + entity.component.id + " (entidade de /" + endpoint + ")" }
22
+ : { fields: topLevelFields(moduleForms), source: "no nível de cima de nenhum form do módulo" };
23
+ };
24
+
25
+ const sumOfWarnings = (list: IList, kpi: IListKpi, fields: TKpiFields, source: string): string[] => {
26
+ if (!kpi.sumOf) return [];
27
+ const field: IFlatElement | undefined = fields.get(kpi.sumOf);
28
+ if (!field) return [list.id + ": kpis.sumOf \"" + kpi.sumOf + "\" não existe " + source + " (campos de array não valem)"];
29
+ const isNumeric: boolean = NUMERIC_DATA_TYPES.includes((field.dataType ?? "").toLowerCase());
30
+ if (field.type !== "input" || !isNumeric) {
31
+ return [list.id + ": kpis.sumOf \"" + kpi.sumOf + "\" não é um input numérico; a rota de soma só soma inputs numéricos"];
32
+ }
33
+ return [];
34
+ };
35
+
36
+ export const kpiWarnings = (list: IList, fields: TKpiFields, source: string): string[] => {
37
+ const kpis: IListKpi[] = list.kpis ?? [];
38
+ const brand: string[] =
39
+ kpis.filter((kpi: IListKpi) => kpi.tone === "brand").length > 1 ? [list.id + ": mais de um KPI com tone \"brand\"; use no máximo um"] : [];
40
+ return [
41
+ ...brand,
42
+ ...kpis.flatMap((kpi: IListKpi): string[] => [
43
+ ...sumOfWarnings(list, kpi, fields, source),
44
+ ...(Array.isArray(kpi.filter) ? kpi.filter : [])
45
+ .filter((condition) => !fields.has(condition.field))
46
+ .map((condition) => list.id + ": kpis.filter cita o campo \"" + condition.field + "\", que não existe " + source + " (campos de array não valem)"),
47
+ ]),
48
+ ];
49
+ };
@@ -0,0 +1,103 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { IProject } from "../interfaces/project.interface";
3
+ import { checkListReferences } from "./list-references";
4
+
5
+ const input = (name: string, dataType: string = "text"): Record<string, unknown> => ({ type: "input", name, label: name, dataType });
6
+ const form = (id: string, endpoint: string, elements: unknown[]): Record<string, unknown> => ({
7
+ componentType: "form",
8
+ id,
9
+ elements,
10
+ contracts: [{ id, endpoint, actions: ["create"] }],
11
+ });
12
+ const list = (extra: Record<string, unknown>): Record<string, unknown> => ({
13
+ componentType: "list",
14
+ id: "billList",
15
+ dataSource: { endpoint: "/bills", paramType: "query" },
16
+ listItems: [],
17
+ ...extra,
18
+ });
19
+ const projectWith = (components: unknown[]): IProject => ({ id: "p", modules: [{ id: "m", components }] }) as unknown as IProject;
20
+
21
+ const billForm = form("bill", "/bills", [
22
+ input("amount", "currency"),
23
+ input("status"),
24
+ { type: "select", name: "qty", label: "qty", dataType: "number", options: [] },
25
+ { type: "array", name: "deps", label: "deps", elements: [input("price", "number")] },
26
+ ]);
27
+ const otherForm = form("other", "/others", [input("otherTotal", "currency")]);
28
+
29
+ describe("kpis", () => {
30
+ test("sumOf num input numérico do form da lista não avisa", () => {
31
+ expect(checkListReferences(projectWith([billForm, otherForm, list({ kpis: [{ label: "a", sumOf: "amount" }] })]))).toEqual([]);
32
+ });
33
+
34
+ test("sumOf de outro form do módulo avisa, porque a soma é da entidade da lista", () => {
35
+ const warnings = checkListReferences(projectWith([billForm, otherForm, list({ kpis: [{ label: "a", sumOf: "otherTotal" }] })]));
36
+ expect(warnings).toEqual(["billList: kpis.sumOf \"otherTotal\" não existe no form bill (entidade de /bills) (campos de array não valem)"]);
37
+ });
38
+
39
+ test("sumOf que não é input avisa, mesmo com dataType numérico", () => {
40
+ const warnings = checkListReferences(projectWith([billForm, list({ kpis: [{ label: "a", sumOf: "qty" }] })]));
41
+ expect(warnings).toEqual(["billList: kpis.sumOf \"qty\" não é um input numérico; a rota de soma só soma inputs numéricos"]);
42
+ });
43
+
44
+ test("sumOf de texto e campo de array avisam", () => {
45
+ const warnings = checkListReferences(projectWith([billForm, list({ kpis: [{ label: "a", sumOf: "status" }, { label: "b", sumOf: "price" }] })]));
46
+ expect(warnings).toEqual([
47
+ "billList: kpis.sumOf \"status\" não é um input numérico; a rota de soma só soma inputs numéricos",
48
+ "billList: kpis.sumOf \"price\" não existe no form bill (entidade de /bills) (campos de array não valem)",
49
+ ]);
50
+ });
51
+
52
+ test("filter só aceita campos do form da lista", () => {
53
+ const kpis = [{ label: "a", filter: [{ field: "status", op: "eq", value: "open" }, { field: "otherTotal", op: "gt", value: 0 }] }];
54
+ expect(checkListReferences(projectWith([billForm, otherForm, list({ kpis })]))).toEqual([
55
+ "billList: kpis.filter cita o campo \"otherTotal\", que não existe no form bill (entidade de /bills) (campos de array não valem)",
56
+ ]);
57
+ });
58
+
59
+ test("sem form com o endpoint da lista, confere contra os forms do módulo", () => {
60
+ const warnings = checkListReferences(projectWith([otherForm, list({ kpis: [{ label: "a", sumOf: "otherTotal" }, { label: "b", sumOf: "nope" }] })]));
61
+ expect(warnings).toEqual(["billList: kpis.sumOf \"nope\" não existe no nível de cima de nenhum form do módulo (campos de array não valem)"]);
62
+ });
63
+
64
+ test("mais de um brand avisa", () => {
65
+ const kpis = [{ label: "a", tone: "brand" }, { label: "b", tone: "brand" }];
66
+ expect(checkListReferences(projectWith([billForm, list({ kpis })]))).toEqual(["billList: mais de um KPI com tone \"brand\"; use no máximo um"]);
67
+ });
68
+ });
69
+
70
+ describe("columnGroup", () => {
71
+ const item = (property: string, columnGroup?: string): Record<string, unknown> => ({ property, label: property, dataType: "text", ...(columnGroup ? { columnGroup } : {}) });
72
+
73
+ test("grupos juntos e colunas sem grupo nas pontas não avisam", () => {
74
+ expect(checkListReferences(projectWith([billForm, list({ listItems: [item("a"), item("b", "Valores"), item("c", "Valores"), item("d")] })]))).toEqual([]);
75
+ });
76
+
77
+ test("grupo interrompido por outro grupo avisa", () => {
78
+ const listItems = [item("a", "Valores"), item("b", "Datas"), item("c", "Valores")];
79
+ expect(checkListReferences(projectWith([billForm, list({ listItems })]))).toEqual(["billList: o columnGroup \"Valores\" aparece separado; deixe as colunas do mesmo grupo juntas"]);
80
+ });
81
+
82
+ test("grupo interrompido por uma coluna sem grupo avisa", () => {
83
+ const listItems = [item("a", "Valores"), item("b"), item("c", "Valores")];
84
+ expect(checkListReferences(projectWith([billForm, list({ listItems })]))).toEqual(["billList: o columnGroup \"Valores\" aparece separado; deixe as colunas do mesmo grupo juntas"]);
85
+ });
86
+ });
87
+
88
+ describe("quickFilters, tabs e columnViews", () => {
89
+ test("nomes que não existem avisam", () => {
90
+ const warnings = checkListReferences(
91
+ projectWith([billForm, list({ quickFilters: ["status"], listFilters: [], tabs: { property: "nope" }, columnViews: [{ label: "v", columns: ["ghost"] }] })]),
92
+ );
93
+ expect(warnings).toEqual([
94
+ "billList: quickFilters cita \"status\", que não está em listFilters",
95
+ "billList: tabs.property \"nope\" não existe em nenhum form do módulo e tabs.options está vazio",
96
+ "billList: columnViews cita a coluna \"ghost\", que não está em listItems",
97
+ ]);
98
+ });
99
+
100
+ test("tabs.property aceita campo de dentro de array", () => {
101
+ expect(checkListReferences(projectWith([billForm, list({ tabs: { property: "price" } })]))).toEqual([]);
102
+ });
103
+ });
@@ -1,31 +1,17 @@
1
1
  import type { IList } from "../interfaces/list.interface";
2
2
  import type { IComponent, IModule, IProject } from "../interfaces/project.interface";
3
- import { allFields, fieldScopes, NUMERIC_DATA_TYPES, type IFlatElement } from "./form-elements";
3
+ import { formEntitiesOf, type IFormEntity } from "./entities";
4
+ import { allFields, type IFlatElement } from "./form-elements";
5
+ import { kpiFieldsOf, kpiWarnings } from "./list-kpi-references";
4
6
 
5
- interface IModuleFields {
6
- names: Set<string>;
7
- fields: Map<string, IFlatElement>;
8
- }
7
+ const NO_GROUP: string = "<sem grupo>";
9
8
 
10
9
  const namesOf = (elements: unknown[] | undefined): Set<string> =>
11
10
  new Set(allFields(elements).flatMap((field: IFlatElement): string[] => (field.name ? [field.name] : [])));
12
11
 
13
12
  const isList = (component: IComponent): component is IList => component.componentType === "list";
14
13
 
15
- const namedFields = (fields: IFlatElement[]): [string, IFlatElement][] =>
16
- fields.flatMap((field: IFlatElement): [string, IFlatElement][] => (field.name ? [[field.name, field]] : []));
17
-
18
- // names: todos os campos, inclusive de arrays (tabs.property). fields: só o nível de cima de cada form,
19
- // que é o que o registro tem e o que os KPIs conseguem contar e somar.
20
- const moduleFieldsOf = (module: IModule): IModuleFields => {
21
- const elementsOf = (component: IComponent): unknown[] | undefined =>
22
- component.componentType === "form" ? component.elements : undefined;
23
- const forms: IComponent[] = module.components.filter((component: IComponent) => component.componentType === "form");
24
- return {
25
- names: new Set(namedFields(forms.flatMap((form: IComponent) => allFields(elementsOf(form)))).map(([name]) => name)),
26
- fields: new Map(namedFields(forms.flatMap((form: IComponent) => fieldScopes(elementsOf(form))[0]))),
27
- };
28
- };
14
+ const isForm = (component: IComponent): boolean => component.componentType === "form";
29
15
 
30
16
  const columnViewWarnings = (list: IList): string[] => {
31
17
  const properties = new Set(list.listItems.map((item) => item.property).filter(Boolean));
@@ -36,64 +22,44 @@ const columnViewWarnings = (list: IList): string[] => {
36
22
  );
37
23
  };
38
24
 
25
+ // Compara cada coluna com a anterior, contando "sem grupo" como um grupo, para pegar também um grupo
26
+ // interrompido por uma coluna sem columnGroup.
39
27
  const columnGroupWarnings = (list: IList): string[] => {
40
- const groups: string[] = list.listItems.filter((item) => item.columnGroup).map((item) => JSON.stringify(item.columnGroup));
41
- const seen: string[] = [];
28
+ if (!list.listItems.some((item) => item.columnGroup)) return [];
29
+ const groups: string[] = list.listItems.map((item) => (item.columnGroup ? JSON.stringify(item.columnGroup) : NO_GROUP));
30
+ const closed = new Set<string>();
42
31
  const warnings: string[] = [];
43
32
  groups.forEach((group: string, index: number) => {
44
- if (index > 0 && group !== groups[index - 1] && seen.includes(group)) {
33
+ const previous: string | undefined = groups[index - 1];
34
+ if (previous !== undefined && previous !== group) closed.add(previous);
35
+ if (group !== NO_GROUP && group !== previous && closed.has(group)) {
45
36
  warnings.push(list.id + ": o columnGroup " + group + " aparece separado; deixe as colunas do mesmo grupo juntas");
46
37
  }
47
- if (!seen.includes(group)) seen.push(group);
48
38
  });
49
39
  return warnings;
50
40
  };
51
41
 
52
- const kpiWarnings = (list: IList, fields: Map<string, IFlatElement>): string[] => {
53
- const kpis = list.kpis ?? [];
54
- const warnings: string[] = [];
55
- if (kpis.filter((kpi) => kpi.tone === "brand").length > 1) {
56
- warnings.push(list.id + ": mais de um KPI com tone \"brand\"; use no máximo um");
57
- }
58
- for (const kpi of kpis) {
59
- if (kpi.sumOf) {
60
- const field = fields.get(kpi.sumOf);
61
- if (!field) warnings.push(list.id + ": kpis.sumOf \"" + kpi.sumOf + "\" não existe no nível de cima de nenhum form do módulo (campos de array não valem)");
62
- else if (!NUMERIC_DATA_TYPES.includes((field.dataType ?? "").toLowerCase())) {
63
- warnings.push(list.id + ": kpis.sumOf \"" + kpi.sumOf + "\" não é um campo numérico");
64
- }
65
- }
66
- for (const condition of Array.isArray(kpi.filter) ? kpi.filter : []) {
67
- if (!fields.has(condition.field)) {
68
- warnings.push(list.id + ": kpis.filter cita o campo \"" + condition.field + "\", que não existe no nível de cima de nenhum form do módulo (campos de array não valem)");
69
- }
70
- }
71
- }
72
- return warnings;
73
- };
74
-
75
- const listWarnings = (list: IList, moduleFields: IModuleFields): string[] => {
42
+ const listWarnings = (list: IList, module: IModule, entities: IFormEntity[]): string[] => {
76
43
  const warnings: string[] = [];
44
+ const moduleForms: IComponent[] = module.components.filter(isForm);
77
45
  const filterNames: Set<string> = namesOf(list.listFilters);
78
46
  for (const name of list.quickFilters ?? []) {
79
- if (!filterNames.has(name)) {
80
- warnings.push(list.id + ": quickFilters cita \"" + name + "\", que não está em listFilters");
81
- }
47
+ if (!filterNames.has(name)) warnings.push(list.id + ": quickFilters cita \"" + name + "\", que não está em listFilters");
82
48
  }
83
49
  const tabs = list.tabs;
84
- if (tabs && !tabs.options?.length && !moduleFields.names.has(tabs.property)) {
85
- warnings.push(
86
- list.id + ": tabs.property \"" + tabs.property + "\" não existe em nenhum form do módulo e tabs.options está vazio",
87
- );
50
+ const moduleNames = new Set<string>(moduleForms.flatMap((form: IComponent) => [...namesOf("elements" in form ? form.elements : undefined)]));
51
+ if (tabs && !tabs.options?.length && !moduleNames.has(tabs.property)) {
52
+ warnings.push(list.id + ": tabs.property \"" + tabs.property + "\" não existe em nenhum form do módulo e tabs.options está vazio");
88
53
  }
89
- return [...warnings, ...columnViewWarnings(list), ...columnGroupWarnings(list), ...kpiWarnings(list, moduleFields.fields)];
54
+ const { fields, source } = kpiFieldsOf(list, entities, moduleForms);
55
+ const kpis: string[] = list.kpis?.length ? kpiWarnings(list, fields, source) : [];
56
+ return [...warnings, ...columnViewWarnings(list), ...columnGroupWarnings(list), ...kpis];
90
57
  };
91
58
 
92
59
  // Nomes citados por texto (quickFilters, tabs.property, columnViews, kpis) que o schema não consegue conferir.
93
- export const checkListReferences = (project: IProject): string[] =>
94
- (project.modules ?? []).flatMap((module: IModule): string[] => {
95
- const lists: IList[] = module.components.filter(isList);
96
- if (lists.length === 0) return [];
97
- const moduleFields: IModuleFields = moduleFieldsOf(module);
98
- return lists.flatMap((list: IList) => listWarnings(list, moduleFields));
99
- });
60
+ export const checkListReferences = (project: IProject): string[] => {
61
+ const entities: IFormEntity[] = formEntitiesOf(project);
62
+ return (project.modules ?? []).flatMap((module: IModule): string[] =>
63
+ module.components.filter(isList).flatMap((list: IList) => listWarnings(list, module, entities)),
64
+ );
65
+ };
@@ -0,0 +1,24 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { IProject } from "../interfaces/project.interface";
3
+ import { checkStoreReferences } from "./store-references";
4
+
5
+ const projectWith = (skeleton: string, store?: Record<string, unknown>): IProject =>
6
+ ({ id: "p", title: "p", skeleton, ...(store ? { store } : {}) }) as unknown as IProject;
7
+
8
+ describe("store.segment", () => {
9
+ test("sem segmento não avisa", () => {
10
+ expect(checkStoreReferences(projectWith("ecommerce", { features: [] }))).toEqual([]);
11
+ expect(checkStoreReferences(projectWith("backoffice"))).toEqual([]);
12
+ });
13
+
14
+ test("em ecommerce e marketplace não avisa", () => {
15
+ expect(checkStoreReferences(projectWith("ecommerce", { segment: "food" }))).toEqual([]);
16
+ expect(checkStoreReferences(projectWith("marketplace", { segment: "events" }))).toEqual([]);
17
+ });
18
+
19
+ test("em skeleton sem venda própria avisa que é ignorado", () => {
20
+ expect(checkStoreReferences(projectWith("referralCommerce", { segment: "retail" }))).toEqual([
21
+ "store.segment \"retail\" só vale para skeleton \"ecommerce\" ou \"marketplace\"; com \"referralCommerce\" ele é ignorado",
22
+ ]);
23
+ });
24
+ });
@@ -0,0 +1,11 @@
1
+ import type { IProject } from "../interfaces/project.interface";
2
+
3
+ const SELLING_SKELETONS: string[] = ["ecommerce", "marketplace"];
4
+
5
+ export const checkStoreReferences = (project: IProject): string[] => {
6
+ const segment = project.store?.segment;
7
+ if (!segment || SELLING_SKELETONS.includes(project.skeleton)) return [];
8
+ return [
9
+ "store.segment \"" + segment + "\" só vale para skeleton \"ecommerce\" ou \"marketplace\"; com \"" + project.skeleton + "\" ele é ignorado",
10
+ ];
11
+ };
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { STORE_SEGMENT_DEFAULT_FEATURES, STORE_SEGMENT_DEFAULT_SETTINGS, storeFeaturesOf } from "./store-segment";
3
+
4
+ describe("storeFeaturesOf", () => {
5
+ test("sem store ou sem segmento e sem lista, nenhuma funcionalidade", () => {
6
+ expect(storeFeaturesOf(undefined)).toEqual([]);
7
+ expect(storeFeaturesOf({})).toEqual([]);
8
+ });
9
+
10
+ test("a lista do projeto sempre vale, mesmo vazia", () => {
11
+ expect(storeFeaturesOf({ segment: "food", features: ["blog"] })).toEqual(["blog"]);
12
+ expect(storeFeaturesOf({ segment: "events", features: [] })).toEqual([]);
13
+ });
14
+
15
+ test("sem lista, vale o padrão do segmento", () => {
16
+ expect(storeFeaturesOf({ segment: "food" })).toEqual(STORE_SEGMENT_DEFAULT_FEATURES.food);
17
+ expect(storeFeaturesOf({ segment: "events" })).toEqual(["stockAvailability", "installments", "coupons"]);
18
+ });
19
+
20
+ test("devolve uma cópia, sem alterar o padrão", () => {
21
+ storeFeaturesOf({ segment: "retail" }).push("blog");
22
+ expect(STORE_SEGMENT_DEFAULT_FEATURES.retail).not.toContain("blog");
23
+ });
24
+
25
+ test("blog nunca vem no padrão", () => {
26
+ for (const features of Object.values(STORE_SEGMENT_DEFAULT_FEATURES)) expect(features).not.toContain("blog");
27
+ });
28
+ });
29
+
30
+ describe("STORE_SEGMENT_DEFAULT_SETTINGS", () => {
31
+ test("retail mantém o catálogo de sempre", () => {
32
+ expect(STORE_SEGMENT_DEFAULT_SETTINGS.retail).toEqual({ catalogLayout: "grid", catalogColumns: 3, productImageAspect: "auto" });
33
+ });
34
+
35
+ test("food usa lista", () => {
36
+ expect(STORE_SEGMENT_DEFAULT_SETTINGS.food.catalogLayout).toBe("list");
37
+ });
38
+ });
@@ -0,0 +1,24 @@
1
+ import type { IProjectStore, IStoreSettings, TStoreFeature, TStoreSegment } from "../interfaces/store-settings.interface";
2
+
3
+ export const DEFAULT_STORE_SEGMENT: TStoreSegment = "retail";
4
+
5
+ export const STORE_SEGMENT_DEFAULT_FEATURES: Record<TStoreSegment, TStoreFeature[]> = {
6
+ retail: ["whatsappButton", "stockAvailability", "cashDiscount", "installments", "favorites", "shipping", "coupons", "reviews", "returns"],
7
+ food: ["whatsappButton", "favorites", "coupons", "reviews", "openingHours", "pickup", "districtDelivery", "payOnDelivery"],
8
+ services: ["whatsappButton", "stockAvailability", "installments", "coupons", "reviews"],
9
+ events: ["stockAvailability", "installments", "coupons"],
10
+ };
11
+
12
+ export const storeFeaturesOf = (store: IProjectStore | undefined): TStoreFeature[] => {
13
+ if (store?.features) return [...store.features];
14
+ return store?.segment ? [...STORE_SEGMENT_DEFAULT_FEATURES[store.segment]] : [];
15
+ };
16
+
17
+ export type TStoreSegmentSettings = Required<Pick<IStoreSettings, "catalogLayout" | "catalogColumns" | "productImageAspect">>;
18
+
19
+ export const STORE_SEGMENT_DEFAULT_SETTINGS: Record<TStoreSegment, TStoreSegmentSettings> = {
20
+ retail: { catalogLayout: "grid", catalogColumns: 3, productImageAspect: "auto" },
21
+ food: { catalogLayout: "list", catalogColumns: 3, productImageAspect: "square" },
22
+ services: { catalogLayout: "grid", catalogColumns: 3, productImageAspect: "landscape" },
23
+ events: { catalogLayout: "grid", catalogColumns: 3, productImageAspect: "landscape" },
24
+ };