create-mercato-app 0.6.6-develop.6381.1.042df302c3 → 0.6.6-develop.6383.1.27fcc83455
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/agentic/guides/module-system.md +130 -0
- package/agentic/shared/AGENTS.md.template +4 -12
- package/dist/agentic/guides/core.auth.md +2 -100
- package/dist/agentic/guides/core.catalog.md +2 -78
- package/dist/agentic/guides/core.currencies.md +2 -42
- package/dist/agentic/guides/core.customer_accounts.md +2 -128
- package/dist/agentic/guides/core.customers.md +2 -137
- package/dist/agentic/guides/core.data_sync.md +2 -106
- package/dist/agentic/guides/core.integrations.md +2 -112
- package/dist/agentic/guides/core.md +3 -38
- package/dist/agentic/guides/core.sales.md +2 -103
- package/dist/agentic/guides/core.workflows.md +2 -151
- package/dist/agentic/guides/module-facts.json +2073 -0
- package/dist/agentic/guides/module-system.md +130 -0
- package/dist/agentic/guides/modules/auth.md +64 -0
- package/dist/agentic/guides/modules/catalog.md +70 -0
- package/dist/agentic/guides/modules/currencies.md +50 -0
- package/dist/agentic/guides/modules/customer_accounts.md +76 -0
- package/dist/agentic/guides/modules/customers.md +115 -0
- package/dist/agentic/guides/modules/data_sync.md +49 -0
- package/dist/agentic/guides/modules/integrations.md +49 -0
- package/dist/agentic/guides/modules/sales.md +109 -0
- package/dist/agentic/guides/modules/workflows.md +73 -0
- package/dist/agentic/shared/AGENTS.md.template +4 -12
- package/dist/index.js +88 -2
- package/package.json +5 -2
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Open Mercato Module System — Conceptual Guide
|
|
2
|
+
|
|
3
|
+
This is the **hand-written, conceptual** layer of the module guides. It explains how an Open Mercato module is structured and how to build or extend one — the timeless concepts that rarely change. It is framework-wide; it does **not** describe any single module's data.
|
|
4
|
+
|
|
5
|
+
## How the guides are layered
|
|
6
|
+
|
|
7
|
+
- **Layer 1 — this file (`.ai/guides/module-system.md`):** conceptual and framework-wide. Module anatomy, auto-discovery, naming, the mandatory mechanisms, data-integrity rules, and the generate/migration workflow.
|
|
8
|
+
- **Layer 2 — generated per-module fact-sheets (`.ai/guides/modules/<module>.md` + `.ai/guides/module-facts.json`):** the concrete **facts** for one module, extracted from its source — entity IDs, events, ACL features, API routes with per-method auth, DI service tokens, searchable entities, host extension tokens, notifications, and CLI commands. These are generated; never hand-write them here.
|
|
9
|
+
- **Package guides (`.ai/guides/core.md`, `ui.md`, `shared.md`, …):** package-specific depth (patterns, helpers, deeper APIs).
|
|
10
|
+
|
|
11
|
+
When you need a concrete fact about a specific module — which events it emits, its entity IDs, which feature gates a route — open that module's fact-sheet. Do not infer module facts from this conceptual guide.
|
|
12
|
+
|
|
13
|
+
## Module anatomy
|
|
14
|
+
|
|
15
|
+
Each module lives in `src/modules/<id>/` and is **auto-discovered**. The only registration is one entry in `src/modules.ts` (`{ id: '<id>', from: '@app' }`). Run `yarn generate` after adding or changing any auto-discovered file.
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
src/modules/<id>/
|
|
19
|
+
├── index.ts # Module metadata
|
|
20
|
+
├── data/
|
|
21
|
+
│ ├── entities.ts # MikroORM entity classes (decorators from @mikro-orm/decorators/legacy)
|
|
22
|
+
│ ├── validators.ts # Zod validation schemas
|
|
23
|
+
│ ├── extensions.ts # Cross-module entity links (export `extensions`)
|
|
24
|
+
│ └── enrichers.ts # Response enrichers (export `enrichers`)
|
|
25
|
+
├── api/
|
|
26
|
+
│ ├── <resource>/route.ts # REST handlers (auto-discovered by method) + `metadata` + `openApi`
|
|
27
|
+
│ └── interceptors.ts # API route interception hooks (export `interceptors`)
|
|
28
|
+
├── backend/ # Admin UI pages (auto-discovered) + paired `page.meta.ts`
|
|
29
|
+
├── frontend/ # Public pages (auto-discovered); customer portal under `[orgSlug]/portal/`
|
|
30
|
+
├── subscribers/ # Event handlers (export `metadata` + default handler)
|
|
31
|
+
├── workers/ # Background jobs (export `metadata` + default handler)
|
|
32
|
+
├── widgets/
|
|
33
|
+
│ ├── injection/ # UI widgets injected into other modules
|
|
34
|
+
│ ├── injection-table.ts # Widget-to-slot mappings
|
|
35
|
+
│ └── components.ts # Component replacement/wrapper definitions (export `componentOverrides`)
|
|
36
|
+
├── di.ts # Awilix DI registrations (export `register(container)`)
|
|
37
|
+
├── acl.ts # Permission features (export `features`)
|
|
38
|
+
├── setup.ts # Tenant init, role features, seed data (export `setup`)
|
|
39
|
+
├── events.ts # Typed event declarations (export `eventsConfig`)
|
|
40
|
+
├── search.ts # Search indexing configuration (export `searchConfig`)
|
|
41
|
+
├── ce.ts # Custom entities / custom field sets (export `entities`)
|
|
42
|
+
├── translations.ts # Translatable fields per entity
|
|
43
|
+
├── notifications.ts # Notification type definitions (export `notificationTypes`)
|
|
44
|
+
└── encryption.ts # Tenant data encryption maps for sensitive / GDPR fields
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Auto-discovery paths
|
|
48
|
+
|
|
49
|
+
| Path pattern | Becomes |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `frontend/<path>.tsx` | `/<path>` (public page) |
|
|
52
|
+
| `frontend/[orgSlug]/portal/<path>/page.tsx` | `/{orgSlug}/portal/<path>` (customer portal page; `[orgSlug]` MUST be first) |
|
|
53
|
+
| `backend/<path>.tsx` | `/backend/<path>` (admin page) |
|
|
54
|
+
| `backend/page.tsx` | `/backend/<module>` (module root page) |
|
|
55
|
+
| `api/<method>/<path>.ts` | `/api/<path>` dispatched by HTTP method |
|
|
56
|
+
| `subscribers/*.ts` | event subscriber (export `metadata` + default handler) |
|
|
57
|
+
| `workers/*.ts` | background worker (export `metadata` + default handler) |
|
|
58
|
+
|
|
59
|
+
### Convention-file reference
|
|
60
|
+
|
|
61
|
+
| File | Export | Purpose |
|
|
62
|
+
|------|--------|---------|
|
|
63
|
+
| `index.ts` | `metadata` | Module metadata |
|
|
64
|
+
| `di.ts` | `register(container)` | DI registrations (Awilix) |
|
|
65
|
+
| `acl.ts` | `features` | Permission features (`['mod.view', 'mod.manage', …]`) |
|
|
66
|
+
| `setup.ts` | `setup` | Tenant init, default role features, seed data |
|
|
67
|
+
| `ce.ts` | `entities` | Custom entities / custom field sets |
|
|
68
|
+
| `events.ts` | `eventsConfig` | Typed event declarations (`createModuleEvents`) |
|
|
69
|
+
| `search.ts` | `searchConfig` | Search indexing config |
|
|
70
|
+
| `translations.ts` | `translatableFields` | Translatable fields per entity |
|
|
71
|
+
| `notifications.ts` | `notificationTypes` | Notification type definitions |
|
|
72
|
+
| `data/entities.ts` | — | MikroORM entity classes |
|
|
73
|
+
| `data/validators.ts` | — | Zod validation schemas |
|
|
74
|
+
| `data/extensions.ts` | `extensions` | Entity extensions (cross-module links) |
|
|
75
|
+
| `data/enrichers.ts` | `enrichers` | Response enrichers |
|
|
76
|
+
| `api/interceptors.ts` | `interceptors` | API route interception hooks |
|
|
77
|
+
| `widgets/components.ts` | `componentOverrides` | Component replacement/wrapper definitions |
|
|
78
|
+
|
|
79
|
+
## Naming conventions
|
|
80
|
+
|
|
81
|
+
- **Module IDs:** plural, snake_case (`order_items`). Special cases: `auth`, `example`.
|
|
82
|
+
- **Event IDs:** `module.entity.action` (singular entity, past-tense action, e.g. `sales.order.created`).
|
|
83
|
+
- **Entity IDs:** colon form `module:entity` (e.g. `customers:customer_person_profile`) — the canonical interop token, **not** the raw class name and **not** the dotted friendly alias some enrichers use.
|
|
84
|
+
- **DB tables:** plural, snake_case with a module prefix (`catalog_products`).
|
|
85
|
+
- **DB columns:** snake_case (`created_at`, `organization_id`). Common columns: `id`, `created_at`, `updated_at`, `deleted_at`, `is_active`, `organization_id`, `tenant_id`.
|
|
86
|
+
- **Feature IDs:** `<module>.<action>` (`my_module.view`, `my_module.manage`). FROZEN once shipped — rename by adding the new ID alongside and keeping the old as a deprecated alias.
|
|
87
|
+
- **JS/TS identifiers:** camelCase. UUID primary keys, explicit foreign keys, junction tables for M2M.
|
|
88
|
+
|
|
89
|
+
## Mandatory module mechanisms
|
|
90
|
+
|
|
91
|
+
The framework provides **one canonical primitive per concern**. Do not invent your own routing, auth, persistence, forms, caching, or cross-module calls. If a feature is not listed here, ask before rolling your own.
|
|
92
|
+
|
|
93
|
+
| Concern | Canonical mechanism |
|
|
94
|
+
|---|---|
|
|
95
|
+
| Module structure & auto-discovery | `src/modules/<id>/{api,backend,frontend,data,subscribers,workers,widgets}` + `index.ts` + one line in `src/modules.ts` — discovered by `yarn generate` |
|
|
96
|
+
| API routes | Files under `api/**/route.ts` exporting handlers + per-method `metadata` (`requireAuth` / `requireFeatures`) + `openApi`. NEVER a top-level `export const requireAuth` — the registry ignores it |
|
|
97
|
+
| CRUD APIs | `makeCrudRoute({ orm, list, create, update, del, indexer })` from `@open-mercato/shared/lib/crud/factory`. Always set `indexer` for query-index coverage. Custom (non-factory) write routes MUST run the mutation guard registry (`runMutationGuards`) |
|
|
98
|
+
| CRUD forms | `<CrudForm />` from `@open-mercato/ui/backend/CrudForm` + `createCrud`/`updateCrud`/`deleteCrud`. Never raw `<form>`, never raw `fetch` |
|
|
99
|
+
| Data tables | `<DataTable entityId apiPath … />` from `@open-mercato/ui/backend/DataTable`. Keep `entityId` / `extensionTableId` stable so widget injection keeps working |
|
|
100
|
+
| HTTP from the client | `apiCall` / `apiCallOrThrow` from `@open-mercato/ui/backend/utils/apiCall` — never raw `fetch` |
|
|
101
|
+
| Authorization (RBAC) | Declare features in `acl.ts`, grant in `setup.ts` `defaultRoleFeatures`, gate with `requireFeatures` in `metadata` / `page.meta.ts`. NEVER `requireRoles` (role names mutate). Treat `module.*` / `*` wildcard grants as part of the contract |
|
|
102
|
+
| Multi-tenant scoping | Every tenant-scoped entity has indexed `organization_id` + `tenant_id`; every read/write filters by them. The CRUD factory injects scope — do not bypass it. Ad-hoc queries use `withScopedPayload` |
|
|
103
|
+
| Encryption for sensitive data | Declare `encryption.ts` `defaultEncryptionMaps`; read via `findWithDecryption` / `findOneWithDecryption`. NEVER hand-roll AES/KMS, NEVER `em.find` on encrypted columns |
|
|
104
|
+
| Cache | Resolve from DI (`container.resolve('cache')`) — never `new Redis(...)`. Tag with `tenant:<id>` / `org:<id>` so invalidation stays tenant-scoped |
|
|
105
|
+
| Background workers | `workers/*.ts` exporting `metadata: { queue, id?, concurrency? }` + default handler. Never spin up custom queues |
|
|
106
|
+
| Events between modules | `events.ts` with `createModuleEvents({ moduleId, events } as const)`; subscribe in `subscribers/`. Never call another module's services directly across boundaries |
|
|
107
|
+
| Domain writes | Implement through the Command pattern so audit, undo, cache, events, and indexing stay consistent — do not mutate domain state directly in route handlers |
|
|
108
|
+
| i18n | `useT()` client-side, `resolveTranslations()` server-side; keys in `src/i18n/<locale>.json`. Never hard-code user-facing strings |
|
|
109
|
+
|
|
110
|
+
> Rule of thumb: if you reach for raw `fetch`, raw `<form>`, ad-hoc `crypto`, ad-hoc `Redis`, or a manual cross-module join, stop and check the row above — there is a canonical helper.
|
|
111
|
+
|
|
112
|
+
## Entity-update safety & data integrity
|
|
113
|
+
|
|
114
|
+
- **`withAtomicFlush`.** MikroORM can silently discard pending scalar changes when a query (`em.find`/`em.findOne`/sync helper) runs on the same `EntityManager` between a scalar mutation and `em.flush()`. Multi-phase mutations MUST use `withAtomicFlush(em, phases, { transaction: true })` from `@open-mercato/shared/lib/commands/flush`. Keep `emitCrudSideEffects` and cache invalidation **outside** the block — they fire only after the DB write commits. For entity + custom fields + side effects in one write, prefer `runCrudCommandWrite`.
|
|
115
|
+
- **Optimistic locking (default ON).** Every **new user-editable entity** MUST carry an `updated_at` column and return `updatedAt` in its list/detail responses, so the OSS optimistic lock can detect concurrent edits. `CrudForm` auto-derives the lock header from `initialValues.updatedAt` (covers update and delete). Append-only logs, junction/assignment tables, session/token rows, and parent-guarded sub-resource lines are exempt.
|
|
116
|
+
- **Encryption.** Sensitive / GDPR fields go through the encryption-maps mechanism (`encryption.ts` + `findWithDecryption`), never hand-rolled crypto. Always pass `tenantId` and `organizationId` to the decryption helpers.
|
|
117
|
+
- **Tenant isolation.** Never expose cross-tenant data; always filter by `organization_id` (and `tenant_id`). Never create direct ORM relationships between modules — reference by FK id and fetch separately.
|
|
118
|
+
|
|
119
|
+
## Generate & migration workflow
|
|
120
|
+
|
|
121
|
+
- **After editing `src/modules.ts` or any structural module file:** run `yarn generate`. Never hand-edit anything under `.mercato/generated/*`.
|
|
122
|
+
- **After editing `data/entities.ts`:** run `yarn db:generate` as a schema-diff probe. Default to the generated SQL; if it emits unrelated churn from another module's stale snapshot, keep only the SQL for your change and update that module's `migrations/.snapshot-open-mercato.json` in the same commit.
|
|
123
|
+
- **Do not run `yarn db:migrate`** unless the user explicitly asks. A PR should normally include the migration file plus snapshot, not local DB state. Never hand-edit a migration that has already shipped — add a new one.
|
|
124
|
+
- **New ACL features must be visible immediately:** add the feature to `acl.ts` **and** to `setup.ts` `defaultRoleFeatures`, then run `yarn mercato auth sync-role-acls` so existing tenants pick it up.
|
|
125
|
+
|
|
126
|
+
## Where to go next
|
|
127
|
+
|
|
128
|
+
- A specific module's surface (entities, events, routes, auth, search, CLI): its **fact-sheet** at `.ai/guides/modules/<module>.md`.
|
|
129
|
+
- Deeper package patterns: the matching **package guide** (`core.md`, `ui.md`, `shared.md`, `events.md`, `queue.md`, `cache.md`, `search.md`).
|
|
130
|
+
- Scaffolding a module end-to-end: the `om-module-scaffold` skill.
|
|
@@ -21,6 +21,7 @@ step, you WILL produce incorrect imports and miss required patterns.
|
|
|
21
21
|
|
|
22
22
|
| Task | Load |
|
|
23
23
|
|---|---|
|
|
24
|
+
| Understand the module system (anatomy, auto-discovery, naming, mandatory mechanisms, data integrity, migrations) | `.ai/guides/module-system.md` |
|
|
24
25
|
| Scaffold a new module from scratch | `.ai/skills/om-module-scaffold/SKILL.md` |
|
|
25
26
|
| Design entities and relationships | `.ai/skills/om-data-model-design/SKILL.md` |
|
|
26
27
|
| Build backend UI (forms, tables, pages) | `.ai/skills/om-backend-ui-design/SKILL.md` |
|
|
@@ -60,19 +61,10 @@ step, you WILL produce incorrect imports and miss required patterns.
|
|
|
60
61
|
|
|
61
62
|
### Module-Specific Guides
|
|
62
63
|
|
|
63
|
-
These
|
|
64
|
+
These per-module fact-sheets are **generated from source** and bundled for the modules enabled in this app. The list below is regenerated on scaffold from your enabled module set — do not edit between the markers.
|
|
64
65
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
| Build CRUD modules — reference patterns, commands, custom fields, search | `.ai/guides/core.customers.md` (if available) |
|
|
68
|
-
| Use workflow automation, triggers, user tasks, signals | `.ai/guides/core.workflows.md` (if available) |
|
|
69
|
-
| Use product catalog, pricing engine, variants, offers | `.ai/guides/core.catalog.md` (if available) |
|
|
70
|
-
| Use sales orders, quotes, invoices, shipments, payments | `.ai/guides/core.sales.md` (if available) |
|
|
71
|
-
| Use staff authentication, RBAC, roles, feature guards | `.ai/guides/core.auth.md` (if available) |
|
|
72
|
-
| Use multi-currency, exchange rates, dual recording | `.ai/guides/core.currencies.md` (if available) |
|
|
73
|
-
| Build integration providers, credentials, health checks | `.ai/guides/core.integrations.md` (if available) |
|
|
74
|
-
| Build data sync adapters, import/export connectors | `.ai/guides/core.data_sync.md` (if available) |
|
|
75
|
-
| Use customer portal auth, customer RBAC, portal pages | `.ai/guides/core.customer_accounts.md` (if available) |
|
|
66
|
+
<!-- om:module-guides:start -->
|
|
67
|
+
<!-- om:module-guides:end -->
|
|
76
68
|
|
|
77
69
|
### Quality & Process
|
|
78
70
|
|
|
@@ -1,101 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# core.auth — moved
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## RBAC Implementation
|
|
6
|
-
|
|
7
|
-
### Two-Layer Model
|
|
8
|
-
|
|
9
|
-
1. **Role ACLs** — features assigned to roles (admin, employee, etc.)
|
|
10
|
-
2. **User ACLs** — per-user overrides (additional features or restrictions)
|
|
11
|
-
|
|
12
|
-
Effective permissions = Role features + User-specific features.
|
|
13
|
-
|
|
14
|
-
### Declaring Features
|
|
15
|
-
|
|
16
|
-
Every module MUST declare features in `acl.ts` and wire them in `setup.ts`:
|
|
17
|
-
|
|
18
|
-
```typescript
|
|
19
|
-
// src/modules/<your_module>/acl.ts
|
|
20
|
-
export const features = [
|
|
21
|
-
'your_module.view',
|
|
22
|
-
'your_module.create',
|
|
23
|
-
'your_module.update',
|
|
24
|
-
'your_module.delete',
|
|
25
|
-
]
|
|
26
|
-
|
|
27
|
-
// src/modules/<your_module>/setup.ts
|
|
28
|
-
import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'
|
|
29
|
-
|
|
30
|
-
export const setup: ModuleSetupConfig = {
|
|
31
|
-
defaultRoleFeatures: {
|
|
32
|
-
superadmin: ['your_module.*'],
|
|
33
|
-
admin: ['your_module.*'],
|
|
34
|
-
user: ['your_module.view'],
|
|
35
|
-
},
|
|
36
|
-
}
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
### Feature Naming Convention
|
|
40
|
-
|
|
41
|
-
Features follow the `<module>.<action>` pattern (e.g., `users.view`, `users.edit`).
|
|
42
|
-
|
|
43
|
-
### Declarative Guards
|
|
44
|
-
|
|
45
|
-
Prefer declarative guards in page and API metadata:
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
|
-
export const metadata = {
|
|
49
|
-
requireAuth: true,
|
|
50
|
-
requireRoles: ['admin'],
|
|
51
|
-
requireFeatures: ['users.manage'],
|
|
52
|
-
}
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
### Server-Side Checks
|
|
56
|
-
|
|
57
|
-
```typescript
|
|
58
|
-
const rbacService = container.resolve('rbacService')
|
|
59
|
-
const hasAccess = await rbacService.userHasAllFeatures(
|
|
60
|
-
userId,
|
|
61
|
-
['your_module.view'],
|
|
62
|
-
{ tenantId, organizationId }
|
|
63
|
-
)
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
### Wildcards
|
|
67
|
-
|
|
68
|
-
Wildcards are first-class ACL grants: `module.*` and `*` satisfy matching concrete features. When your code inspects raw granted feature arrays (instead of calling `rbacService`), use the shared wildcard-aware matchers (`matchFeature`, `hasFeature`, `hasAllFeatures`) — never use `includes(...)`.
|
|
69
|
-
|
|
70
|
-
### Special Flags
|
|
71
|
-
|
|
72
|
-
- `isSuperAdmin` — bypasses all feature checks
|
|
73
|
-
- Organization visibility list — restricts which organizations a user can access
|
|
74
|
-
|
|
75
|
-
## Security Rules
|
|
76
|
-
|
|
77
|
-
- Hash passwords with `bcryptjs` (cost >= 10)
|
|
78
|
-
- Never log credentials
|
|
79
|
-
- Return minimal auth error messages — never reveal whether an email exists
|
|
80
|
-
- Use `findWithDecryption` / `findOneWithDecryption` for user queries
|
|
81
|
-
|
|
82
|
-
## Authentication Flow
|
|
83
|
-
|
|
84
|
-
1. User submits credentials via `POST /api/auth/session`
|
|
85
|
-
2. Password verified with bcryptjs
|
|
86
|
-
3. JWT session token issued
|
|
87
|
-
4. Session attached to requests via middleware
|
|
88
|
-
|
|
89
|
-
## Subscribing to Auth Events
|
|
90
|
-
|
|
91
|
-
```typescript
|
|
92
|
-
export const metadata = {
|
|
93
|
-
event: 'auth.user.created',
|
|
94
|
-
persistent: true,
|
|
95
|
-
id: 'your-module-user-created',
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export default async function handler(payload, ctx) {
|
|
99
|
-
// React to new user registration
|
|
100
|
-
}
|
|
101
|
-
```
|
|
3
|
+
> This guide has moved. See [`modules/auth.md`](modules/auth.md) for the generated `auth` fact-sheet, and [`module-system.md`](module-system.md) for conceptual module guidance.
|
|
@@ -1,79 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# core.catalog — moved
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Pricing System
|
|
6
|
-
|
|
7
|
-
Never reimplement pricing logic. Use the catalog pricing service via DI:
|
|
8
|
-
|
|
9
|
-
```typescript
|
|
10
|
-
const pricingService = container.resolve('catalogPricingService')
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
- `selectBestPrice` — finds the best price for a given context (customer, channel, quantity)
|
|
14
|
-
- `resolvePriceVariantId` — resolves variant-level prices
|
|
15
|
-
- Register custom pricing resolvers with priority (higher = checked first):
|
|
16
|
-
|
|
17
|
-
```typescript
|
|
18
|
-
import { registerCatalogPricingResolver } from '@open-mercato/core/modules/catalog/lib/pricing'
|
|
19
|
-
registerCatalogPricingResolver(myResolver, { priority: 10 })
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
Price layers compose in order: base price → channel override → customer-specific → promotional.
|
|
23
|
-
|
|
24
|
-
The pipeline emits `catalog.pricing.resolve.before` and `catalog.pricing.resolve.after` events that your module can subscribe to.
|
|
25
|
-
|
|
26
|
-
## Data Model
|
|
27
|
-
|
|
28
|
-
| Entity | Purpose | Key Constraints |
|
|
29
|
-
|--------|---------|----------------|
|
|
30
|
-
| **Products** | Core items with media and descriptions | MUST have at least a name |
|
|
31
|
-
| **Categories** | Hierarchical product grouping | No circular parent-child references |
|
|
32
|
-
| **Variants** | Product variations (size, color) | MUST reference valid option schemas |
|
|
33
|
-
| **Prices** | Multi-tier with channel scoping | Use `selectBestPrice` for resolution |
|
|
34
|
-
| **Offers** | Time-limited promotions | MUST have valid date ranges |
|
|
35
|
-
| **Option Schemas** | Variant option type definitions | Cannot delete while variants reference them |
|
|
36
|
-
|
|
37
|
-
## Subscribing to Catalog Events
|
|
38
|
-
|
|
39
|
-
React to product lifecycle events in your module:
|
|
40
|
-
|
|
41
|
-
```typescript
|
|
42
|
-
// src/modules/<your_module>/subscribers/product-updated.ts
|
|
43
|
-
export const metadata = {
|
|
44
|
-
event: 'catalog.product.updated',
|
|
45
|
-
persistent: true,
|
|
46
|
-
id: 'your-module-product-updated',
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export default async function handler(payload, ctx) {
|
|
50
|
-
// payload.resourceId = product ID
|
|
51
|
-
}
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
Key events:
|
|
55
|
-
- `catalog.product.created` / `updated` / `deleted`
|
|
56
|
-
- `catalog.pricing.resolve.before` / `after` (excluded from workflow triggers)
|
|
57
|
-
|
|
58
|
-
## Extending Catalog UI
|
|
59
|
-
|
|
60
|
-
Use widget injection to add your module's UI into catalog pages:
|
|
61
|
-
|
|
62
|
-
```typescript
|
|
63
|
-
// src/modules/<your_module>/widgets/injection-table.ts
|
|
64
|
-
export const widgetInjections = {
|
|
65
|
-
'crud-form:catalog.catalog_product:fields': {
|
|
66
|
-
widgetId: 'your-module-product-fields',
|
|
67
|
-
priority: 100,
|
|
68
|
-
},
|
|
69
|
-
}
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
Common injection spots:
|
|
73
|
-
- `crud-form:catalog.catalog_product:fields` — product edit form
|
|
74
|
-
- `data-table:catalog.products:columns` — product list columns
|
|
75
|
-
- `data-table:catalog.products:row-actions` — product row actions
|
|
76
|
-
|
|
77
|
-
## Using Catalog in Sales
|
|
78
|
-
|
|
79
|
-
When building sales-related features, use the catalog pricing service to resolve prices rather than reading price entities directly. This ensures channel scoping, customer-specific pricing, and promotional offers are applied correctly.
|
|
3
|
+
> This guide has moved. See [`modules/catalog.md`](modules/catalog.md) for the generated `catalog` fact-sheet, and [`module-system.md`](module-system.md) for conceptual module guidance.
|
|
@@ -1,43 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# core.currencies — moved
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Key Rules
|
|
6
|
-
|
|
7
|
-
1. **Store amounts with 4 decimal precision** — never truncate to 2 decimals internally
|
|
8
|
-
2. **Use date-based exchange rates** — always resolve rates for the transaction date, not the "current" rate
|
|
9
|
-
3. **Record both currencies** — dual recording (transaction currency + base currency) is mandatory for reporting
|
|
10
|
-
4. **Calculate realized gains/losses** on payment: `(payment rate - invoice rate) × foreign amount`
|
|
11
|
-
5. **Never hard-delete exchange rates** — they are historical reference data
|
|
12
|
-
|
|
13
|
-
## Multi-Currency Transaction Pattern
|
|
14
|
-
|
|
15
|
-
When processing multi-currency transactions (e.g., sales invoice in EUR with USD base):
|
|
16
|
-
|
|
17
|
-
1. Retrieve the exchange rate for the transaction date
|
|
18
|
-
2. Generate the document in the transaction currency
|
|
19
|
-
3. Calculate the base currency equivalent: `foreign amount × rate`
|
|
20
|
-
4. Store both amounts on the document
|
|
21
|
-
5. On payment: calculate realized gain/loss from rate difference
|
|
22
|
-
6. Report in both transaction and base currencies
|
|
23
|
-
|
|
24
|
-
## Data Model
|
|
25
|
-
|
|
26
|
-
| Entity | Table | Purpose |
|
|
27
|
-
|--------|-------|---------|
|
|
28
|
-
| **Currency** | `currency` | Currency master data (code, name, symbol) |
|
|
29
|
-
| **Exchange Rate** | `exchange_rate` | Daily exchange rates per currency pair |
|
|
30
|
-
|
|
31
|
-
## Adding a New Currency
|
|
32
|
-
|
|
33
|
-
1. Add the currency record via the admin UI or `seedDefaults` hook in your `setup.ts`
|
|
34
|
-
2. Ensure exchange rates exist for the currency pair at required dates
|
|
35
|
-
3. Verify all sales/pricing logic resolves the new currency correctly
|
|
36
|
-
|
|
37
|
-
## Using Currencies in Your Module
|
|
38
|
-
|
|
39
|
-
When your module deals with monetary amounts:
|
|
40
|
-
- Store the currency code alongside the amount
|
|
41
|
-
- Reference the currencies module for exchange rate lookups
|
|
42
|
-
- Use the transaction date for rate resolution, not the current date
|
|
43
|
-
- Store both foreign and base amounts for reporting
|
|
3
|
+
> This guide has moved. See [`modules/currencies.md`](modules/currencies.md) for the generated `currencies` fact-sheet, and [`module-system.md`](module-system.md) for conceptual module guidance.
|
|
@@ -1,129 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# core.customer_accounts — moved
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Portal Authentication
|
|
6
|
-
|
|
7
|
-
### Login Flow
|
|
8
|
-
1. Customer submits credentials via `POST /api/login`
|
|
9
|
-
2. Password verified with bcryptjs, lockout checked (5 attempts → 15 min lock)
|
|
10
|
-
3. JWT issued with customer claims (`type: 'customer'`, features, CRM links)
|
|
11
|
-
4. Two cookies set: `customer_auth_token` (JWT, 8h) + `customer_session_token` (raw, 30d)
|
|
12
|
-
|
|
13
|
-
### Other Auth Methods
|
|
14
|
-
- **Signup**: `POST /api/signup` — self-registration with email verification
|
|
15
|
-
- **Magic Link**: `POST /api/magic-link/request` + `/verify` — passwordless login (15 min TTL)
|
|
16
|
-
- **Password Reset**: `POST /api/password/reset-request` + `/reset-confirm` (60 min TTL)
|
|
17
|
-
- **Invitation**: Admin invites user → `POST /api/invitations/accept` (72h TTL)
|
|
18
|
-
|
|
19
|
-
## Customer RBAC
|
|
20
|
-
|
|
21
|
-
### Two-Layer Model (mirrors staff RBAC)
|
|
22
|
-
1. **Role ACLs** — features assigned to roles
|
|
23
|
-
2. **User ACLs** — per-user overrides (takes precedence if present)
|
|
24
|
-
|
|
25
|
-
### Default Roles (seeded on tenant creation)
|
|
26
|
-
| Role | Features | Portal Admin |
|
|
27
|
-
|------|----------|-------------|
|
|
28
|
-
| Portal Admin | `portal.*` | Yes |
|
|
29
|
-
| Buyer | Orders, quotes, catalog, account | No |
|
|
30
|
-
| Viewer | Read-only orders, invoices, catalog | No |
|
|
31
|
-
|
|
32
|
-
### Feature Convention
|
|
33
|
-
Portal features use `portal.<area>.<action>` naming (e.g., `portal.orders.view`, `portal.catalog.view`).
|
|
34
|
-
|
|
35
|
-
### Cross-Module Feature Merging
|
|
36
|
-
Your module can declare `defaultCustomerRoleFeatures` in `setup.ts`. During tenant setup, these are merged into the corresponding customer role ACLs:
|
|
37
|
-
|
|
38
|
-
```typescript
|
|
39
|
-
// src/modules/<your_module>/setup.ts
|
|
40
|
-
export const setup: ModuleSetupConfig = {
|
|
41
|
-
defaultCustomerRoleFeatures: {
|
|
42
|
-
portal_admin: ['portal.your_feature.*'],
|
|
43
|
-
buyer: ['portal.your_feature.view'],
|
|
44
|
-
},
|
|
45
|
-
}
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
## Using Customer Auth in Your Module
|
|
49
|
-
|
|
50
|
-
### Server Components (pages)
|
|
51
|
-
```typescript
|
|
52
|
-
import { getCustomerAuthFromCookies } from '@open-mercato/core/modules/customer_accounts/lib/customerAuthServer'
|
|
53
|
-
|
|
54
|
-
const auth = await getCustomerAuthFromCookies()
|
|
55
|
-
if (!auth) redirect('/login')
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
### API Routes
|
|
59
|
-
```typescript
|
|
60
|
-
import { requireCustomerAuth, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
|
|
61
|
-
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
62
|
-
import type { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'
|
|
63
|
-
|
|
64
|
-
// In your API handler:
|
|
65
|
-
const auth = await requireCustomerAuth(request) // throws 401 if not authenticated
|
|
66
|
-
const container = await createRequestContainer()
|
|
67
|
-
const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService
|
|
68
|
-
// Re-resolves ACL on every request so role/feature revocation is immediate
|
|
69
|
-
await requireCustomerFeature(auth, ['portal.orders.view'], customerRbacService) // throws 403 if missing
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
### RBAC Service
|
|
73
|
-
```typescript
|
|
74
|
-
const rbacService = container.resolve('customerRbacService')
|
|
75
|
-
const hasAccess = await rbacService.userHasAllFeatures(
|
|
76
|
-
userId, ['portal.orders.view'], { tenantId, organizationId }
|
|
77
|
-
)
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
## Portal Page Guards
|
|
81
|
-
|
|
82
|
-
Use declarative metadata for portal pages:
|
|
83
|
-
|
|
84
|
-
```typescript
|
|
85
|
-
export const metadata = {
|
|
86
|
-
requireCustomerAuth: true,
|
|
87
|
-
requireCustomerFeatures: ['portal.orders.view'],
|
|
88
|
-
}
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
## Subscribing to Customer Events
|
|
92
|
-
|
|
93
|
-
| Event | When |
|
|
94
|
-
|-------|------|
|
|
95
|
-
| `customer_accounts.user.created` | New customer signup |
|
|
96
|
-
| `customer_accounts.user.updated` | Profile updated |
|
|
97
|
-
| `customer_accounts.user.locked` | Account locked after failed logins |
|
|
98
|
-
| `customer_accounts.login.success` | Successful login |
|
|
99
|
-
| `customer_accounts.invitation.accepted` | Invitation accepted |
|
|
100
|
-
|
|
101
|
-
```typescript
|
|
102
|
-
export const metadata = {
|
|
103
|
-
event: 'customer_accounts.user.created',
|
|
104
|
-
persistent: true,
|
|
105
|
-
id: 'your-module-customer-signup',
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export default async function handler(payload, ctx) {
|
|
109
|
-
// React to customer signup — e.g., create default preferences
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
## CRM Auto-Linking
|
|
114
|
-
|
|
115
|
-
When a customer signs up, the module automatically searches for a matching CRM person by email and links them (`personEntityId`). The reverse also works — creating a CRM person auto-links to an existing customer user.
|
|
116
|
-
|
|
117
|
-
## Widget Injection Spots
|
|
118
|
-
|
|
119
|
-
| Spot | Widget | Purpose |
|
|
120
|
-
|------|--------|---------|
|
|
121
|
-
| `crud-form:customers:customer_person_profile:fields` | Account status | Shows portal account status on CRM person detail |
|
|
122
|
-
| `crud-form:customers:customer_company_profile:fields` | Company users | Shows portal users linked to a CRM company |
|
|
123
|
-
|
|
124
|
-
## Security Notes
|
|
125
|
-
|
|
126
|
-
- All public endpoints are rate-limited (per-email + per-IP)
|
|
127
|
-
- Tokens stored as SHA-256 hashes — raw tokens never persisted
|
|
128
|
-
- Emails use deterministic hash for lookups (`hashForLookup`)
|
|
129
|
-
- Error messages never confirm whether an email is registered
|
|
3
|
+
> This guide has moved. See [`modules/customer_accounts.md`](modules/customer_accounts.md) for the generated `customer_accounts` fact-sheet, and [`module-system.md`](module-system.md) for conceptual module guidance.
|
|
@@ -1,138 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# core.customers — moved
|
|
2
2
|
|
|
3
|
-
This
|
|
4
|
-
|
|
5
|
-
## CRUD API Pattern
|
|
6
|
-
|
|
7
|
-
Use `makeCrudRoute` with `indexer: { entityType }` for query index coverage:
|
|
8
|
-
|
|
9
|
-
```typescript
|
|
10
|
-
// src/modules/<your_module>/api/get/<entities>.ts
|
|
11
|
-
import { makeCrudRoute } from '@open-mercato/shared/lib/crud/make-crud-route'
|
|
12
|
-
import { YourEntity } from '../../entities/YourEntity'
|
|
13
|
-
|
|
14
|
-
const handler = makeCrudRoute({
|
|
15
|
-
entity: YourEntity,
|
|
16
|
-
entityId: 'your_module.your_entity',
|
|
17
|
-
operations: ['list', 'detail'],
|
|
18
|
-
indexer: { entityType: 'your_module.your_entity' },
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
export default handler
|
|
22
|
-
export const openApi = { summary: 'List and retrieve entities', tags: ['Your Module'] }
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
Key points:
|
|
26
|
-
- Always set `indexer: { entityType }` — keeps custom entities indexed
|
|
27
|
-
- Wire custom field helpers for create/update if your module supports custom fields
|
|
28
|
-
- Export `openApi` on every API route file
|
|
29
|
-
|
|
30
|
-
## Undoable Commands Pattern
|
|
31
|
-
|
|
32
|
-
All write operations should use the Command pattern with undo support:
|
|
33
|
-
|
|
34
|
-
```typescript
|
|
35
|
-
import { registerCommand } from '@open-mercato/shared/lib/commands'
|
|
36
|
-
import { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'
|
|
37
|
-
|
|
38
|
-
registerCommand('your_module.entity.create', {
|
|
39
|
-
async execute(payload, ctx) {
|
|
40
|
-
// 1. Create entity
|
|
41
|
-
// 2. Capture snapshot for undo: extractUndoPayload(entity)
|
|
42
|
-
// 3. Side effects: emitCrudSideEffects({ indexer: { entityType, cacheAliases } })
|
|
43
|
-
},
|
|
44
|
-
async undo(payload, ctx) {
|
|
45
|
-
// 1. Restore from snapshot
|
|
46
|
-
// 2. Side effects: emitCrudUndoSideEffects({ indexer: { entityType, cacheAliases } })
|
|
47
|
-
},
|
|
48
|
-
})
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
Key points:
|
|
52
|
-
- Include `indexer: { entityType, cacheAliases }` in both `emitCrudSideEffects` and `emitCrudUndoSideEffects`
|
|
53
|
-
- Capture custom field snapshots in `before`/`after` payloads (`snapshot.custom`)
|
|
54
|
-
- Restore custom fields via `buildCustomFieldResetMap(before.custom, after.custom)` in undo
|
|
55
|
-
|
|
56
|
-
## Custom Field Integration
|
|
57
|
-
|
|
58
|
-
```typescript
|
|
59
|
-
import { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
- Pass `{ transform }` to normalize values (e.g., `normalizeCustomFieldSubmitValue`)
|
|
63
|
-
- Works for both `cf_` and `cf:` prefixed keys
|
|
64
|
-
- Pass `entityIds` to form helpers so correct custom-field sets are loaded
|
|
65
|
-
- If your module ships default custom fields, declare them in `ce.ts` via `entities[].fields`
|
|
66
|
-
|
|
67
|
-
## Search Configuration
|
|
68
|
-
|
|
69
|
-
Declare in `search.ts` with all three strategies:
|
|
70
|
-
|
|
71
|
-
```typescript
|
|
72
|
-
import type { SearchModuleConfig } from '@open-mercato/shared/modules/search'
|
|
73
|
-
|
|
74
|
-
export const searchConfig: SearchModuleConfig = {
|
|
75
|
-
entities: {
|
|
76
|
-
'your_module.your_entity': {
|
|
77
|
-
fields: ['name', 'description'], // Fulltext indexing
|
|
78
|
-
// fieldPolicy for sensitive field handling
|
|
79
|
-
// buildSource for vector embeddings
|
|
80
|
-
// formatResult for search result display
|
|
81
|
-
},
|
|
82
|
-
},
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
Key points:
|
|
87
|
-
- Use `fieldPolicy.excluded` for sensitive fields (passwords, tokens)
|
|
88
|
-
- Use `fieldPolicy.hashOnly` for PII needing exact-match only (email, phone)
|
|
89
|
-
- Always define `formatResult` for human-friendly search results
|
|
90
|
-
|
|
91
|
-
## Backend Page Structure
|
|
92
|
-
|
|
93
|
-
Follow this pattern for each page type:
|
|
94
|
-
|
|
95
|
-
| Page | Pattern | Key Features |
|
|
96
|
-
|------|---------|-------------|
|
|
97
|
-
| **List** | `DataTable` | Filters, search, export, row actions, pagination |
|
|
98
|
-
| **Create** | `CrudForm` mode=create | Fields, groups, custom fields, back link |
|
|
99
|
-
| **Detail/Edit** | `CrudForm` mode=edit or tabbed layout | Entity data, related entities, activities |
|
|
100
|
-
|
|
101
|
-
## Module Files Checklist
|
|
102
|
-
|
|
103
|
-
When scaffolding a new CRUD module, ensure all these files are present:
|
|
104
|
-
|
|
105
|
-
| File | Purpose |
|
|
106
|
-
|------|---------|
|
|
107
|
-
| `index.ts` | Module metadata |
|
|
108
|
-
| `acl.ts` | Feature-based permissions |
|
|
109
|
-
| `setup.ts` | Tenant init, default role features |
|
|
110
|
-
| `di.ts` | Awilix DI registrations |
|
|
111
|
-
| `events.ts` | Typed event declarations |
|
|
112
|
-
| `data/entities.ts` | MikroORM entity classes |
|
|
113
|
-
| `data/validators.ts` | Zod validation schemas |
|
|
114
|
-
| `search.ts` | Search indexing configuration |
|
|
115
|
-
| `ce.ts` | Custom entities / custom field sets |
|
|
116
|
-
|
|
117
|
-
Optional:
|
|
118
|
-
- `translations.ts` — translatable fields per entity
|
|
119
|
-
- `notifications.ts` — notification type definitions
|
|
120
|
-
- `cli.ts` — module CLI commands
|
|
121
|
-
|
|
122
|
-
## Entity Update Safety
|
|
123
|
-
|
|
124
|
-
When mutating entities across multiple phases that include queries:
|
|
125
|
-
|
|
126
|
-
```typescript
|
|
127
|
-
import { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'
|
|
128
|
-
|
|
129
|
-
await withAtomicFlush(em, [
|
|
130
|
-
() => { record.name = 'New'; record.status = 'active' },
|
|
131
|
-
() => syncEntityTags(em, record, tags),
|
|
132
|
-
], { transaction: true })
|
|
133
|
-
|
|
134
|
-
// Side effects AFTER the atomic flush
|
|
135
|
-
await emitCrudSideEffects({ ... })
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
Never run `em.find`/`em.findOne` between scalar mutations and `em.flush()` without `withAtomicFlush` — changes will be silently lost. Cache invalidation must also stay outside `withAtomicFlush` and fire after commit, so the opt-in `OM_CACHE_SAFETY_ALWAYS_CONSISTENT` mode (default OFF) never serves stale or partially-committed reads.
|
|
3
|
+
> This guide has moved. See [`modules/customers.md`](modules/customers.md) for the generated `customers` fact-sheet, and [`module-system.md`](module-system.md) for conceptual module guidance.
|