Files
hedena_gold/apps/api/src/main.ts
T
s.esmaeiliandClaude Opus 5 8133a2bdf4 parity(api,admin): split customer name, add making-charge offset, wire SMS
Applies the two approved additive migrations and fixes every consumer.

D0 — Customer.firstName / lastName
The reference has had two columns since 2020
(2020_10_01_120430_customers_table.php:18-19); the port collapsed them, so
the edit form showed the whole name in the "first name" box and saved an
empty last name. Adds both columns, backfills first-token/rest, and keeps
fullName in sync with a customer_sync_full_name trigger. Nothing dropped.

The trigger is SQL, so Prisma cannot see it: writing the parts rebuilds
fullName, writing fullName re-derives the parts, and writing both in one
statement lets THE PARTS WIN. Documented in the migration header, the
Customer model doc comment and DECISIONS.md §D14, because a write can now
store something other than what was passed.

D9 — Customer.makingChargeOffsetPercent
Legacy customers.percent, the per-customer making-charge offset that the
app adds to the variant's making charge (henza_pwa
Mixins/product/index.ts:69-75). toRow() was returning the referring
AGENT's commission rate instead (CUST-02). DB default 0 reproduces
today's behaviour exactly, so no existing customer's price moves; the
reference's application-layer default of 3 for NEW customers
(AdminController.php:338) lives in the create form, and the field is
required on create with the reference's own message (:354).

update() and updateCredit() both accepted percent and silently discarded
it; both now persist it. Sort/filter aliases fname/lname pointed at
fullName and now point at the real columns.

SMS — Trez provider (Sms.php:57-82)
New global SmsModule/SmsService: form-urlencoded POST, 20s timeout, body
trimmed, every message persisted. send() never throws, matching the
reference, which discarded Sms::Send's result so a gateway outage never
aborted the order or approval that triggered it. The OTP text is
byte-identical, including the Android SMS Retriever markers. Credentials
come from env only; production refuses to boot without them rather than
silently locking every customer out. .env.example carries names, no values.

Admin panel: the split(' ') fallback is removed from singleCustomer.vue,
and bulkCustomer.vue defaults percent to 3, requires it, coerces the
Decimal on load so diff-send works, and only re-sends `name` when a name
part changed. ReagentCustomer.vue is untouched — its «درصد کمیسیون» is
AdminUser.wagePercent, a different field.

Tests: 32 jest (incl. 14 new SMS config/template), 9 trigger assertions,
53 auth smoke, and the full D12 round-trip on the customer entity —
«محمد علی» + «احمدی» survives create, edit, a byte-identical no-op save,
and single-field edits. Typecheck clean on api and admin-panel.

Note: migrate dev is interactive-only and could not run here, so the
migrations were applied with migrate deploy after a read-only drift check.
The only drift is the pre-existing _goldbank_migrations table, which
Prisma would DROP; it was NOT dropped (DEAD-07).

[ref: henza_server/app/Models/Sms.php, app/Http/Controllers/Adm/AdminController.php]

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 08:08:50 +03:30

62 lines
2.4 KiB
TypeScript

import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { extname, join } from 'node:path';
import type { Response } from 'express';
import { AppModule } from './app.module';
import { prepareDatabase } from './prisma/bootstrap';
import { PrismaExceptionFilter } from './prisma/prisma-exception.filter';
import { assertSmsConfigured } from './modules/sms/sms.service';
// serve-static's bundled `mime` version predates .avif, so it falls back to
// application/octet-stream — browsers still render the image (they sniff
// content), but a strict client or an <img> under some CSPs would not.
const EXTRA_MIME_TYPES: Record<string, string> = {
'.avif': 'image/avif',
};
async function bootstrap() {
// Fail fast rather than start a server on which no customer could log in.
// In production a missing SMS credential throws here; outside production it
// only warns and the codes are logged locally.
assertSmsConfigured();
await prepareDatabase();
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
app.useGlobalFilters(new PrismaExceptionFilter());
app.enableCors();
// Uploaded files, mounted OUTSIDE the /api prefix so the URLs stored on
// UploadedFile.url ("/uploads/<name>") resolve directly.
app.useStaticAssets(process.env.UPLOAD_DIR ?? join(process.cwd(), 'storage', 'uploads'), {
prefix: '/uploads/',
index: false,
dotfiles: 'deny',
setHeaders: (res: Response, path: string) => {
const mime = EXTRA_MIME_TYPES[extname(path).toLowerCase()];
if (mime) res.setHeader('Content-Type', mime);
},
});
const port = Number(process.env.PORT ?? 3000);
try {
// Bind all interfaces explicitly so the container is reachable from nginx.
await app.listen(port, '0.0.0.0');
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EADDRINUSE') {
// eslint-disable-next-line no-console
console.error(
`\n[api] Port ${port} is already in use. Free it or change API_PORT ` +
`in the repo-root .env (and PORT in apps/api/.env to match) — the ` +
`API will not fall back to a different port.\n`,
);
process.exit(1);
}
throw err;
}
}
bootstrap();