@tomei/rental
Version:
Tomei Rental Package
925 lines • 45.2 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rental = void 0;
const rental_status_enum_1 = require("../../enum/rental-status.enum");
const rental_repository_1 = require("./rental.repository");
const general_1 = require("@tomei/general");
const config_1 = require("@tomei/config");
const sequelize_1 = require("sequelize");
const activity_history_1 = require("@tomei/activity-history");
const account_type_enum_1 = require("../../enum/account-type.enum");
const joint_hirer_1 = require("../joint-hirer/joint-hirer");
const joint_hirer_entity_1 = require("../../models/joint-hirer.entity");
const agreement_repository_1 = require("../agreement/agreement.repository");
const rentalDb = require("../../database");
const rental_entity_1 = require("../../models/rental.entity");
const joint_hirer_repository_1 = require("../joint-hirer/joint-hirer.repository");
const models_1 = require("../../models");
const agreement_1 = require("../agreement/agreement");
const aggrement_status_enum_1 = require("../../enum/aggrement-status.enum");
const agreement_signature_repository_1 = require("../agreement-signature/agreement-signature.repository");
const agreement_signature_status_enum_1 = require("../../enum/agreement-signature-status.enum");
const hirer_type_enum_1 = require("../../enum/hirer-type.enum");
const agreement_history_repository_1 = require("../agreement-history/agreement-history.repository");
const finance_1 = require("@tomei/finance");
const ItemClassMap_1 = require("../../ClassMappings/ItemClassMap");
class Rental extends general_1.ObjectBase {
get RentalId() {
return this.ObjectId;
}
set RentalId(value) {
this.ObjectId = value;
}
get Status() {
return this._Status;
}
get EscheatmentYN() {
return this._EscheatmentYN;
}
get CreatedById() {
return this._CreatedById;
}
get CreatedAt() {
return this._CreatedAt;
}
get UpdatedById() {
return this._UpdatedById;
}
get UpdatedAt() {
return this._UpdatedAt;
}
setTerminated() {
this._Status = rental_status_enum_1.RentalStatusEnum.TERMINATED;
}
constructor(rentalAttr) {
super();
this.ObjectType = 'Rental';
this.JointHirers = [];
this.Invoices = [];
this._EscheatmentYN = 'N';
if (rentalAttr) {
this.RentalId = rentalAttr.RentalId;
this.CustomerId = rentalAttr.CustomerId;
this.CustomerType = rentalAttr.CustomerType;
this.ItemId = rentalAttr.ItemId;
this.ItemType = rentalAttr.ItemType;
this.PriceId = rentalAttr.PriceId;
this.StartDateTime = rentalAttr.StartDateTime;
this.EndDateTime = rentalAttr.EndDateTime;
this.CancelRemarks = rentalAttr.CancelRemarks;
this.TerminateRemarks = rentalAttr.TerminateRemarks;
this.AgreementNo = rentalAttr.AgreementNo;
this.AccountType = rentalAttr.AccountType;
this._Status = rentalAttr.Status;
this._EscheatmentYN = rentalAttr.EscheatmentYN;
this._CreatedById = rentalAttr.CreatedById;
this._CreatedAt = rentalAttr.CreatedAt;
this._UpdatedById = rentalAttr.UpdatedById;
this._UpdatedAt = rentalAttr.UpdatedAt;
}
}
static init(dbTransaction, rentalId) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (rentalId) {
const rental = yield Rental._Repo.findByPk(rentalId, dbTransaction);
if (rental) {
return new Rental(rental);
}
else {
throw new general_1.ClassError('Rental', 'RentalErrMsg00', 'Rental Not Found');
}
}
return new Rental();
}
catch (error) {
throw new general_1.ClassError('Rental', 'RentalErrMsg00', 'Failed To Initialize Rental');
}
});
}
create(rentalPrice, loginUser, jointHirers, dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'Rental - Create');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'Rental - Create' privilege.");
}
const isItemAvailable = yield Rental.isItemAvailable(this.ItemId, this.ItemType, this.StartDateTime, this.EndDateTime, dbTransaction);
if (!isItemAvailable) {
throw new general_1.ClassError('Rental', 'RentalErrMsg02', 'Rental Item is not available at current date.');
}
yield Rental._AgreementRepo.create({
AgreementNo: this.AgreementNo,
Status: 'Not Generated',
}, {
transaction: dbTransaction,
});
yield Rental._AgreementSignatureRepo.create({
SignatureId: this.createId(),
AgreementNo: this.AgreementNo,
Party: hirer_type_enum_1.HirerTypeEnum.PRIMARY,
PartyId: this.CustomerId,
PartyType: 'Customer',
SignatureStatus: agreement_signature_status_enum_1.AgreementSignatureStatusEnum.PENDING,
SignedAt: null,
VerificationMethod: null,
VerificationJustification: null,
VerifiedById: null,
CreatedById: loginUser.ObjectId,
CreatedAt: new Date(),
UpdatedById: loginUser.ObjectId,
UpdatedAt: new Date(),
}, { transaction: dbTransaction });
if (jointHirers && jointHirers.length > 0) {
for (const jointHirer of jointHirers) {
yield Rental._AgreementSignatureRepo.create({
SignatureId: this.createId(),
AgreementNo: this.AgreementNo,
Party: hirer_type_enum_1.HirerTypeEnum.JOINT,
PartyId: jointHirer.CustomerId,
PartyType: 'Customer',
SignatureStatus: agreement_signature_status_enum_1.AgreementSignatureStatusEnum.PENDING,
SignedAt: null,
VerificationMethod: null,
VerificationJustification: null,
VerifiedById: null,
CreatedById: loginUser.ObjectId,
CreatedAt: new Date(),
UpdatedById: loginUser.ObjectId,
UpdatedAt: new Date(),
}, { transaction: dbTransaction });
}
}
if (!rentalPrice.PriceId) {
const rentalPriceData = yield rentalPrice.create(loginUser, dbTransaction);
this.PriceId = rentalPriceData.PriceId;
}
else {
this.PriceId = rentalPrice.PriceId;
}
this.RentalId = this.createId();
this._Status = rental_status_enum_1.RentalStatusEnum.PENDING_SIGNING;
this._CreatedById = loginUser.ObjectId;
this._UpdatedById = loginUser.ObjectId;
this._CreatedAt = new Date();
this._UpdatedAt = new Date();
const data = {
RentalId: this.RentalId,
CustomerId: this.CustomerId,
CustomerType: this.CustomerType,
ItemId: this.ItemId,
ItemType: this.ItemType,
PriceId: this.PriceId,
StartDateTime: this.StartDateTime,
EndDateTime: this.EndDateTime,
CancelRemarks: this.CancelRemarks,
TerminateRemarks: this.TerminateRemarks,
AgreementNo: this.AgreementNo,
AccountType: this.AccountType,
Status: this.Status,
EscheatmentYN: this.EscheatmentYN,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
yield Rental._Repo.create(data, {
transaction: dbTransaction,
});
if (jointHirers) {
for (let i = 0; i < jointHirers.length; i++) {
jointHirers[i].RentalId = this.RentalId;
yield jointHirers[i].create(loginUser, dbTransaction);
this.JointHirers.push(jointHirers[i]);
}
}
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.CREATE;
activity.Description = 'Add Rental';
activity.EntityType = 'Rental';
activity.EntityId = this.RentalId;
activity.EntityValueBefore = JSON.stringify({});
activity.EntityValueAfter = JSON.stringify(data);
yield activity.create(loginUser.ObjectId, dbTransaction);
return this;
}
catch (error) {
throw error;
}
});
}
static isItemAvailable(itemId, itemType, startDateTime, endDateTime, dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
try {
const rental = yield Rental._Repo.findOne({
where: {
ItemId: itemId,
ItemType: itemType,
StartDateTime: {
[sequelize_1.Op.lte]: endDateTime,
},
EndDateTime: {
[sequelize_1.Op.gte]: startDateTime,
},
},
transaction: dbTransaction,
});
if (!rental) {
return true;
}
if (rental.Status === rental_status_enum_1.RentalStatusEnum.TERMINATED ||
rental.Status === rental_status_enum_1.RentalStatusEnum.CANCELLED) {
return true;
}
return false;
}
catch (error) {
throw error;
}
});
}
static findAll(loginUser, dbTransaction, page, row, search) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
try {
const systemCode = yield config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'Rental - View');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'Rental - View' privilege.");
}
const queryObj = {};
let options = {
transaction: dbTransaction,
order: [['CreatedAt', 'DESC']],
};
if (page && row) {
options = Object.assign(Object.assign({}, options), { limit: row, offset: row * (page - 1) });
}
if (search) {
Object.entries(search).forEach(([key, value]) => {
if (key === 'StartDateTime') {
queryObj[key] = {
[sequelize_1.Op.gte]: value,
};
}
else if (key === 'EndDateTime') {
queryObj[key] = {
[sequelize_1.Op.lte]: value,
};
}
else if (key === 'CustomerId') {
queryObj[key] = {
[sequelize_1.Op.substring]: value,
};
options.include = [
{
model: joint_hirer_entity_1.JointHirerModel,
required: false,
where: {
CustomerId: {
[sequelize_1.Op.substring]: value,
},
},
},
];
}
else {
queryObj[key] = {
[sequelize_1.Op.substring]: value,
};
}
});
if (((_a = options === null || options === void 0 ? void 0 : options.include) === null || _a === void 0 ? void 0 : _a.length) > 1) {
options.include.push({
model: models_1.AgreementModel,
required: false,
});
}
else {
options.include = [
{
model: models_1.AgreementModel,
required: false,
},
];
}
options = Object.assign(Object.assign({}, options), { where: queryObj });
}
return yield Rental._Repo.findAndCountAll(options);
}
catch (err) {
throw err;
}
});
}
static checkActiveByItemId(loginUser, itemId, itemType, dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = yield config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'Rental - View');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'Rental - View' privilege.");
}
const queryObj = {
ItemId: itemId,
ItemType: itemType,
Status: rental_status_enum_1.RentalStatusEnum.ACTIVE,
};
const options = {
transaction: dbTransaction,
where: queryObj,
};
const rental = yield Rental._Repo.findOne(options);
if (rental) {
return true;
}
else {
return false;
}
}
catch (err) {
throw err;
}
});
}
setStartDateTime(startDateTime) {
const startDateTimeObject = new Date(startDateTime);
startDateTimeObject.setHours(0, 0, 0, 0);
if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
throw new general_1.ClassError('Rental', 'RentalErrMsg02', 'StartDateTime cannot be a past datetime.');
}
if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
throw new general_1.ClassError('Rental', 'RentalErrMsg03', 'StartDateTime cannot be more than EndDateTime.');
}
if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
this._Status = rental_status_enum_1.RentalStatusEnum.RESERVED;
}
else {
this._Status = rental_status_enum_1.RentalStatusEnum.ACTIVE;
}
}
periodEndProcess(loginUser, dbTransaction, stockInventory) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = yield config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'Rental – PeriodEndProcess');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg04', "You do not have 'Rental - PeriodEndProcess' privilege.");
}
if (this.AgreementNo === undefined || this.AgreementNo === null) {
throw new general_1.ClassError('Rental', 'RentalErrMsg05', 'Rental must be existing rental.');
}
if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
throw new general_1.ClassError('Rental', 'RentalErrMsg06', 'Rental period is not ending today.');
}
yield stockInventory.setAvailable(loginUser, dbTransaction);
const entityValueBefore = {
RentalId: this.RentalId,
CustomerId: this.CustomerId,
CustomerType: this.CustomerType,
ItemId: this.ItemId,
ItemType: this.ItemType,
PriceId: this.PriceId,
StartDateTime: this.StartDateTime,
EndDateTime: this.EndDateTime,
CancelRemarks: this.CancelRemarks,
TerminateRemarks: this.TerminateRemarks,
AgreementNo: this.AgreementNo,
AccountType: this.AccountType,
Status: this.Status,
EscheatmentYN: this.EscheatmentYN,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
this.setTerminated();
this._UpdatedById = loginUser.ObjectId;
this._UpdatedAt = new Date();
const entityValueAfter = {
RentalId: this.RentalId,
CustomerId: this.CustomerId,
CustomerType: this.CustomerType,
ItemId: this.ItemId,
ItemType: this.ItemType,
PriceId: this.PriceId,
StartDateTime: this.StartDateTime,
EndDateTime: this.EndDateTime,
CancelRemarks: this.CancelRemarks,
TerminateRemarks: this.TerminateRemarks,
AgreementNo: this.AgreementNo,
AccountType: this.AccountType,
Status: this.Status,
EscheatmentYN: this.EscheatmentYN,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.UPDATE;
activity.Description = 'Set Rental as Terminated';
activity.EntityType = 'Rental';
activity.EntityId = this.RentalId;
activity.EntityValueBefore = JSON.stringify(entityValueBefore);
activity.EntityValueAfter = JSON.stringify(entityValueAfter);
yield activity.create(loginUser.ObjectId, dbTransaction);
return this;
}
catch (err) {
throw err;
}
});
}
getCustomerActiveRentals(loginUser, dbTransaction, CustomerId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'Rental - View' privilege.");
}
const query = `
SELECT
r.*
FROM
rental_Rental r
LEFT JOIN
rental_JointHirer jh ON r.RentalId = jh.RentalId
WHERE
r.Status = 'Active'
AND (
r.CustomerId = '${CustomerId}'
OR jh.CustomerId = '${CustomerId}'
)
GROUP BY
r.RentalId
`;
const db = rentalDb.getConnection();
const result = yield db.query(query, {
type: sequelize_1.QueryTypes.SELECT,
transaction: dbTransaction,
model: rental_entity_1.RentalModel,
mapToModel: true,
});
const records = result.map((record) => {
return {
RentalId: record.RentalId,
CustomerId: record.CustomerId,
CustomerType: record.CustomerType,
ItemId: record.ItemId,
ItemType: record.ItemType,
PriceId: record.PriceId,
StartDateTime: record.StartDateTime,
EndDateTime: record.EndDateTime,
CancelRemarks: record.CancelRemarks,
TerminateRemarks: record.TerminateRemarks,
AgreementNo: record.AgreementNo,
AccountType: record.AccountType,
Status: record.Status,
EscheatmentYN: record.EscheatmentYN,
CreatedById: record.CreatedById,
CreatedAt: record.CreatedAt,
UpdatedById: record.UpdatedById,
UpdatedAt: record.UpdatedAt,
};
});
return records;
}
catch (error) {
throw error;
}
});
}
getJointHirers(dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (!this.RentalId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
}
if (this.AccountType !== account_type_enum_1.RentalAccountTypeEnum.JOINT) {
throw new general_1.ClassError('Rental', 'RentalErrMsg07', 'This rental does not have joint hirers.');
}
const jointHirers = yield Rental._JointHirerRepo.findAll({
where: {
RentalId: this.RentalId,
},
transaction: dbTransaction,
});
const jointHirerInstances = Promise.all(jointHirers.map((hirer) => __awaiter(this, void 0, void 0, function* () {
return yield joint_hirer_1.JointHirer.init(hirer.HirerId, dbTransaction);
})));
return jointHirerInstances;
}
catch (error) {
console.error('Error in getJointHirers:', error);
throw error;
}
});
}
getCustomerIds(loginUser, dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'Rental - View' privilege.");
}
if (!this.RentalId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
}
const options = {
where: {
RentalId: this.RentalId,
Status: 'Active',
},
transaction: dbTransaction,
};
const joinHirers = yield Rental._JointHirerRepo.findAll(options);
const customerIds = [this.CustomerId];
for (let i = 0; i < joinHirers.length; i++) {
const jointHirer = joinHirers[i];
customerIds.push(jointHirer.CustomerId);
}
return customerIds;
}
catch (error) {
throw error;
}
});
}
signAgreement(loginUser, party, PartyId, PartyType, dbTransaction, statusAfterSign, method, justification) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'RENTAL_SIGN' privilege.");
}
const agreement = yield agreement_1.Agreement.init(this.AgreementNo, dbTransaction);
if (this.Status !== rental_status_enum_1.RentalStatusEnum.PENDING_SIGNING &&
agreement.Status !== aggrement_status_enum_1.AggrementStatusEnum.GENERATED) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'Rental is not ready to be signed yet.');
}
const signatureList = yield agreement_1.Agreement.getSignatureList(loginUser, this.AgreementNo, dbTransaction);
const customerSignature = signatureList.find((sig) => sig.PartyId === PartyId &&
sig.PartyType === PartyType &&
sig.Party === party &&
sig.SignatureStatus === agreement_signature_status_enum_1.AgreementSignatureStatusEnum.PENDING);
if (!customerSignature) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'Signature is not pending.');
}
const signaturePayload = {
SignatureStatus: agreement_signature_status_enum_1.AgreementSignatureStatusEnum.SIGNED,
SignedAt: new Date(),
UpdatedById: loginUser.ObjectId,
UpdatedAt: new Date(),
VerificationMethod: null,
VerificationJustification: null,
VerifiedById: null,
};
if (method) {
signaturePayload.VerificationMethod = method;
signaturePayload.VerificationJustification = justification;
signaturePayload.VerifiedById = loginUser.ObjectId;
}
yield Rental._AgreementSignatureRepo.update(signaturePayload, {
where: {
AgreementNo: this.AgreementNo,
Party: party,
PartyId: PartyId,
PartyType: PartyType,
},
transaction: dbTransaction,
});
const signatureActivity = new activity_history_1.Activity();
signatureActivity.ActivityId = signatureActivity.createId();
signatureActivity.Action = activity_history_1.ActionEnum.UPDATE;
signatureActivity.Description = 'Update hirer signature';
signatureActivity.EntityType = 'AgreementSignature';
signatureActivity.EntityId = this.AgreementNo;
signatureActivity.EntityValueBefore = JSON.stringify(customerSignature);
signatureActivity.EntityValueAfter = JSON.stringify(signaturePayload);
yield signatureActivity.create(loginUser.ObjectId, dbTransaction);
const updatedSignatureList = yield agreement_1.Agreement.getSignatureList(loginUser, this.AgreementNo, dbTransaction);
const pendingSignatures = updatedSignatureList.filter((sig) => sig.SignatureStatus === 'Pending');
if (pendingSignatures.length > 0) {
return;
}
const entityValueAgreementBefore = {
AgreementNo: agreement.AgreementNo,
Status: agreement.Status,
DateSigned: agreement.DateSigned,
};
const payload = {
DateSigned: new Date(),
Status: aggrement_status_enum_1.AggrementStatusEnum.SIGNED,
};
yield Rental._AgreementRepo.update(payload, {
where: {
AgreementNo: this.AgreementNo,
},
transaction: dbTransaction,
});
const entityValueAgreementAfter = Object.assign({ entityValueAgreementBefore }, payload);
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.UPDATE;
activity.Description = 'Update agreement';
activity.EntityType = 'RentalAgreement';
activity.EntityId = this.AgreementNo;
activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
yield activity.create(loginUser.ObjectId, dbTransaction);
const entityValueRentalBefore = {
RentalId: this.RentalId,
CustomerId: this.CustomerId,
CustomerType: this.CustomerType,
ItemId: this.ItemId,
ItemType: this.ItemType,
PriceId: this.PriceId,
StartDateTime: this.StartDateTime,
EndDateTime: this.EndDateTime,
CancelRemarks: this.CancelRemarks,
TerminateRemarks: this.TerminateRemarks,
AgreementNo: this.AgreementNo,
AccountType: this.AccountType,
Status: this.Status,
EscheatmentYN: this.EscheatmentYN,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
this._Status = statusAfterSign
? statusAfterSign
: rental_status_enum_1.RentalStatusEnum.ACTIVE;
const payloadRental = {
Status: this._Status,
UpdatedById: loginUser.ObjectId,
UpdatedAt: new Date(),
};
yield Rental._Repo.update(payloadRental, {
where: {
RentalId: this.RentalId,
},
transaction: dbTransaction,
});
const entityValueRentalAfter = Object.assign({ entityValueRentalBefore }, payloadRental);
const rentalActivity = new activity_history_1.Activity();
rentalActivity.ActivityId = activity.createId();
rentalActivity.Action = activity_history_1.ActionEnum.UPDATE;
rentalActivity.Description = 'Sign rental agreement';
rentalActivity.EntityType = 'Rental';
rentalActivity.EntityId = this.RentalId;
rentalActivity.EntityValueBefore = JSON.stringify(entityValueRentalBefore);
rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
yield rentalActivity.create(loginUser.ObjectId, dbTransaction);
}
catch (error) {
throw error;
}
});
}
generateAgreement(loginUser, dbTransaction, MediaId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_AGREEMENT_CREATE');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.");
}
const agreement = yield agreement_1.Agreement.init(this.AgreementNo, dbTransaction);
if (!MediaId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg0X', 'MediaId is required.');
}
const EntityValueBefore = agreement;
agreement.Status = aggrement_status_enum_1.AggrementStatusEnum.GENERATED;
agreement.MediaId = MediaId;
yield Rental._AgreementRepo.update({
Status: agreement.Status,
MediaId: agreement.MediaId,
}, {
where: {
AgreementNo: this.AgreementNo,
},
transaction: dbTransaction,
});
const EntityValueAfter = agreement;
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.UPDATE;
activity.Description = 'Generate agreement.';
activity.EntityType = 'RentalAgreement';
activity.EntityId = this.AgreementNo;
activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
yield activity.create(loginUser.ObjectId, dbTransaction);
const agreementHistory = yield Rental._AgreementHistoryRepo.create({
AgreementNo: this.AgreementNo,
MediaId,
ActivityCompleted: 'Agreement Generated',
CreatedAt: new Date(),
}, { transaction: dbTransaction });
const entityValueAfter = agreementHistory.get({ plain: true });
const activityHistory = new activity_history_1.Activity();
activityHistory.ActivityId = activityHistory.createId();
activityHistory.Action = activity_history_1.ActionEnum.CREATE;
activityHistory.Description = 'Generate agreement.';
activityHistory.EntityType = 'RentalAgreementHistory';
activityHistory.EntityId = agreementHistory.HistoryId.toString();
activityHistory.EntityValueBefore = JSON.stringify({});
activityHistory.EntityValueAfter = JSON.stringify(entityValueAfter);
yield activityHistory.create(loginUser.ObjectId, dbTransaction);
}
catch (error) {
throw error;
}
});
}
toJSON() {
return {
RentalId: this.RentalId,
CustomerId: this.CustomerId,
CustomerType: this.CustomerType,
ItemId: this.ItemId,
ItemType: this.ItemType,
PriceId: this.PriceId,
StartDateTime: this.StartDateTime,
EndDateTime: this.EndDateTime,
Status: this.Status,
CancelRemarks: this.CancelRemarks,
TerminateRemarks: this.TerminateRemarks,
EscheatmentYN: this.EscheatmentYN,
AgreementNo: this.AgreementNo,
AccountType: this.AccountType,
CreatedById: this.CreatedById,
CreatedAt: this.CreatedAt,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
};
}
getInvoices(loginUser, dbTransaction, accountingSystem) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW_INVOICE');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'RENTAL_VIEW_INVOICE' privilege.");
}
if (!this.ObjectId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'ObjectId is missing.');
}
if (this.Invoices.length > 0) {
return this.Invoices;
}
const search = {
DocType: finance_1.DocType.INVOICE,
RelatedObjectId: this.ObjectId,
RelatedObjectType: this.ObjectType,
};
const documents = yield finance_1.Document.findAll(loginUser, dbTransaction, undefined, undefined, search, undefined, accountingSystem);
this.Invoices = documents.rows.map((doc) => {
const document = new finance_1.Document(dbTransaction, doc);
return document;
});
return this.Invoices;
}
catch (error) {
throw error;
}
});
}
getItem(dbTransaction) {
return __awaiter(this, void 0, void 0, function* () {
if (this.Item) {
return this.Item;
}
else {
const ItemClass = ItemClassMap_1.ItemClassMap[this.ItemType];
if (!ItemClass || typeof ItemClass.init !== 'function') {
throw new Error(`Invalid or unregistered ItemType: ${this.ItemType}`);
}
ItemClass._Repo = ItemClass._Repo || ItemClass.getRepo();
if (!ItemClass._Repo) {
throw new Error(`ItemType ${this.ItemType} does not have a repository.`);
}
const itemInstance = yield ItemClass.init(this.ItemId, dbTransaction);
if (!itemInstance) {
throw new Error(`${this.ItemType} not found with ID ${this.ItemId}`);
}
this.Item = itemInstance;
if (typeof this.Item.setAvailable !== 'function') {
throw new Error(`${this.ItemType} does not implement setAvailable()`);
}
return this.Item;
}
});
}
cancel(loginUser, dbTransaction, remarks) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'RENTAL_CANCEL');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'RENTAL_CANCEL' privilege.");
}
if (!this.ObjectId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'Rental not found. Rental Id is empty.');
}
if (!remarks) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'Cancellation remarks is required.');
}
const entityValueBefore = this.toJSON();
this._Status = rental_status_enum_1.RentalStatusEnum.CANCELLED;
this.CancelRemarks = remarks;
this._UpdatedById = loginUser.ObjectId;
this._UpdatedAt = new Date();
yield Rental._Repo.update({
Status: this.Status,
CancelRemarks: this.CancelRemarks,
UpdatedById: this.UpdatedById,
UpdatedAt: this.UpdatedAt,
}, {
where: {
RentalId: this.RentalId,
},
transaction: dbTransaction,
});
const item = yield this.getItem(dbTransaction);
yield item.setAvailable(loginUser, dbTransaction);
const entityValueAfter = this.toJSON();
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.UPDATE;
activity.Description = 'Rental Cancellation';
activity.EntityType = this.ObjectType;
activity.EntityId = this.ObjectId;
activity.EntityValueBefore = JSON.stringify(entityValueBefore);
activity.EntityValueAfter = JSON.stringify(entityValueAfter);
yield activity.create(loginUser.ObjectId, dbTransaction);
return this;
}
catch (error) {
throw error;
}
});
}
update(loginUser, dbTransaction, updates) {
return __awaiter(this, void 0, void 0, function* () {
try {
const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'RENTAL_UPDATE');
if (!isPrivileged) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', "You do not have 'RENTAL_UPDATE' privilege.");
}
if (!this.ObjectId) {
throw new general_1.ClassError('Rental', 'RentalErrMsg01', 'Rental not found. Rental Id is empty.');
}
const entityValueBefore = this.toJSON();
yield Rental._Repo.update(updates, {
where: {
RentalId: this.RentalId,
},
transaction: dbTransaction,
});
Object.assign(this, updates);
this._UpdatedById = loginUser.ObjectId;
this._UpdatedAt = new Date();
const entityValueAfter = this.toJSON();
const activity = new activity_history_1.Activity();
activity.ActivityId = activity.createId();
activity.Action = activity_history_1.ActionEnum.UPDATE;
activity.Description = 'Update Rental';
activity.EntityType = this.ObjectType;
activity.EntityId = this.ObjectId;
activity.EntityValueBefore = JSON.stringify(entityValueBefore);
activity.EntityValueAfter = JSON.stringify(entityValueAfter);
yield activity.create(loginUser.ObjectId, dbTransaction);
return this;
}
catch (error) {
throw error;
}
});
}
}
exports.Rental = Rental;
Rental._Repo = new rental_repository_1.RentalRepository();
Rental._AgreementRepo = new agreement_repository_1.AgreementRepository();
Rental._JointHirerRepo = new joint_hirer_repository_1.JointHirerRepository();
Rental._AgreementSignatureRepo = new agreement_signature_repository_1.AgreementSignatureRepository();
Rental._AgreementHistoryRepo = new agreement_history_repository_1.AgreementHistoryRepository();
//# sourceMappingURL=rental.js.map