synt_backend
Version:
Synt light-weight node backend service
99 lines (98 loc) • 3.01 kB
JavaScript
const { Model } = require("sequelize");
const SequelizeTokenify = require("sequelize-tokenify");
function padLeadingZeros(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
module.exports = (sequelize, DataTypes) => {
class Incident extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Incident.belongsTo(models.VME);
Incident.belongsTo(models.User);
Incident.belongsTo(models.ReportType);
Incident.belongsTo(models.Supplier); // new supplier (known aannemer)
Incident.belongsToMany(models.Lot, { through: "IncidentLot" });
Incident.hasMany(models.Image);
Incident.hasMany(models.IncidentComment);
}
}
Incident.init(
{
reference: {
type: DataTypes.VIRTUAL,
get() {
return `REF${padLeadingZeros(this.getDataValue("id"), 3)}`;
},
},
token: {
type: DataTypes.STRING,
unique: true,
},
report_description: DataTypes.STRING,
is_urgent: DataTypes.BOOLEAN,
has_tried_to_call: DataTypes.BOOLEAN,
has_called: DataTypes.BOOLEAN,
is_covered: DataTypes.BOOLEAN,
call_description: DataTypes.STRING,
solved_at: DataTypes.DATE,
declaration: {
type: DataTypes.TEXT,
get() {
return typeof this.getDataValue("declaration") === "string"
? JSON.parse(this.getDataValue("declaration"))
: this.getDataValue("declaration");
},
set(value) {
this.setDataValue(
"declaration",
typeof value === "string" ? value : JSON.stringify(value)
);
},
}, // keypoint
case: {
type: DataTypes.TEXT,
get() {
return typeof this.getDataValue("case") === "string"
? JSON.parse(this.getDataValue("case"))
: this.getDataValue("case");
},
set(value) {
this.setDataValue(
"case",
typeof value === "string" ? value : JSON.stringify(value)
);
},
}, // keypoint
case_id: DataTypes.INTEGER, // keypoint
},
{
sequelize,
paranoid: true,
modelName: "Incident",
}
);
Incident.prototype.getReference = async function () {
let ReportType = await sequelize.models.ReportType.findOne({
where: { id: this.getDataValue("ReportTypeId") },
});
let prepend = "REF";
if (ReportType) {
prepend = ReportType.name.toUpperCase().replaceAll(" ", "_");
}
console.log(`${prepend}${padLeadingZeros(this.getDataValue("id"), 3)}`);
return `${prepend}${padLeadingZeros(this.getDataValue("id"), 3)}`;
};
SequelizeTokenify.tokenify(Incident, {
field: "token",
length: 6,
});
return Incident;
};
;