Uecko_ERP/modules/customers/src/api/domain/value-objects/customer-status.ts

73 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-08-11 17:49:52 +00:00
import { DomainValidationError } from "@erp/core/api";
import { ValueObject } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
interface ICustomerStatusProps {
value: string;
}
2025-08-26 18:55:59 +00:00
export enum CUSTOMER_STATUS {
ACTIVE = "active",
INACTIVE = "inactive",
2025-08-11 17:49:52 +00:00
}
export class CustomerStatus extends ValueObject<ICustomerStatusProps> {
2025-08-26 18:55:59 +00:00
private static readonly ALLOWED_STATUSES = ["active", "inactive"];
private static readonly FIELD = "status";
private static readonly ERROR_CODE = "INVALID_STATUS";
2025-08-11 17:49:52 +00:00
private static readonly TRANSITIONS: Record<string, string[]> = {
2025-08-26 18:55:59 +00:00
active: [CUSTOMER_STATUS.INACTIVE],
inactive: [CUSTOMER_STATUS.ACTIVE],
2025-08-11 17:49:52 +00:00
};
static create(value: string): Result<CustomerStatus, Error> {
if (!CustomerStatus.ALLOWED_STATUSES.includes(value)) {
2025-08-26 18:55:59 +00:00
const detail = `Status value not valid: ${value}`;
2025-08-11 17:49:52 +00:00
return Result.fail(
new DomainValidationError(CustomerStatus.ERROR_CODE, CustomerStatus.FIELD, detail)
);
}
return Result.ok(
2025-08-26 18:55:59 +00:00
value === "active" ? CustomerStatus.createActive() : CustomerStatus.createInactive()
2025-08-11 17:49:52 +00:00
);
}
2025-08-26 18:55:59 +00:00
public static createActive(): CustomerStatus {
return new CustomerStatus({ value: CUSTOMER_STATUS.ACTIVE });
2025-08-11 17:49:52 +00:00
}
2025-08-26 18:55:59 +00:00
public static createInactive(): CustomerStatus {
return new CustomerStatus({ value: CUSTOMER_STATUS.INACTIVE });
2025-08-11 17:49:52 +00:00
}
2025-08-26 18:55:59 +00:00
isActive(): boolean {
return this.props.value === CUSTOMER_STATUS.ACTIVE;
2025-08-11 17:49:52 +00:00
}
2025-09-04 10:02:24 +00:00
getProps(): string {
2025-08-11 17:49:52 +00:00
return this.props.value;
}
toPrimitive() {
2025-09-04 10:02:24 +00:00
return this.getProps();
2025-08-11 17:49:52 +00:00
}
canTransitionTo(nextStatus: string): boolean {
return CustomerStatus.TRANSITIONS[this.props.value].includes(nextStatus);
}
transitionTo(nextStatus: string): Result<CustomerStatus, Error> {
if (!this.canTransitionTo(nextStatus)) {
return Result.fail(
2025-08-26 18:55:59 +00:00
new Error(`Transition not allowed from ${this.props.value} to ${nextStatus}`)
2025-08-11 17:49:52 +00:00
);
}
return CustomerStatus.create(nextStatus);
}
toString(): string {
2025-09-04 10:02:24 +00:00
return this.getProps();
2025-08-11 17:49:52 +00:00
}
}