const { DataTypes } = require('sequelize'); const sequelize = require('../config/database'); const Material = sequelize.define('Material', { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, code: { type: DataTypes.STRING, allowNull: false, unique: true, comment: '物资编号' }, name: { type: DataTypes.STRING, allowNull: false, comment: '物资名称' }, category: { type: DataTypes.STRING, allowNull: false, comment: '物资类别', validate: { isIn: [['feed', 'medicine', 'equipment', 'other']] } }, unit: { type: DataTypes.STRING, allowNull: false, comment: '单位' }, stockQuantity: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: '库存数量' }, warningQuantity: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: '预警数量' }, status: { type: DataTypes.STRING, allowNull: false, defaultValue: 'normal', comment: '状态', validate: { isIn: [['normal', 'low', 'out']] } }, supplier: { type: DataTypes.STRING, allowNull: true, comment: '供应商' }, remark: { type: DataTypes.TEXT, allowNull: true, comment: '备注' }, updateTime: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW, comment: '更新时间' } }, { tableName: 'materials', timestamps: true, paranoid: true, underscored: true, freezeTableName: true }); // 钩子函数,在保存前更新状态和更新时间 Material.beforeSave((material) => { material.updateTime = new Date(); // 根据库存数量和预警数量更新状态 if (material.stockQuantity <= 0) { material.status = 'out'; } else if (material.stockQuantity <= material.warningQuantity) { material.status = 'low'; } else { material.status = 'normal'; } }); module.exports = Material;