@meghjs/mcp 0.0.0-stage → 0.7.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
@@ -0,0 +1,172 @@
1
+ ---
2
+ title: Auth
3
+ description: Scaffold sign-up and sign-in with JWTs, API keys or both, and optionally roles and permissions, with scaffold:auth.
4
+ ---
5
+
6
+ # Auth
7
+
8
+ ```sh
9
+ npx megh scaffold:auth
10
+ # shorthand
11
+ npx megh sc:auth
12
+ ```
13
+
14
+ You are asked three things:
15
+
16
+ 1. **How clients sign in:** JWT, API keys, or both.
17
+ 2. **Roles:** none, single (one role per user, `users.role_id`), or multiple
18
+ (any number per user, the `user_roles` table).
19
+ 3. **Permissions:** whether roles grant permissions (with roles only).
20
+
21
+ Or give the answers as options:
22
+
23
+ ```sh
24
+ npx megh sc:auth --strategy jwt -y
25
+ npx megh sc:auth --strategy both --roles multiple --permissions -y
26
+ npx megh sc:auth --strategy api-key --roles single --no-permissions -y
27
+ ```
28
+
29
+ | Option | Description |
30
+ |---|---|
31
+ | `--strategy <strategy>` | `jwt`, `api-key` or `both` (default `jwt`) |
32
+ | `--roles <mode>` | `none`, `single` or `multiple` (default `none`) |
33
+ | `--permissions` / `--no-permissions` | Roles grant permissions |
34
+ | `-f`, `--force` | Overwrite the generated auth files |
35
+ | `-y`, `--yes` | Don't prompt |
36
+
37
+ JWTs use [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken), which the
38
+ command tells you to install:
39
+
40
+ ```sh
41
+ npm install jsonwebtoken
42
+ npm install -D @types/jsonwebtoken
43
+ ```
44
+
45
+ Then create the tables and the roles:
46
+
47
+ ```sh
48
+ npx megh migrate --seed
49
+ ```
50
+
51
+ ## Routes
52
+
53
+ | Route | Body | Response |
54
+ |---|---|---|
55
+ | `POST /auth/register` | `{ name, email, password }` | Same as login |
56
+ | `POST /auth/login` | `{ email, password }` | JWT: `{ token_type: "Bearer", access_token, expires_in, user }`. API keys only: `{ api_key, user }` |
57
+ | `GET /auth/me` | | The signed-in user, with their roles |
58
+ | `GET /auth/api-keys` | | The user's active keys (API keys) |
59
+ | `POST /auth/api-keys` | `{ name, expires_at? }` | The new key, with `key` shown this once (API keys) |
60
+ | `DELETE /auth/api-keys/:id` | | Revokes a key (API keys) |
61
+
62
+ Send the token as `Authorization: Bearer <access_token>`, or the key as
63
+ `X-API-Key: <key>`. A wrong password and an unknown email both answer
64
+ `401 Invalid email or password.`; a registered email answers 400. Passwords
65
+ need at least 8 characters.
66
+
67
+ ```sh
68
+ curl -X POST localhost:4000/auth/login -H 'content-type: application/json' \
69
+ -d '{"email":"ann@example.com","password":"secret123"}'
70
+
71
+ curl localhost:4000/auth/me -H "authorization: Bearer $TOKEN"
72
+ ```
73
+
74
+ ## Protecting Routes
75
+
76
+ ```ts
77
+ import { ApiController, Authorized, AuthUser, Get, type Row } from '@meghjs/core';
78
+ import type { User } from '../models/user.model';
79
+
80
+ @ApiController('/orders')
81
+ export class OrderController {
82
+ @Authorized() // signed in, else 401
83
+ @Get()
84
+ mine(@AuthUser() user: Row<User>) { /* ... */ }
85
+
86
+ @Authorized({ roles: ['admin'] }) // and an admin, else 403
87
+ @Get('/all')
88
+ all() { /* ... */ }
89
+
90
+ @Authorized({ permissions: ['orders.manage'] })
91
+ @Get('/export')
92
+ export() { /* ... */ }
93
+ }
94
+ ```
95
+
96
+ `@Authorized()` on the controller class protects all of its routes. Roles
97
+ match by slug or name; see [RBAC](/cli/scaffold/rbac).
98
+
99
+ ## Generated Files
100
+
101
+ | File | Contents |
102
+ |---|---|
103
+ | `src/database/migrations/*` | `users`, and as chosen `roles`, `user_roles` or `users.role_id`, `permissions` with `role_permissions`, `api_keys` |
104
+ | `src/models/*.model.ts` | `User` (with its `roles` / `role` relation), `Role`, `Permission`, `ApiKey` |
105
+ | `src/auth/password.ts` | `hashPassword()` / `verifyPassword()` with scrypt, built into Node.js |
106
+ | `src/auth/jwt.ts` | `signToken()` / `verifyToken()`: HS256 with `JWT_SECRET` |
107
+ | `src/auth/api-keys.ts` | `generateApiKey()` / `hashApiKey()` |
108
+ | `src/auth/authentication.ts` | `AppAuthentication`: reads the token or key and sets `request.user`, with its roles loaded |
109
+ | `src/auth/authorization.ts` | `AppAuthorization`: the checks behind `@Authorized(...)` |
110
+ | `src/auth/rbac.ts` | `rolesOf()`, `hasRole()`, `permissionsOf()`, `hasPermission()`, `assignRole()` |
111
+ | `src/dtos/auth.dto.ts` | `RegisterDto`, `LoginDto`, `CreateApiKeyDto` |
112
+ | `src/services/auth.service.ts` | `AuthService`: register, login and API keys |
113
+ | `src/controllers/auth.controller.ts` | `AuthController`: the routes above |
114
+ | `src/database/seeders/roles.seeder.ts` | The `admin` and `user` roles (and permissions), safe to run again |
115
+
116
+ It also updates:
117
+
118
+ - **`src/app.ts`**: registers the handlers and the controller.
119
+
120
+ ```ts
121
+ app.useAuthentication(AppAuthentication);
122
+ app.useAuthorization(AppAuthorization);
123
+
124
+ app.useControllers([HomeController, AuthController]);
125
+ ```
126
+
127
+ - **`.env`**: `JWT_SECRET` (a random 96-character key) and `JWT_EXPIRES_IN=1d`.
128
+ `.env.example` gets the names without the secret.
129
+ - **`src/config/openapi.config.ts`**: `auth: 'bearer'` (`'apiKey'` with API
130
+ keys only), for the Authorize button of the [docs page](/microservices/openapi).
131
+ - **`src/database/seeders/database.seeder.ts`**, if you have one: calls
132
+ `"roles"`, so `db:seed` runs it.
133
+
134
+ New users get the `user` role. `User` and `ApiKey` leave the password,
135
+ remember token and key hash out of their JSON, so responses never contain
136
+ them.
137
+
138
+ ## Security
139
+
140
+ - Passwords are hashed with scrypt and a random salt, and compared in
141
+ constant time.
142
+ - Only the SHA-256 hash of an API key is stored. A key is shown once, when it
143
+ is created; revoked and expired keys are refused.
144
+ - Tokens are signed with HS256 and verified with only that algorithm. Keep
145
+ `JWT_SECRET` out of version control. A JWT can't be revoked before it
146
+ expires, so keep `JWT_EXPIRES_IN` short or use API keys where you need
147
+ revocation.
148
+ - Deactivated users (`is_active = false`) can't sign in, and their tokens
149
+ stop working.
150
+ - Not included: refresh tokens, email verification, password reset and rate
151
+ limiting on login.
152
+
153
+ ## An Existing Users Table
154
+
155
+ If a migration already creates `users`, it is kept. An alter-table migration
156
+ adds the columns sign-in needs and the table lacks (`email`, `password`, and
157
+ `role_id` for a single role), as nullable columns since the table may have
158
+ rows. The `User` model is updated with
159
+ [`sync:model`](/cli/generators#syncing-a-model), and the generated code only
160
+ uses columns the table has.
161
+
162
+ ## Running It Again
163
+
164
+ Generated files aren't overwritten: running `scaffold:auth` again fails with
165
+ the files that exist. Pass `-f` to regenerate them, e.g. to switch from JWT to
166
+ both. Migrations and models are never rewritten, and nothing is registered
167
+ twice. A file that already has exactly the content it would get, such as
168
+ `rbac.ts` from an earlier [`scaffold:rbac`](/cli/scaffold/rbac) with the same
169
+ roles, is kept.
170
+
171
+ See [Authentication](/core-concept/authentication) for how
172
+ `MeghAuthentication` and `@Authorized` work.
@@ -0,0 +1,224 @@
1
+ ---
2
+ title: Domains
3
+ description: Scaffold the tables of a business domain, such as e-commerce, POS or medical, with scaffold:domain.
4
+ ---
5
+
6
+ # Domains
7
+
8
+ ```sh
9
+ npx megh scaffold:domain ecommerce # checklist of the domain's templates
10
+ npx megh sc:domain ecommerce -y --resource # every template, as REST resources
11
+ npx megh sc:domain pos --only product,sale,sale_item --factory
12
+ npx megh sc:domain medical --migrations-only
13
+ npx megh sc:domain # pick a domain
14
+ ```
15
+
16
+ `scaffold:domain` writes a migration for each template of a domain, in the
17
+ order their foreign keys need, and then a model for each (join tables have
18
+ none). Templates a foreign key points to from another domain are included,
19
+ such as `common/user` for `ecommerce/customer`.
20
+
21
+ Domains share tables: `ecommerce` and `pos` both have `products` and
22
+ `customers`, and `hr` and `medical` both have `departments`. Scaffolding a
23
+ second domain reuses the tables and models already there.
24
+
25
+ | Option | Description |
26
+ |---|---|
27
+ | `--only <list>` | Only these templates, e.g. `product,order,order_item` |
28
+ | `--all` | Every template, without the checklist |
29
+ | `--resource` | Generate REST resources (DTOs, service, controller), not just models |
30
+ | `--migrations-only` | Only write the migrations |
31
+ | `--factory` | Also write a factory for each model |
32
+ | `--no-deps` | Don't create the tables foreign keys point to |
33
+ | `-f`, `--force` | Regenerate the models (and resources) that already exist |
34
+ | `-y`, `--yes` | Don't prompt: every template (or `--only`), with their dependencies |
35
+
36
+ Scaffold a single template with
37
+ [`make:model --template`](/cli/scaffold/templates#from-a-template), and add your
38
+ own domains in [`.megh/templates/`](/cli/scaffold/templates#your-own-templates).
39
+
40
+ ## Built-in Templates
41
+
42
+ Every table also has an `id`, `created_at` and `updated_at`, except join
43
+ tables, which have neither. Run `npx megh templates <domain>` for the same list in the
44
+ terminal.
45
+
46
+ ### Common `common`
47
+
48
+ Users, roles, categories and other tables most apps share.
49
+
50
+ | Template | Table | Columns |
51
+ |---|---|---|
52
+ | `user` | `users` (soft deletes) | name, email, password, email_verified_at, remember_token, is_active, last_login_at |
53
+ | `role` | `roles` | name, slug, description |
54
+ | `permission` | `permissions` | name, group, description |
55
+ | `user_role` | `user_roles` (join table) | user_id, role_id |
56
+ | `role_permission` | `role_permissions` (join table) | role_id, permission_id |
57
+ | `category` | `categories` | parent_id, name, slug, description, image, sort_order, is_active |
58
+ | `tag` | `tags` | name, slug |
59
+ | `address` | `addresses` | addressable_type, addressable_id, label, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, is_default |
60
+ | `attachment` | `attachments` | attachable_type, attachable_id, name, path, disk, mime_type, size |
61
+ | `api_key` | `api_keys` | user_id, name, prefix, key_hash, last_used_at, expires_at, revoked_at |
62
+ | `setting` | `settings` | name, value, group |
63
+
64
+ ### E-commerce `ecommerce`
65
+
66
+ An online store: catalog, carts, orders and payments.
67
+
68
+ | Template | Table | Columns |
69
+ |---|---|---|
70
+ | `brand` | `brands` | name, slug, logo, description, website, is_active |
71
+ | `product` | `products` (soft deletes) | category_id, brand_id, name, slug, sku, description, price, compare_at_price, cost, stock, weight, status, is_featured |
72
+ | `product_variant` | `product_variants` | product_id, sku, name, price, stock, options, image |
73
+ | `product_tag` | `product_tags` (join table) | product_id, tag_id |
74
+ | `customer` | `customers` | user_id, first_name, last_name, email, phone, accepts_marketing |
75
+ | `cart` | `carts` | customer_id, session_id, currency, status |
76
+ | `cart_item` | `cart_items` | cart_id, product_id, product_variant_id, quantity, price |
77
+ | `coupon` | `coupons` | code, description, discount_type, value, min_order_amount, max_uses, used_count, starts_at, ends_at, is_active |
78
+ | `order` | `orders` | customer_id, coupon_id, number, status, subtotal, discount, tax, shipping_total, total, currency, shipping_address, billing_address, placed_at, notes |
79
+ | `order_item` | `order_items` | order_id, product_id, product_variant_id, name, sku, quantity, price, discount, total |
80
+ | `payment` | `payments` | order_id, method, provider, transaction_id, amount, currency, status, paid_at |
81
+ | `shipment` | `shipments` | order_id, carrier, tracking_number, status, shipped_at, delivered_at |
82
+ | `review` | `reviews` | product_id, customer_id, rating, title, comment, is_approved |
83
+ | `wishlist` | `wishlists` | customer_id, product_id |
84
+
85
+ ### Point of sale `pos`
86
+
87
+ Shops and tills: outlets, shifts, sales, purchases and stock.
88
+
89
+ | Template | Table | Columns |
90
+ |---|---|---|
91
+ | `outlet` | `outlets` | name, code, phone, email, address_line1, address_line2, city, state, postal_code, country, is_active |
92
+ | `register` | `registers` | outlet_id, name, is_active |
93
+ | `shift` | `shifts` | register_id, user_id, opened_at, closed_at, opening_cash, closing_cash, expected_cash, status, notes |
94
+ | `customer` | `customers` | name, email, phone, loyalty_points, notes |
95
+ | `supplier` | `suppliers` | name, contact_name, email, phone, address_line1, address_line2, city, state, postal_code, country, tax_number, is_active |
96
+ | `tax_rate` | `tax_rates` | name, rate, is_inclusive, is_active |
97
+ | `product` | `products` | category_id, name, sku, barcode, price, cost, stock, reorder_level, tax_rate_id, is_active |
98
+ | `sale` | `sales` | outlet_id, register_id, shift_id, customer_id, user_id, number, subtotal, discount, tax, total, paid_amount, change_amount, status, sold_at |
99
+ | `sale_item` | `sale_items` | sale_id, product_id, name, quantity, price, discount, tax, total |
100
+ | `sale_payment` | `sale_payments` | sale_id, method, amount, reference |
101
+ | `purchase` | `purchases` | supplier_id, outlet_id, number, status, subtotal, tax, total, ordered_at, received_at, notes |
102
+ | `purchase_item` | `purchase_items` | purchase_id, product_id, quantity, unit_cost, total |
103
+ | `stock_movement` | `stock_movements` | product_id, outlet_id, user_id, type, quantity, reference, notes |
104
+
105
+ ### Medical `medical`
106
+
107
+ Clinics and hospitals: patients, doctors, appointments and records.
108
+
109
+ | Template | Table | Columns |
110
+ |---|---|---|
111
+ | `department` | `departments` | name, code, description, phone, is_active |
112
+ | `doctor` | `doctors` | user_id, department_id, first_name, last_name, email, phone, specialization, license_number, consultation_fee, is_active |
113
+ | `patient` | `patients` (soft deletes) | mrn, first_name, last_name, gender, date_of_birth, phone, email, address_line1, address_line2, city, state, postal_code, country, blood_group, allergies, emergency_contact_name, emergency_contact_phone |
114
+ | `appointment` | `appointments` | patient_id, doctor_id, department_id, scheduled_at, duration_minutes, status, reason, notes |
115
+ | `medical_record` | `medical_records` | patient_id, doctor_id, appointment_id, visit_date, chief_complaint, diagnosis, treatment, vitals, notes |
116
+ | `medication` | `medications` | name, generic_name, form, strength, manufacturer, price, stock, is_active |
117
+ | `prescription` | `prescriptions` | patient_id, doctor_id, medical_record_id, medication_id, dosage, frequency, duration, quantity, instructions, prescribed_at |
118
+ | `lab_test` | `lab_tests` | patient_id, doctor_id, name, code, status, result, normal_range, unit, ordered_at, completed_at |
119
+ | `insurance` | `insurances` | patient_id, provider, policy_number, group_number, coverage_percent, valid_from, valid_until, is_active |
120
+ | `invoice` | `invoices` | patient_id, appointment_id, insurance_id, number, subtotal, discount, tax, total, paid_amount, status, issued_at, due_date |
121
+
122
+ ### Construction `construction`
123
+
124
+ Building projects: sites, contractors, work orders, materials and budgets.
125
+
126
+ | Template | Table | Columns |
127
+ |---|---|---|
128
+ | `client` | `clients` | name, company, email, phone, address_line1, address_line2, city, state, postal_code, country |
129
+ | `project` | `projects` (soft deletes) | client_id, manager_id, name, code, description, status, budget, start_date, end_date, address_line1, address_line2, city, state, postal_code, country |
130
+ | `site` | `sites` | project_id, supervisor_id, name, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, is_active |
131
+ | `contractor` | `contractors` | name, company, trade, email, phone, license_number, address_line1, address_line2, city, state, postal_code, country, rating, is_active |
132
+ | `work_order` | `work_orders` | project_id, site_id, contractor_id, assigned_to_id, title, description, priority, status, due_date, completed_at, estimated_cost, actual_cost |
133
+ | `material` | `materials` | name, sku, unit, unit_cost, quantity_on_hand, reorder_level, supplier |
134
+ | `equipment` | `equipment` | site_id, name, code, category, serial_number, status, purchase_date, purchase_cost |
135
+ | `timesheet` | `timesheets` | user_id, project_id, work_order_id, date, hours, overtime_hours, status, notes |
136
+ | `inspection` | `inspections` | project_id, site_id, inspector_name, type, scheduled_at, inspected_at, result, notes |
137
+ | `change_order` | `change_orders` | project_id, requested_by_id, number, title, description, amount, days_impact, status, approved_at |
138
+ | `budget_item` | `budget_items` | project_id, category, description, budgeted_amount, actual_amount, notes |
139
+
140
+ ### Marketing `marketing`
141
+
142
+ Campaigns, leads, contacts, segments and email.
143
+
144
+ | Template | Table | Columns |
145
+ |---|---|---|
146
+ | `campaign` | `campaigns` | owner_id, name, slug, type, status, budget, spent, starts_at, ends_at, description |
147
+ | `contact` | `contacts` | first_name, last_name, email, phone, company, job_title, source, country, status |
148
+ | `lead` | `leads` | contact_id, campaign_id, owner_id, name, email, phone, company, source, status, score, notes |
149
+ | `segment` | `segments` | name, description, rules, is_dynamic |
150
+ | `contact_segment` | `contact_segments` (join table) | contact_id, segment_id |
151
+ | `email_template` | `email_templates` | name, subject, body, from_name, from_email, is_active |
152
+ | `subscriber` | `subscribers` | email, name, status, source, subscribed_at, unsubscribed_at, ip_address |
153
+ | `landing_page` | `landing_pages` | campaign_id, title, slug, content, meta_title, meta_description, status, published_at, views, conversions |
154
+ | `utm_link` | `utm_links` | campaign_id, url, utm_source, utm_medium, utm_campaign, utm_term, utm_content, short_code, clicks |
155
+
156
+ ### Real estate `real-estate`
157
+
158
+ Properties, listings, agents, tenants, leases and rent.
159
+
160
+ | Template | Table | Columns |
161
+ |---|---|---|
162
+ | `agent` | `agents` | user_id, first_name, last_name, email, phone, license_number, agency, commission_rate, avatar, is_active |
163
+ | `property` | `properties` (soft deletes) | agent_id, title, slug, description, type, status, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, bedrooms, bathrooms, area, area_unit, lot_size, year_built, price, currency, is_featured |
164
+ | `unit` | `units` | property_id, unit_number, floor, bedrooms, bathrooms, area, rent, status |
165
+ | `amenity` | `amenities` | name, slug, icon, category |
166
+ | `property_amenity` | `property_amenities` (join table) | property_id, amenity_id |
167
+ | `listing` | `listings` | property_id, agent_id, type, price, currency, status, listed_at, expires_at, description, views |
168
+ | `tenant` | `tenants` | user_id, first_name, last_name, email, phone, date_of_birth, national_id, employer, monthly_income, emergency_contact_name, emergency_contact_phone |
169
+ | `lease` | `leases` | unit_id, tenant_id, start_date, end_date, rent_amount, deposit_amount, billing_day, status, terms, signed_at |
170
+ | `rent_payment` | `rent_payments` | lease_id, amount, due_date, paid_at, method, reference, status, late_fee |
171
+ | `inquiry` | `inquiries` | property_id, listing_id, agent_id, name, email, phone, message, status |
172
+ | `viewing` | `viewings` | property_id, inquiry_id, agent_id, scheduled_at, status, feedback |
173
+ | `maintenance_request` | `maintenance_requests` | unit_id, tenant_id, title, description, priority, status, reported_at, resolved_at, cost |
174
+
175
+ ### HR `hr`
176
+
177
+ Employees, departments, attendance, leave and payroll.
178
+
179
+ | Template | Table | Columns |
180
+ |---|---|---|
181
+ | `department` | `departments` | name, code, description, is_active |
182
+ | `position` | `positions` | department_id, title, description, min_salary, max_salary |
183
+ | `employee` | `employees` (soft deletes) | user_id, department_id, position_id, employee_number, first_name, last_name, email, phone, gender, date_of_birth, hire_date, employment_type, salary, status, address_line1, address_line2, city, state, postal_code, country |
184
+ | `attendance` | `attendances` | employee_id, date, check_in, check_out, status, hours, notes |
185
+ | `leave_type` | `leave_types` | name, code, days_per_year, is_paid |
186
+ | `leave_request` | `leave_requests` | employee_id, leave_type_id, approved_by_id, start_date, end_date, days, reason, status, approved_at |
187
+ | `payroll` | `payrolls` | employee_id, period_start, period_end, basic_salary, allowances, deductions, tax, net_pay, status, paid_at |
188
+
189
+ ### CRM `crm`
190
+
191
+ Accounts, contacts, deal pipelines and activities.
192
+
193
+ | Template | Table | Columns |
194
+ |---|---|---|
195
+ | `account` | `accounts` | owner_id, name, industry, website, phone, email, address_line1, address_line2, city, state, postal_code, country, annual_revenue, employee_count, status |
196
+ | `contact` | `contacts` | account_id, owner_id, first_name, last_name, email, phone, job_title, notes |
197
+ | `pipeline` | `pipelines` | name, is_default, sort_order |
198
+ | `pipeline_stage` | `pipeline_stages` | pipeline_id, name, probability, sort_order, is_won, is_lost |
199
+ | `deal` | `deals` | account_id, contact_id, pipeline_id, pipeline_stage_id, owner_id, title, amount, currency, expected_close_date, status, closed_at, lost_reason |
200
+ | `activity` | `activities` | user_id, account_id, contact_id, deal_id, type, subject, description, due_at, completed_at |
201
+
202
+ ### Education `education`
203
+
204
+ Schools and courses: students, teachers, enrollments and grades.
205
+
206
+ | Template | Table | Columns |
207
+ |---|---|---|
208
+ | `teacher` | `teachers` | user_id, staff_number, first_name, last_name, email, phone, specialization, hire_date, is_active |
209
+ | `student` | `students` | user_id, student_number, first_name, last_name, email, phone, gender, date_of_birth, admission_date, status, address_line1, address_line2, city, state, postal_code, country |
210
+ | `course` | `courses` | teacher_id, code, title, description, credits, level, capacity, price, status, starts_at, ends_at |
211
+ | `enrollment` | `enrollments` | student_id, course_id, enrolled_at, status, progress, completed_at |
212
+ | `grade` | `grades` | enrollment_id, assessment, score, max_score, letter, weight, graded_at, remarks |
213
+
214
+ ### Logistics `logistics`
215
+
216
+ Warehouses, vehicles, drivers and deliveries.
217
+
218
+ | Template | Table | Columns |
219
+ |---|---|---|
220
+ | `warehouse` | `warehouses` | name, code, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, phone, capacity, is_active |
221
+ | `vehicle` | `vehicles` | warehouse_id, plate_number, type, make, model, year, capacity_kg, status |
222
+ | `driver` | `drivers` | user_id, vehicle_id, first_name, last_name, phone, email, license_number, license_expires_at, status |
223
+ | `delivery` | `deliveries` | warehouse_id, vehicle_id, driver_id, tracking_number, recipient_name, recipient_phone, address_line1, address_line2, city, state, postal_code, country, latitude, longitude, weight, status, scheduled_at, delivered_at, proof_url, notes |
224
+ | `tracking_event` | `tracking_events` | delivery_id, status, location, latitude, longitude, occurred_at, notes |
@@ -0,0 +1,77 @@
1
+ ---
2
+ title: Scaffold
3
+ description: Generate tables, models and whole features from templates with the Megh CLI.
4
+ ---
5
+
6
+ # Scaffold
7
+
8
+ The `scaffold:*` commands, and the `--template` / `--fields` options of
9
+ `make:model` and `make:resource`, build complete parts of an app from
10
+ templates. A template describes a table: its columns, foreign keys,
11
+ timestamps and indexes. It becomes an ordinary `schema.create(...)`
12
+ [migration](/advanced/orm/migrations), and the usual [generators](/cli/generators)
13
+ then write the model, DTOs, service, controller and factory from that
14
+ migration. Everything generated is plain code you own and can edit.
15
+
16
+ | Command | Alias | Description |
17
+ |---------|-------|-------------|
18
+ | `make:model <name> --template <ref>` | `m:m` | A table and its model from a template |
19
+ | `make:resource <name> --template <ref>` | `m:r` | A table and its full REST resource from a template |
20
+ | `make:model <name> --fields <list>` | `m:m` | A table described on the command line |
21
+ | `scaffold:domain [domain]` | `sc:domain` | Several tables of a business domain at once |
22
+ | `scaffold:auth` | `sc:auth` | Sign-up and sign-in with JWTs and/or API keys, optionally with roles |
23
+ | `scaffold:rbac` | `sc:rbac` | Roles (one or many per user) and permissions |
24
+ | `template:list [domain]` | `templates` | List the templates |
25
+
26
+ ## Pages
27
+
28
+ | Page | What it covers |
29
+ |---|---|
30
+ | [Templates and Fields](/cli/scaffold/templates) | `--template`, `--fields`, the field spec and presets, your own templates |
31
+ | [Domains](/cli/scaffold/domains) | `scaffold:domain` and every built-in template |
32
+ | [Auth](/cli/scaffold/auth) | `scaffold:auth`: JWT, API keys, the generated routes and code |
33
+ | [RBAC](/cli/scaffold/rbac) | `scaffold:rbac`: roles, permissions and `@Authorized({ roles })` |
34
+
35
+ ## Quick Start
36
+
37
+ ```sh
38
+ npx megh new shop --yes --database postgres
39
+ cd shop
40
+
41
+ # Sign-in with JWTs, many roles per user, roles grant permissions
42
+ npx megh sc:auth --strategy jwt --roles multiple --permissions -y
43
+
44
+ # The store: products, orders, payments, ...
45
+ npx megh sc:domain ecommerce --resource -y
46
+
47
+ npx megh migrate --seed
48
+ npm run start:dev
49
+ ```
50
+
51
+ ## How It Works
52
+
53
+ 1. **Migrations.** Each template becomes a create-table migration in
54
+ `src/database/migrations/`. Tables a foreign key points to are created too
55
+ when no migration creates them yet (`products.category_id` brings in
56
+ `categories`). Migrations are numbered so each table comes after the tables
57
+ it references, and after every migration already in the folder.
58
+ 2. **Models and more.** The migrations are read, not run, so no database is
59
+ needed: `make:model`, `make:resource` and `make:factory` build the model,
60
+ DTOs, service, controller and factory from their columns.
61
+ 3. **Existing work is kept.** A table some migration already creates keeps
62
+ that migration, and the template's columns are not applied to it. An
63
+ existing model is reused. To change a table, write an alter-table
64
+ migration and run [`sync:model`](/cli/generators#syncing-a-model).
65
+
66
+ Then create the tables:
67
+
68
+ ```sh
69
+ npx megh migrate
70
+ ```
71
+
72
+ ## Prompts
73
+
74
+ In a terminal, commands ask for what is missing: a template, the templates
75
+ of a domain, the sign-in strategy, the role mode, and whether to create the
76
+ tables foreign keys point to. Pass `-y` / `--yes` to skip the prompts and use
77
+ the options given (and the defaults), e.g. in scripts and CI.
@@ -0,0 +1,118 @@
1
+ ---
2
+ title: RBAC
3
+ description: Add roles and permissions to an app's users with scaffold:rbac, and check them with @Authorized.
4
+ ---
5
+
6
+ # RBAC
7
+
8
+ ```sh
9
+ npx megh scaffold:rbac
10
+ # shorthand
11
+ npx megh sc:rbac --roles multiple --permissions -y
12
+ ```
13
+
14
+ `scaffold:rbac` adds role-based access control to an app's users without
15
+ the sign-in parts. Use it when you already authenticate users your own way,
16
+ or to add roles before running [`scaffold:auth`](/cli/scaffold/auth).
17
+ `scaffold:auth` asks the same questions and generates the same files, so you
18
+ don't need both.
19
+
20
+ | Option | Description |
21
+ |---|---|
22
+ | `--roles <mode>` | `single` or `multiple` (default `multiple`) |
23
+ | `--permissions` / `--no-permissions` | Roles grant permissions |
24
+ | `-f`, `--force` | Overwrite the generated files |
25
+ | `-y`, `--yes` | Don't prompt |
26
+
27
+ ## Role Modes
28
+
29
+ | Mode | Tables | `User` model |
30
+ |---|---|---|
31
+ | `single` | `roles`, `users.role_id` | `@BelongsTo(() => Role) role` |
32
+ | `multiple` | `roles`, `user_roles` (`user_id`, `role_id`) | `@BelongsToMany(() => Role, { table: "user_roles" }) roles` |
33
+ | `--permissions` | also `permissions`, `role_permissions` | `Role` gets `@BelongsToMany(() => Permission, { table: "role_permissions" }) permissions` |
34
+
35
+ A role has a `name`, a unique `slug` and a `description`; a permission has a
36
+ unique `name` such as `users.manage`, a `group` and a `description`. Without
37
+ a `users` table, one is created from the `common/user` template; an existing
38
+ one gets `role_id` through an alter-table migration.
39
+
40
+ ## Generated Files
41
+
42
+ | File | Contents |
43
+ |---|---|
44
+ | `src/database/migrations/*` | The tables above |
45
+ | `src/models/role.model.ts`, `permission.model.ts` | The models, and the relations on `User` |
46
+ | `src/auth/rbac.ts` | Role and permission helpers |
47
+ | `src/auth/authorization.ts` | `AppAuthorization`, registered in `src/app.ts` with `app.useAuthorization()` |
48
+ | `src/database/seeders/roles.seeder.ts` | The `admin` and `user` roles, and their permissions |
49
+
50
+ Create the tables and roles:
51
+
52
+ ```sh
53
+ npx megh migrate --seed
54
+ ```
55
+
56
+ The seeder finds roles and permissions by slug and name before creating
57
+ them, so it is safe to run again. Edit its `ROLES` and `PERMISSIONS` to fit
58
+ your app:
59
+
60
+ ```ts [src/database/seeders/roles.seeder.ts]
61
+ const ROLES = [
62
+ { name: "Admin", slug: "admin", description: "Full access" },
63
+ { name: "User", slug: "user", description: "A signed-up user" },
64
+ ];
65
+
66
+ /** Permissions per role slug. Check them with @Authorized({ permissions: [...] }). */
67
+ const PERMISSIONS: Record<string, string[]> = {
68
+ admin: ["users.view", "users.manage", "roles.manage"],
69
+ user: [],
70
+ };
71
+ ```
72
+
73
+ ## Checking Roles
74
+
75
+ On a route:
76
+
77
+ ```ts
78
+ @Authorized({ roles: ['admin', 'editor'] }) // any of these roles
79
+ @Authorized({ permissions: ['posts.publish'] }) // any of these permissions
80
+ ```
81
+
82
+ A caller without a user gets 401 and one without the role or permission 403.
83
+ Roles match by slug or name.
84
+
85
+ In code, with the helpers from `src/auth/rbac.ts`:
86
+
87
+ ```ts
88
+ import { assignRole, hasPermission, hasRole } from '../auth/rbac';
89
+
90
+ if (await hasRole(user, ['admin'])) { /* ... */ }
91
+ if (await hasPermission(user, ['posts.publish'])) { /* ... */ }
92
+
93
+ await assignRole(user, 'editor'); // false if there is no such role
94
+ ```
95
+
96
+ The helpers use the roles (and permissions) already loaded on the user, as
97
+ the generated `AppAuthentication` loads them, and query them otherwise.
98
+
99
+ ## Request User
100
+
101
+ `AppAuthorization` reads `request.user`, which an
102
+ [authentication handler](/core-concept/authentication) sets. `scaffold:auth`
103
+ generates one. With your own, return a `User`, ideally with its roles loaded
104
+ so the checks don't query them on every request:
105
+
106
+ ```ts
107
+ return User.with('roles.permissions').where('id', id).first();
108
+ ```
109
+
110
+ To manage roles over HTTP, generate resources for them:
111
+
112
+ ```sh
113
+ npx megh make:resource role
114
+ npx megh make:resource permission
115
+ ```
116
+
117
+ and protect them with `@Authorized({ roles: ['admin'] })` on the controller
118
+ class.