feat(customers): create/edit/archive CRUD with soft-delete (plan phase 2)
First master-data CRUD module on the phase-1 RBAC foundation. API: - Customer gains archivedAt (soft-delete marker, distinct from the legacy `status` business flag); pushed to dev (nullable, non-destructive). - CustomersService: create/update/archive/restore. list() and the browser default to archivedAt=null; ?includeArchived=true opts in. App-created rows set nameMissing=false and leave legacy provenance null. - CustomersController write routes guarded per the matrix: create/update need STAFF+ (customer:create/update), archive/restore need ADMIN (customer:delete). Every mutation audit-logged. - create/update DTOs (class-validator); date strings coerced to Date. Web: - Shared CustomerForm (create + edit) with identity/address/account sections; new routes /clientes/nuevo and /clientes/[id]/editar, each self-gated on the ability. - List page: ability-gated "Nuevo cliente" button. Detail page: gated Editar / Archivar (Restaurar) action bar; archived badge. - api.ts create/update/archive/restore; CustomerInput type; archived flag on list items. Verified against dev: create (dates coerced, archivedAt null), edit 200, VIEWER create 403, STAFF create 201 but archive 403, ADMIN archive drops the row from the default list and includeArchived surfaces it, restore returns it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsEnum,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
} from "class-validator";
|
||||
import { Currency } from "@jorgecuadros/database";
|
||||
|
||||
/**
|
||||
* Editable customer fields. Internal/derived columns (nameSource, nameMissing,
|
||||
* legacy* provenance, archivedAt) are managed by the service, not the client.
|
||||
* `name` is the only required field; everything else is optional.
|
||||
*/
|
||||
export class CreateCustomerDto {
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
name!: string;
|
||||
|
||||
@IsOptional() @IsString() addressLine1?: string;
|
||||
@IsOptional() @IsString() addressLine2?: string;
|
||||
@IsOptional() @IsString() city?: string;
|
||||
@IsOptional() @IsString() state?: string;
|
||||
@IsOptional() @IsString() zipCode?: string;
|
||||
@IsOptional() @IsString() country?: string;
|
||||
@IsOptional() @IsString() phone?: string;
|
||||
@IsOptional() @IsString() mobile?: string;
|
||||
@IsOptional() @IsString() fax?: string;
|
||||
@IsOptional() @IsEmail() email?: string;
|
||||
@IsOptional() @IsString() notes?: string;
|
||||
@IsOptional() @IsString() identificationType?: string;
|
||||
@IsOptional() @IsString() identificationNumber?: string;
|
||||
/** ISO date string; coerced to Date by the service. */
|
||||
@IsOptional() @IsString() identificationExpiration?: string;
|
||||
@IsOptional() @IsString() customerSince?: string;
|
||||
@IsOptional() @IsBoolean() status?: boolean;
|
||||
@IsOptional() @IsNumber() minimumBalance?: number;
|
||||
@IsOptional() @IsNumber() feeAmount?: number;
|
||||
@IsOptional() @IsEnum(Currency) preferredCurrency?: Currency;
|
||||
}
|
||||
@@ -1,11 +1,35 @@
|
||||
import { Controller, Get, Param, Query, UseGuards } from "@nestjs/common";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from "@nestjs/common";
|
||||
import { Request } from "express";
|
||||
import { AuthenticatedGuard } from "../auth/authenticated.guard";
|
||||
import { AbilityGuard } from "../auth/ability.guard";
|
||||
import { RequireAbility } from "../auth/require-ability.decorator";
|
||||
import { AuditService } from "../common/audit.service";
|
||||
import { CustomersService } from "./customers.service";
|
||||
import { CreateCustomerDto } from "./create-customer.dto";
|
||||
import { UpdateCustomerDto } from "./update-customer.dto";
|
||||
|
||||
@UseGuards(AuthenticatedGuard)
|
||||
@UseGuards(AuthenticatedGuard, AbilityGuard)
|
||||
@Controller("customers")
|
||||
export class CustomersController {
|
||||
constructor(private readonly customers: CustomersService) {}
|
||||
constructor(
|
||||
private readonly customers: CustomersService,
|
||||
private readonly audit: AuditService,
|
||||
) {}
|
||||
|
||||
private actingId(req: Request): string {
|
||||
return (req.user as { id: string }).id;
|
||||
}
|
||||
|
||||
@Get("stats")
|
||||
stats() {
|
||||
@@ -18,14 +42,57 @@ export class CustomersController {
|
||||
@Query("page") page?: string,
|
||||
@Query("pageSize") pageSize?: string,
|
||||
@Query("line") line?: "utility" | "insurance" | "both",
|
||||
@Query("includeArchived") includeArchived?: string,
|
||||
) {
|
||||
const p = Math.max(1, Number(page) || 1);
|
||||
const ps = Math.min(100, Math.max(1, Number(pageSize) || 25));
|
||||
return this.customers.list({ query, page: p, pageSize: ps, line });
|
||||
return this.customers.list({
|
||||
query,
|
||||
page: p,
|
||||
pageSize: ps,
|
||||
line,
|
||||
includeArchived: includeArchived === "true",
|
||||
});
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
detail(@Param("id") id: string) {
|
||||
return this.customers.detail(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequireAbility("customer:create")
|
||||
async create(@Body() dto: CreateCustomerDto, @Req() req: Request) {
|
||||
const c = await this.customers.create(dto);
|
||||
void this.audit.log(this.actingId(req), "customer.create", { customerId: c.id, name: c.name });
|
||||
return c;
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@RequireAbility("customer:update")
|
||||
async update(
|
||||
@Param("id") id: string,
|
||||
@Body() dto: UpdateCustomerDto,
|
||||
@Req() req: Request,
|
||||
) {
|
||||
const c = await this.customers.update(id, dto);
|
||||
void this.audit.log(this.actingId(req), "customer.update", { customerId: id });
|
||||
return c;
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@RequireAbility("customer:delete")
|
||||
async archive(@Param("id") id: string, @Req() req: Request) {
|
||||
const c = await this.customers.archive(id);
|
||||
void this.audit.log(this.actingId(req), "customer.archive", { customerId: id });
|
||||
return c;
|
||||
}
|
||||
|
||||
@Post(":id/restore")
|
||||
@RequireAbility("customer:delete")
|
||||
async restore(@Param("id") id: string, @Req() req: Request) {
|
||||
const c = await this.customers.restore(id);
|
||||
void this.audit.log(this.actingId(req), "customer.restore", { customerId: id });
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@jorgecuadros/database";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { CreateCustomerDto } from "./create-customer.dto";
|
||||
import { UpdateCustomerDto } from "./update-customer.dto";
|
||||
|
||||
export interface ListParams {
|
||||
query?: string;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
line?: "utility" | "insurance" | "both";
|
||||
includeArchived?: boolean;
|
||||
}
|
||||
|
||||
/** Parse an optional ISO date string to a Date (or null to clear it). */
|
||||
function toDate(v?: string): Date | null | undefined {
|
||||
if (v === undefined) return undefined;
|
||||
if (v === "" || v === null) return null;
|
||||
const d = new Date(v);
|
||||
return isNaN(d.getTime()) ? undefined : d;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -14,9 +25,11 @@ export class CustomersService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/** Unified customer list with search + business-line filter, paginated. */
|
||||
async list({ query, page, pageSize, line }: ListParams) {
|
||||
async list({ query, page, pageSize, line, includeArchived }: ListParams) {
|
||||
const where: Prisma.CustomerWhereInput = {};
|
||||
|
||||
if (!includeArchived) where.archivedAt = null;
|
||||
|
||||
if (query && query.trim()) {
|
||||
const q = query.trim();
|
||||
where.OR = [
|
||||
@@ -54,6 +67,7 @@ export class CustomersService {
|
||||
phone: true,
|
||||
mobile: true,
|
||||
status: true,
|
||||
archivedAt: true,
|
||||
_count: { select: { properties: true, policies: true, transactions: true } },
|
||||
},
|
||||
}),
|
||||
@@ -69,6 +83,7 @@ export class CustomersService {
|
||||
phone: r.phone,
|
||||
mobile: r.mobile,
|
||||
status: r.status,
|
||||
archived: r.archivedAt != null,
|
||||
propertyCount: r._count.properties,
|
||||
policyCount: r._count.policies,
|
||||
transactionCount: r._count.transactions,
|
||||
@@ -133,6 +148,58 @@ export class CustomersService {
|
||||
};
|
||||
}
|
||||
|
||||
// --- writes ---------------------------------------------------------------
|
||||
|
||||
private toData(dto: CreateCustomerDto | UpdateCustomerDto) {
|
||||
// Whitelisted by the DTO already; map the date strings to Date objects.
|
||||
const { identificationExpiration, customerSince, ...rest } = dto;
|
||||
return {
|
||||
...rest,
|
||||
...(identificationExpiration !== undefined && {
|
||||
identificationExpiration: toDate(identificationExpiration),
|
||||
}),
|
||||
...(customerSince !== undefined && { customerSince: toDate(customerSince) }),
|
||||
};
|
||||
}
|
||||
|
||||
async create(dto: CreateCustomerDto) {
|
||||
return this.prisma.customer.create({
|
||||
// App-created rows: nameMissing false (name is required), no legacy
|
||||
// provenance — those columns stay null, marking a native record.
|
||||
data: { ...this.toData(dto), name: dto.name, nameMissing: false },
|
||||
});
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateCustomerDto) {
|
||||
await this.ensureExists(id);
|
||||
return this.prisma.customer.update({ where: { id }, data: this.toData(dto) });
|
||||
}
|
||||
|
||||
/** Soft-delete: hide from default lists, keep the row + provenance. */
|
||||
async archive(id: string) {
|
||||
await this.ensureExists(id);
|
||||
return this.prisma.customer.update({
|
||||
where: { id },
|
||||
data: { archivedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
async restore(id: string) {
|
||||
await this.ensureExists(id);
|
||||
return this.prisma.customer.update({
|
||||
where: { id },
|
||||
data: { archivedAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureExists(id: string) {
|
||||
const found = await this.prisma.customer.findUnique({
|
||||
where: { id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!found) throw new NotFoundException(`Customer ${id} not found`);
|
||||
}
|
||||
|
||||
/** Top-line counts for a dashboard header. */
|
||||
async stats() {
|
||||
const [customers, withUtilities, withInsurance, policies, properties, transactions] =
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsEnum,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
} from "class-validator";
|
||||
import { Currency } from "@jorgecuadros/database";
|
||||
|
||||
/** Same editable fields as create, all optional. */
|
||||
export class UpdateCustomerDto {
|
||||
@IsOptional() @IsString() @MinLength(1) name?: string;
|
||||
@IsOptional() @IsString() addressLine1?: string;
|
||||
@IsOptional() @IsString() addressLine2?: string;
|
||||
@IsOptional() @IsString() city?: string;
|
||||
@IsOptional() @IsString() state?: string;
|
||||
@IsOptional() @IsString() zipCode?: string;
|
||||
@IsOptional() @IsString() country?: string;
|
||||
@IsOptional() @IsString() phone?: string;
|
||||
@IsOptional() @IsString() mobile?: string;
|
||||
@IsOptional() @IsString() fax?: string;
|
||||
@IsOptional() @IsEmail() email?: string;
|
||||
@IsOptional() @IsString() notes?: string;
|
||||
@IsOptional() @IsString() identificationType?: string;
|
||||
@IsOptional() @IsString() identificationNumber?: string;
|
||||
@IsOptional() @IsString() identificationExpiration?: string;
|
||||
@IsOptional() @IsString() customerSince?: string;
|
||||
@IsOptional() @IsBoolean() status?: boolean;
|
||||
@IsOptional() @IsNumber() minimumBalance?: number;
|
||||
@IsOptional() @IsNumber() feeAmount?: number;
|
||||
@IsOptional() @IsEnum(Currency) preferredCurrency?: Currency;
|
||||
}
|
||||
Reference in New Issue
Block a user