Uecko_ERP/modules/customer-invoices/src/api/infrastructure/sequelize/models/customer-invoice-tax.model.ts

135 lines
3.1 KiB
TypeScript

import {
DataTypes,
type InferAttributes,
type InferCreationAttributes,
Model,
type NonAttribute,
type Sequelize,
} from "sequelize";
import type { CustomerInvoice } from "../../../domain";
export type CustomerInvoiceTaxCreationAttributes = InferCreationAttributes<
CustomerInvoiceTaxModel,
{ omit: "invoice" }
>;
export class CustomerInvoiceTaxModel extends Model<
InferAttributes<CustomerInvoiceTaxModel>,
InferCreationAttributes<CustomerInvoiceTaxModel>
> {
declare tax_id: string;
declare invoice_id: string;
declare tax_code: string; //"iva_21"
// Taxable amount (base imponible) // 100,00 €
declare taxable_amount_value: number;
declare taxable_amount_scale: number;
// Total tax amount / taxes total // 21,00 €
declare taxes_amount_value: number;
declare taxes_amount_scale: number;
// Relaciones
declare invoice: NonAttribute<CustomerInvoice>;
static associate(database: Sequelize) {
const models = database.models;
const requiredModels = ["CustomerInvoiceModel"];
// Comprobamos que los modelos existan
for (const name of requiredModels) {
if (!models[name]) {
throw new Error(`[CustomerInvoiceTaxModel.associate] Missing model: ${name}`);
}
}
const { CustomerInvoiceModel } = database.models;
CustomerInvoiceTaxModel.belongsTo(CustomerInvoiceModel, {
as: "invoice",
foreignKey: "invoice_id",
targetKey: "id",
onDelete: "CASCADE",
onUpdate: "CASCADE",
});
}
static hooks(_database: Sequelize) {
//
}
}
export default (database: Sequelize) => {
CustomerInvoiceTaxModel.init(
{
tax_id: {
type: DataTypes.UUID,
primaryKey: true,
},
invoice_id: {
type: DataTypes.UUID,
allowNull: false,
},
tax_code: {
type: new DataTypes.STRING(40), // Sugerido por IA
allowNull: false,
},
taxable_amount_value: {
type: new DataTypes.BIGINT(), // importante: evita problemas de precisión con valores grandes
allowNull: false,
defaultValue: 0,
},
taxable_amount_scale: {
type: new DataTypes.SMALLINT(),
allowNull: false,
defaultValue: 2,
},
taxes_amount_value: {
type: new DataTypes.BIGINT(), // importante: evita problemas de precisión con valores grandes
allowNull: false,
defaultValue: 0,
},
taxes_amount_scale: {
type: new DataTypes.SMALLINT(),
allowNull: false,
defaultValue: 2,
},
},
{
sequelize: database,
modelName: "CustomerInvoiceTaxModel",
tableName: "customer_invoice_taxes",
underscored: true,
indexes: [
{
name: "invoice_id_idx",
fields: ["invoice_id"],
},
{
name: "invoice_tax_code_unique",
fields: ["invoice_id", "tax_code"],
unique: true, // cada impuesto aparece como máximo una vez
},
],
whereMergeStrategy: "and", // <- cómo tratar el merge de un scope
defaultScope: {},
scopes: {},
}
);
return CustomerInvoiceTaxModel;
};