rapida-partner 7.3.0 → 8.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 (41) hide show
  1. package/README.md +6 -0
  2. package/index.ts +2 -1
  3. package/package.json +1 -1
  4. package/src/interfaces/choice-display.interface.ts +4 -0
  5. package/src/interfaces/form-array.interface.ts +3 -0
  6. package/src/interfaces/form-checkbox.interface.ts +6 -0
  7. package/src/interfaces/form-datepicker.interface.ts +4 -0
  8. package/src/interfaces/form-file.interface.ts +1 -0
  9. package/src/interfaces/form-radio.interface.ts +4 -0
  10. package/src/interfaces/form-switch.interface.ts +6 -0
  11. package/src/interfaces/list.interface.ts +32 -1
  12. package/src/interfaces/project-backend.interface.ts +6 -6
  13. package/src/interfaces/store-blog-post.interface.ts +1 -1
  14. package/src/interfaces/store-coupon.interface.ts +2 -2
  15. package/src/interfaces/store-order.interface.ts +2 -2
  16. package/src/interfaces/store-return.interface.ts +1 -1
  17. package/src/interfaces/store-review.interface.ts +1 -1
  18. package/src/interfaces/store-settings.interface.ts +1 -1
  19. package/src/schemas/choice-display.ref.json +6 -0
  20. package/src/schemas/form-array.ref.json +3 -0
  21. package/src/schemas/form-checkbox.ref.json +6 -0
  22. package/src/schemas/form-datepicker.ref.json +3 -0
  23. package/src/schemas/form-radio.ref.json +6 -0
  24. package/src/schemas/form-switch.ref.json +3 -0
  25. package/src/schemas/list.ref.json +68 -0
  26. package/src/utils/form-elements.ts +48 -0
  27. package/src/utils/form-references.ts +34 -0
  28. package/src/utils/list-references.ts +73 -25
  29. package/src/modules/store-blog/store-blog.module.ts +0 -108
  30. package/src/modules/store-coupons/store-coupons.module.ts +0 -127
  31. package/src/modules/store-orders/store-order.elements.ts +0 -82
  32. package/src/modules/store-orders/store-orders.module.ts +0 -108
  33. package/src/modules/store-returns/store-return.elements.ts +0 -70
  34. package/src/modules/store-returns/store-returns.module.ts +0 -101
  35. package/src/modules/store-reviews/store-reviews.module.ts +0 -132
  36. package/src/modules/store-settings/contact-legal.elements.ts +0 -57
  37. package/src/modules/store-settings/features.elements.ts +0 -93
  38. package/src/modules/store-settings/identity-visual.elements.ts +0 -101
  39. package/src/modules/store-settings/pages-showcase.elements.ts +0 -100
  40. package/src/modules/store-settings/store-settings.module.ts +0 -80
  41. package/src/modules/store-settings/translations.ts +0 -7
@@ -1,51 +1,99 @@
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
4
 
4
- interface INamedNode {
5
- name?: string;
6
- elements?: unknown[];
7
- tabs?: { elements?: unknown[] }[];
5
+ interface IModuleFields {
6
+ names: Set<string>;
7
+ fields: Map<string, IFlatElement>;
8
8
  }
9
9
 
10
- const namesOf = (elements: unknown[] | undefined): string[] =>
11
- (elements ?? []).flatMap((element: unknown): string[] => {
12
- const node = (element ?? {}) as INamedNode;
13
- return [
14
- ...(node.name ? [node.name] : []),
15
- ...namesOf(node.elements),
16
- ...namesOf((node.tabs ?? []).flatMap((tab) => tab.elements ?? [])),
17
- ];
18
- });
10
+ const namesOf = (elements: unknown[] | undefined): Set<string> =>
11
+ new Set(allFields(elements).flatMap((field: IFlatElement): string[] => (field.name ? [field.name] : [])));
19
12
 
20
13
  const isList = (component: IComponent): component is IList => component.componentType === "list";
21
14
 
22
- const formNamesOf = (module: IModule): Set<string> =>
23
- new Set(
24
- module.components.flatMap((component: IComponent): string[] =>
25
- component.componentType === "form" ? namesOf(component.elements) : [],
26
- ),
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
+ };
29
+
30
+ const columnViewWarnings = (list: IList): string[] => {
31
+ const properties = new Set(list.listItems.map((item) => item.property).filter(Boolean));
32
+ return (list.columnViews ?? []).flatMap((view) =>
33
+ view.columns
34
+ .filter((column: string) => !properties.has(column))
35
+ .map((column: string) => list.id + ": columnViews cita a coluna \"" + column + "\", que não está em listItems"),
27
36
  );
37
+ };
38
+
39
+ 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[] = [];
42
+ const warnings: string[] = [];
43
+ groups.forEach((group: string, index: number) => {
44
+ if (index > 0 && group !== groups[index - 1] && seen.includes(group)) {
45
+ warnings.push(list.id + ": o columnGroup " + group + " aparece separado; deixe as colunas do mesmo grupo juntas");
46
+ }
47
+ if (!seen.includes(group)) seen.push(group);
48
+ });
49
+ return warnings;
50
+ };
51
+
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
+ };
28
74
 
29
- const listWarnings = (list: IList, formNames: Set<string>): string[] => {
75
+ const listWarnings = (list: IList, moduleFields: IModuleFields): string[] => {
30
76
  const warnings: string[] = [];
31
- const filterNames = new Set(namesOf(list.listFilters));
77
+ const filterNames: Set<string> = namesOf(list.listFilters);
32
78
  for (const name of list.quickFilters ?? []) {
33
79
  if (!filterNames.has(name)) {
34
80
  warnings.push(list.id + ": quickFilters cita \"" + name + "\", que não está em listFilters");
35
81
  }
36
82
  }
37
83
  const tabs = list.tabs;
38
- if (tabs && !tabs.options?.length && !formNames.has(tabs.property)) {
84
+ if (tabs && !tabs.options?.length && !moduleFields.names.has(tabs.property)) {
39
85
  warnings.push(
40
86
  list.id + ": tabs.property \"" + tabs.property + "\" não existe em nenhum form do módulo e tabs.options está vazio",
41
87
  );
42
88
  }
43
- return warnings;
89
+ return [...warnings, ...columnViewWarnings(list), ...columnGroupWarnings(list), ...kpiWarnings(list, moduleFields.fields)];
44
90
  };
45
91
 
46
- // Nomes citados por texto (quickFilters e tabs.property) que o schema não consegue conferir.
92
+ // Nomes citados por texto (quickFilters, tabs.property, columnViews, kpis) que o schema não consegue conferir.
47
93
  export const checkListReferences = (project: IProject): string[] =>
48
94
  (project.modules ?? []).flatMap((module: IModule): string[] => {
49
- const formNames = formNamesOf(module);
50
- return module.components.filter(isList).flatMap((list: IList) => listWarnings(list, formNames));
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));
51
99
  });
@@ -1,108 +0,0 @@
1
- import { EDataType } from "../../enums/form.enum";
2
- import type { IPublicContract } from "../../interfaces/form-contract.interface";
3
- import type { IForm, IFormElement } from "../../interfaces/form.interface";
4
- import type { IList } from "../../interfaces/list.interface";
5
- import type { IModule } from "../../interfaces/project.interface";
6
- import { tr } from "../store-settings/translations";
7
-
8
- export const STORE_BLOG_POSTS_ENDPOINT = "/store-blog-posts";
9
-
10
- export interface IStoreBlogModuleOptions {
11
- publicAccess?: IPublicContract["access"];
12
- allowedOrigins?: string[];
13
- }
14
-
15
- const ENTITY = "storeBlogPosts";
16
-
17
- const postElements: IFormElement[] = [
18
- { type: "input", name: "title", dataType: EDataType.TEXT, label: tr("Título", "Title", "Título"), isRequired: true, space: 2 },
19
- {
20
- type: "input",
21
- name: "slug",
22
- dataType: EDataType.TEXT,
23
- label: tr("Nome na URL", "URL name", "Nombre en la URL"),
24
- tooltip: tr("Letras minúsculas, números e hífen (ex.: como-guardar-blu-ray)", "Lowercase letters, numbers and hyphens (e.g. how-to-store-blu-ray)", "Letras minúsculas, números y guion (ej.: como-guardar-blu-ray)"),
25
- isRequired: true,
26
- isUnique: true,
27
- space: 2,
28
- },
29
- { type: "input", name: "excerpt", dataType: EDataType.TEXT, label: tr("Resumo", "Excerpt", "Resumen") },
30
- {
31
- type: "file",
32
- name: "coverImage",
33
- dataType: EDataType.TEXT,
34
- label: tr("Imagem de capa", "Cover image", "Imagen de portada"),
35
- validators: ["onlyImages"],
36
- storageConfig: { path: "store-blog-posts", fileNameStrategy: "uuid", visibility: "public" },
37
- },
38
- {
39
- type: "input",
40
- name: "content",
41
- dataType: EDataType.WYSIWYG,
42
- label: tr("Conteúdo", "Content", "Contenido"),
43
- isRequired: true,
44
- storageConfig: { path: "store-blog-posts", fileNameStrategy: "uuid", visibility: "public" },
45
- },
46
- { type: "datepicker", name: "publishedAt", label: tr("Publicar em", "Publish on", "Publicar el") },
47
- { type: "switch", name: "isPublished", label: tr("Publicado", "Published", "Publicado") },
48
- ];
49
-
50
- export const getStoreBlogPostForm = (options: IStoreBlogModuleOptions = {}): IForm => ({
51
- componentType: "form",
52
- id: "storeBlogPostForm",
53
- title: tr("Artigo do blog", "Blog post", "Artículo del blog"),
54
- icon: "newspaper",
55
- guards: "isAuthorized",
56
- elements: postElements,
57
- contracts: [
58
- {
59
- id: ENTITY,
60
- endpoint: STORE_BLOG_POSTS_ENDPOINT,
61
- actions: ["create", "get", "getById", "update", "softDelete"],
62
- request: { entity: ENTITY, fields: [] },
63
- },
64
- ],
65
- publicContracts: [
66
- {
67
- id: "storeBlogPostsFromStore",
68
- endpoint: STORE_BLOG_POSTS_ENDPOINT,
69
- actions: ["get", "getById"],
70
- access: options.publicAccess ?? "trustedCallers",
71
- ...(options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}),
72
- request: { entity: ENTITY, fields: [] },
73
- },
74
- ],
75
- });
76
-
77
- export const getStoreBlogPostList = (): IList => ({
78
- componentType: "list",
79
- id: "storeBlogPostList",
80
- title: tr("Blog", "Blog", "Blog"),
81
- guards: ["isAuthorized"],
82
- dataSource: { endpoint: STORE_BLOG_POSTS_ENDPOINT, paramType: "query", hasAuthentication: true },
83
- listItems: [
84
- { property: "title", type: "title", label: tr("Título", "Title", "Título"), dataType: EDataType.TEXT },
85
- { property: "excerpt", type: "subtitle", label: tr("Resumo", "Excerpt", "Resumen"), dataType: EDataType.TEXT },
86
- { property: "publishedAt", label: tr("Publicar em", "Publish on", "Publicar el"), dataType: EDataType.DATE },
87
- ],
88
- contracts: [
89
- {
90
- id: ENTITY,
91
- endpoint: STORE_BLOG_POSTS_ENDPOINT,
92
- actions: ["get", "getById", "update", "softDelete"],
93
- request: { entity: ENTITY, fields: [] },
94
- },
95
- ],
96
- });
97
-
98
- /**
99
- * Módulo pronto "Blog", para o Backoffice do vendedor (funcionalidade
100
- * "blog"). A loja lista os artigos publicados por IMarketplace.blogPostsEndpoint
101
- * (STORE_BLOG_POSTS_ENDPOINT).
102
- */
103
- export const getStoreBlogModule = (options: IStoreBlogModuleOptions = {}): IModule => ({
104
- id: "storeBlogModule",
105
- title: tr("Blog", "Blog", "Blog"),
106
- icon: "newspaper",
107
- components: [getStoreBlogPostList(), getStoreBlogPostForm(options)],
108
- });
@@ -1,127 +0,0 @@
1
- import { EDataType } from "../../enums/form.enum";
2
- import type { IPublicContract } from "../../interfaces/form-contract.interface";
3
- import type { IForm, IFormElement } from "../../interfaces/form.interface";
4
- import type { IList } from "../../interfaces/list.interface";
5
- import type { IModule } from "../../interfaces/project.interface";
6
- import type { TStoreCouponDiscountType } from "../../interfaces/store-coupon.interface";
7
- import { tr } from "../store-settings/translations";
8
-
9
- export const STORE_COUPONS_ENDPOINT = "/store-coupons";
10
-
11
- export interface IStoreCouponsModuleOptions {
12
- // Quem lê os cupons sem login. "trustedCallers" (padrão): só o backend da
13
- // loja, com o token de serviço de IMarketplace.sellerServiceAuth.
14
- publicAccess?: IPublicContract["access"];
15
- allowedOrigins?: string[];
16
- }
17
-
18
- const ENTITY = "storeCoupons";
19
-
20
- const DISCOUNT_TYPE_LABELS: Record<TStoreCouponDiscountType, ReturnType<typeof tr>> = {
21
- percentage: tr("Percentual (%)", "Percentage (%)", "Porcentaje (%)"),
22
- value: tr("Valor fixo", "Fixed amount", "Monto fijo"),
23
- };
24
-
25
- const couponElements: IFormElement[] = [
26
- {
27
- type: "input",
28
- name: "code",
29
- dataType: EDataType.TEXT,
30
- label: tr("Código", "Code", "Código"),
31
- tooltip: tr("O que o cliente digita no carrinho (ex.: BEMVINDO10)", "What the customer types in the cart (e.g. WELCOME10)", "Lo que el cliente escribe en el carrito (ej.: BIENVENIDO10)"),
32
- isRequired: true,
33
- isUnique: true,
34
- space: 2,
35
- },
36
- { type: "input", name: "description", dataType: EDataType.TEXT, label: tr("Descrição", "Description", "Descripción"), space: 2 },
37
- {
38
- type: "select",
39
- name: "discountType",
40
- dataType: EDataType.TEXT,
41
- label: tr("Tipo de desconto", "Discount type", "Tipo de descuento"),
42
- isRequired: true,
43
- options: (Object.keys(DISCOUNT_TYPE_LABELS) as TStoreCouponDiscountType[]).map((value) => ({
44
- label: DISCOUNT_TYPE_LABELS[value],
45
- value,
46
- isSelected: value === "percentage",
47
- })),
48
- space: 2,
49
- },
50
- { type: "input", name: "discountValue", dataType: EDataType.NUMBER, label: tr("Desconto", "Discount", "Descuento"), isRequired: true, space: 2 },
51
- { type: "input", name: "minimumSubtotal", dataType: EDataType.CURRENCY, label: tr("Pedido mínimo", "Minimum order", "Pedido mínimo"), space: 2 },
52
- { type: "datepicker", name: "startDate", label: tr("Válido a partir de", "Valid from", "Válido desde") },
53
- { type: "datepicker", name: "endDate", label: tr("Válido até", "Valid until", "Válido hasta") },
54
- { type: "input", name: "usageLimit", dataType: EDataType.INTEGER, label: tr("Limite de usos", "Usage limit", "Límite de usos"), space: 2 },
55
- {
56
- type: "input",
57
- name: "usageLimitPerCustomer",
58
- dataType: EDataType.INTEGER,
59
- label: tr("Limite por cliente", "Limit per customer", "Límite por cliente"),
60
- space: 2,
61
- },
62
- { type: "switch", name: "isActive", label: tr("Ativo", "Active", "Activo") },
63
- ];
64
-
65
- // Um código por workspace; fica no contrato interno, de onde o gerador cria o índice único.
66
- const UNIQUE_CODE = [{ identificator: "storeCouponCodePerWorkspace", fields: ["code"] }];
67
-
68
- export const getStoreCouponForm = (options: IStoreCouponsModuleOptions = {}): IForm => ({
69
- componentType: "form",
70
- id: "storeCouponForm",
71
- title: tr("Cupom", "Coupon", "Cupón"),
72
- icon: "ticket-percent",
73
- guards: "isAuthorized",
74
- elements: couponElements,
75
- contracts: [
76
- {
77
- id: ENTITY,
78
- endpoint: STORE_COUPONS_ENDPOINT,
79
- actions: ["create", "get", "getById", "update", "softDelete"],
80
- request: { entity: ENTITY, fields: [], uniqueConstraints: UNIQUE_CODE },
81
- },
82
- ],
83
- publicContracts: [
84
- {
85
- id: "storeCouponsFromStore",
86
- endpoint: STORE_COUPONS_ENDPOINT,
87
- actions: ["get"],
88
- access: options.publicAccess ?? "trustedCallers",
89
- ...(options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}),
90
- request: { entity: ENTITY, fields: [] },
91
- },
92
- ],
93
- });
94
-
95
- export const getStoreCouponList = (): IList => ({
96
- componentType: "list",
97
- id: "storeCouponList",
98
- title: tr("Cupons", "Coupons", "Cupones"),
99
- guards: ["isAuthorized"],
100
- dataSource: { endpoint: STORE_COUPONS_ENDPOINT, paramType: "query", hasAuthentication: true },
101
- listItems: [
102
- { property: "code", type: "title", label: tr("Código", "Code", "Código"), dataType: EDataType.TEXT },
103
- { property: "description", type: "subtitle", label: tr("Descrição", "Description", "Descripción"), dataType: EDataType.TEXT },
104
- { property: "discountValue", type: "description", label: tr("Desconto", "Discount", "Descuento"), dataType: EDataType.NUMBER },
105
- { property: "endDate", label: tr("Válido até", "Valid until", "Válido hasta"), dataType: EDataType.DATE },
106
- ],
107
- contracts: [
108
- {
109
- id: ENTITY,
110
- endpoint: STORE_COUPONS_ENDPOINT,
111
- actions: ["get", "getById", "update", "softDelete"],
112
- request: { entity: ENTITY, fields: [] },
113
- },
114
- ],
115
- });
116
-
117
- /**
118
- * Módulo pronto "Cupons", para o Backoffice do vendedor (funcionalidade
119
- * "coupons"). A loja lê os cupons por IMarketplace.couponsEndpoint
120
- * (STORE_COUPONS_ENDPOINT), valida o código e desconta no servidor.
121
- */
122
- export const getStoreCouponsModule = (options: IStoreCouponsModuleOptions = {}): IModule => ({
123
- id: "storeCouponsModule",
124
- title: tr("Cupons", "Coupons", "Cupones"),
125
- icon: "ticket-percent",
126
- components: [getStoreCouponList(), getStoreCouponForm(options)],
127
- });
@@ -1,82 +0,0 @@
1
- import { EDataType } from "../../enums/form.enum";
2
- import type { IFormElement } from "../../interfaces/form.interface";
3
- import type { TStoreOrderFulfillmentStatus } from "../../interfaces/store-order.interface";
4
- import { tr } from "../store-settings/translations";
5
-
6
- type TLabel = ReturnType<typeof tr>;
7
-
8
- const text = (name: string, label: TLabel, extra: Partial<{ isRequired: boolean; isDisabled: boolean }> = {}): IFormElement => ({
9
- type: "input",
10
- name,
11
- dataType: EDataType.TEXT,
12
- label,
13
- ...extra,
14
- });
15
-
16
- const money = (name: string, label: TLabel): IFormElement => ({
17
- type: "input",
18
- name,
19
- dataType: EDataType.CURRENCY,
20
- label,
21
- isDisabled: true,
22
- });
23
-
24
- export const STORE_ORDER_STATUS_LABELS: Record<TStoreOrderFulfillmentStatus, TLabel> = {
25
- received: tr("Recebido", "Received", "Recibido"),
26
- preparing: tr("Em separação", "Preparing", "En preparación"),
27
- shipped: tr("Enviado", "Shipped", "Enviado"),
28
- delivered: tr("Entregue", "Delivered", "Entregado"),
29
- cancelled: tr("Cancelado", "Cancelled", "Cancelado"),
30
- };
31
-
32
- export const fulfillmentElements: IFormElement[] = [
33
- {
34
- type: "select",
35
- name: "status",
36
- dataType: EDataType.TEXT,
37
- label: tr("Andamento", "Status", "Estado"),
38
- isRequired: true,
39
- options: (Object.keys(STORE_ORDER_STATUS_LABELS) as TStoreOrderFulfillmentStatus[]).map((status) => ({
40
- label: STORE_ORDER_STATUS_LABELS[status],
41
- value: status,
42
- isSelected: status === "received",
43
- })),
44
- },
45
- text("trackingCode", tr("Código de rastreio", "Tracking code", "Código de seguimiento")),
46
- text("trackingUrl", tr("Link de rastreio", "Tracking link", "Enlace de seguimiento")),
47
- text("notes", tr("Observações", "Notes", "Observaciones")),
48
- ];
49
-
50
- export const orderElements: IFormElement[] = [
51
- text("storeOrderId", tr("Pedido na loja", "Store order", "Pedido en la tienda"), { isRequired: true, isDisabled: true }),
52
- text("storeName", tr("Loja", "Store", "Tienda"), { isDisabled: true }),
53
- text("customerName", tr("Cliente", "Customer", "Cliente"), { isDisabled: true }),
54
- text("customerEmail", tr("E-mail do cliente", "Customer e-mail", "Correo del cliente"), { isDisabled: true }),
55
- {
56
- type: "array",
57
- name: "items",
58
- label: tr("Itens", "Items", "Artículos"),
59
- elements: [
60
- text("productId", tr("Produto (id)", "Product (id)", "Producto (id)"), { isRequired: true, isDisabled: true }),
61
- text("name", tr("Produto", "Product", "Producto"), { isRequired: true, isDisabled: true }),
62
- { type: "input", name: "quantity", dataType: EDataType.INTEGER, label: tr("Quantidade", "Quantity", "Cantidad"), isRequired: true, isDisabled: true },
63
- money("unitPrice", tr("Preço unitário", "Unit price", "Precio unitario")),
64
- ],
65
- },
66
- money("subtotal", tr("Subtotal", "Subtotal", "Subtotal")),
67
- money("discount", tr("Desconto", "Discount", "Descuento")),
68
- money("shipping", tr("Frete", "Shipping", "Envío")),
69
- money("total", tr("Total", "Total", "Total")),
70
- text("currency", tr("Moeda", "Currency", "Moneda"), { isDisabled: true }),
71
- ];
72
-
73
- export const addressElements: IFormElement[] = [
74
- text("addressZipCode", tr("CEP", "ZIP code", "Código postal"), { isDisabled: true }),
75
- text("addressStreet", tr("Logradouro", "Street", "Calle"), { isDisabled: true }),
76
- text("addressNumber", tr("Número", "Number", "Número"), { isDisabled: true }),
77
- text("addressComplement", tr("Complemento", "Complement", "Complemento"), { isDisabled: true }),
78
- text("addressDistrict", tr("Bairro", "District", "Barrio"), { isDisabled: true }),
79
- text("addressCity", tr("Cidade", "City", "Ciudad"), { isDisabled: true }),
80
- text("addressState", tr("Estado", "State", "Estado"), { isDisabled: true }),
81
- text("addressCountry", tr("País", "Country", "País"), { isDisabled: true }),
82
- ];
@@ -1,108 +0,0 @@
1
- import { EDataType } from "../../enums/form.enum";
2
- import type { IPublicContract } from "../../interfaces/form-contract.interface";
3
- import type { IForm } from "../../interfaces/form.interface";
4
- import type { IList } from "../../interfaces/list.interface";
5
- import type { IModule } from "../../interfaces/project.interface";
6
- import { tr } from "../store-settings/translations";
7
- import { STORE_ORDER_STATUS_LABELS, addressElements, fulfillmentElements, orderElements } from "./store-order.elements";
8
-
9
- export const STORE_ORDERS_ENDPOINT = "/store-orders";
10
-
11
- export interface IStoreOrdersModuleOptions {
12
- // Quem cria e lê os pedidos sem login. "trustedCallers" (padrão): só o
13
- // backend da loja, com o token de serviço de IMarketplace.sellerServiceAuth.
14
- publicAccess?: IPublicContract["access"];
15
- allowedOrigins?: string[];
16
- }
17
-
18
- const ENTITY = "storeOrders";
19
-
20
- // Um pedido por storeOrderId em cada workspace. Fica no contrato interno do
21
- // form, de onde o gerador cria o índice único, e não no público: o reenvio do
22
- // mesmo pedido pela loja é recusado em vez de duplicar.
23
- const UNIQUE_STORE_ORDER = [{ identificator: "storeOrderIdPerWorkspace", fields: ["storeOrderId"] }];
24
-
25
- export const getStoreOrderForm = (options: IStoreOrdersModuleOptions = {}): IForm => ({
26
- componentType: "form",
27
- id: "storeOrderForm",
28
- title: tr("Pedido da loja", "Store order", "Pedido de la tienda"),
29
- icon: "truck",
30
- guards: "isAuthorized",
31
- elements: [
32
- {
33
- type: "tab",
34
- id: "storeOrderTabs",
35
- tabs: [
36
- { id: "fulfillment", title: tr("Entrega", "Fulfillment", "Entrega"), elements: fulfillmentElements },
37
- { id: "order", title: tr("Pedido", "Order", "Pedido"), elements: orderElements },
38
- { id: "address", title: tr("Endereço", "Address", "Dirección"), elements: addressElements },
39
- ],
40
- },
41
- ],
42
- contracts: [
43
- {
44
- id: ENTITY,
45
- endpoint: STORE_ORDERS_ENDPOINT,
46
- actions: ["get", "getById", "update"],
47
- request: { entity: ENTITY, fields: [], uniqueConstraints: UNIQUE_STORE_ORDER },
48
- },
49
- ],
50
- publicContracts: [
51
- {
52
- id: "storeOrdersFromStore",
53
- endpoint: STORE_ORDERS_ENDPOINT,
54
- actions: ["create", "get", "update"],
55
- access: options.publicAccess ?? "trustedCallers",
56
- ...(options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}),
57
- request: { entity: ENTITY, fields: [] },
58
- },
59
- ],
60
- });
61
-
62
- export const getStoreOrderList = (): IList => ({
63
- componentType: "list",
64
- id: "storeOrderList",
65
- title: tr("Pedidos da loja", "Store orders", "Pedidos de la tienda"),
66
- guards: ["isAuthorized"],
67
- dataSource: { endpoint: STORE_ORDERS_ENDPOINT, paramType: "query", hasAuthentication: true },
68
- listItems: [
69
- { property: "storeOrderId", type: "title", label: tr("Pedido", "Order", "Pedido"), dataType: EDataType.TEXT },
70
- { property: "customerName", type: "subtitle", label: tr("Cliente", "Customer", "Cliente"), dataType: EDataType.TEXT },
71
- { property: "total", type: "description", label: tr("Total", "Total", "Total"), dataType: EDataType.CURRENCY },
72
- { property: "status", type: "badge", label: tr("Andamento", "Status", "Estado"), dataType: EDataType.TEXT },
73
- { property: "createdAt", label: tr("Recebido em", "Received at", "Recibido el"), dataType: EDataType.DATE, isTimestamp: true },
74
- ],
75
- listFilters: [
76
- {
77
- type: "select",
78
- name: "status",
79
- dataType: EDataType.TEXT,
80
- label: tr("Andamento", "Status", "Estado"),
81
- options: (Object.keys(STORE_ORDER_STATUS_LABELS) as (keyof typeof STORE_ORDER_STATUS_LABELS)[]).map((status) => ({
82
- label: STORE_ORDER_STATUS_LABELS[status],
83
- value: status,
84
- })),
85
- },
86
- ],
87
- contracts: [
88
- {
89
- id: ENTITY,
90
- endpoint: STORE_ORDERS_ENDPOINT,
91
- actions: ["get", "getById", "update"],
92
- request: { entity: ENTITY, fields: [] },
93
- },
94
- ],
95
- });
96
-
97
- /**
98
- * Módulo pronto "Pedidos da loja", para o Backoffice do vendedor. A loja cria
99
- * aqui cada pedido aprovado (IStoreOrder) por IMarketplace.storeOrdersEndpoint
100
- * (STORE_ORDERS_ENDPOINT) e lê o andamento da entrega; o vendedor atualiza
101
- * status e rastreio.
102
- */
103
- export const getStoreOrdersModule = (options: IStoreOrdersModuleOptions = {}): IModule => ({
104
- id: "storeOrdersModule",
105
- title: tr("Pedidos da loja", "Store orders", "Pedidos de la tienda"),
106
- icon: "truck",
107
- components: [getStoreOrderList(), getStoreOrderForm(options)],
108
- });
@@ -1,70 +0,0 @@
1
- import { EDataType } from "../../enums/form.enum";
2
- import type { IFormElement } from "../../interfaces/form.interface";
3
- import type { TStoreReturnReason, TStoreReturnStatus, TStoreReturnType } from "../../interfaces/store-return.interface";
4
- import { tr } from "../store-settings/translations";
5
-
6
- type TLabel = ReturnType<typeof tr>;
7
-
8
- const readOnly = (name: string, label: TLabel, dataType: EDataType.TEXT | EDataType.INTEGER = EDataType.TEXT): IFormElement => ({
9
- type: "input",
10
- name,
11
- dataType,
12
- label,
13
- isDisabled: true,
14
- });
15
-
16
- const options = <T extends string>(labels: Record<T, TLabel>, selected?: T) =>
17
- (Object.keys(labels) as T[]).map((value: T) => ({ label: labels[value], value, ...(value === selected ? { isSelected: true } : {}) }));
18
-
19
- export const STORE_RETURN_STATUS_LABELS: Record<TStoreReturnStatus, TLabel> = {
20
- requested: tr("Solicitado", "Requested", "Solicitado"),
21
- approved: tr("Aprovado", "Approved", "Aprobado"),
22
- rejected: tr("Recusado", "Rejected", "Rechazado"),
23
- received: tr("Produto recebido", "Item received", "Producto recibido"),
24
- completed: tr("Concluído", "Completed", "Concluido"),
25
- };
26
-
27
- export const STORE_RETURN_TYPE_LABELS: Record<TStoreReturnType, TLabel> = {
28
- return: tr("Devolução", "Return", "Devolución"),
29
- exchange: tr("Troca", "Exchange", "Cambio"),
30
- };
31
-
32
- export const STORE_RETURN_REASON_LABELS: Record<TStoreReturnReason, TLabel> = {
33
- defect: tr("Produto com defeito", "Defective item", "Producto defectuoso"),
34
- wrongItem: tr("Produto errado", "Wrong item", "Producto equivocado"),
35
- notAsDescribed: tr("Diferente do anunciado", "Not as described", "Distinto de lo anunciado"),
36
- regret: tr("Desistência", "Changed my mind", "Desistimiento"),
37
- other: tr("Outro", "Other", "Otro"),
38
- };
39
-
40
- export const resolutionElements: IFormElement[] = [
41
- {
42
- type: "select",
43
- name: "status",
44
- dataType: EDataType.TEXT,
45
- label: tr("Andamento", "Status", "Estado"),
46
- isRequired: true,
47
- options: options(STORE_RETURN_STATUS_LABELS, "requested"),
48
- },
49
- { type: "input", name: "resolutionNotes", dataType: EDataType.TEXT, label: tr("Resposta ao cliente", "Reply to the customer", "Respuesta al cliente") },
50
- { type: "input", name: "returnTrackingCode", dataType: EDataType.TEXT, label: tr("Código de postagem", "Return tracking code", "Código de envío") },
51
- ];
52
-
53
- export const requestElements: IFormElement[] = [
54
- readOnly("storeOrderId", tr("Pedido na loja", "Store order", "Pedido en la tienda")),
55
- { type: "select", name: "type", dataType: EDataType.TEXT, label: tr("Tipo", "Type", "Tipo"), isRequired: true, isDisabled: true, options: options(STORE_RETURN_TYPE_LABELS) },
56
- { type: "select", name: "reason", dataType: EDataType.TEXT, label: tr("Motivo", "Reason", "Motivo"), isRequired: true, isDisabled: true, options: options(STORE_RETURN_REASON_LABELS) },
57
- readOnly("comment", tr("Comentário do cliente", "Customer comment", "Comentario del cliente")),
58
- readOnly("customerName", tr("Cliente", "Customer", "Cliente")),
59
- readOnly("customerEmail", tr("E-mail do cliente", "Customer e-mail", "Correo del cliente")),
60
- {
61
- type: "array",
62
- name: "items",
63
- label: tr("Itens", "Items", "Artículos"),
64
- elements: [
65
- readOnly("productId", tr("Produto (id)", "Product (id)", "Producto (id)")),
66
- readOnly("name", tr("Produto", "Product", "Producto")),
67
- readOnly("quantity", tr("Quantidade", "Quantity", "Cantidad"), EDataType.INTEGER),
68
- ],
69
- },
70
- ];