first commit
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Copyright (c) 2026 Niolla
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is proprietary and confidential.
|
||||
* Unauthorized copying, modification, distribution, or use
|
||||
* of this file, via any medium, is strictly prohibited.
|
||||
*/
|
||||
|
||||
// app/utils/document.util.js
|
||||
|
||||
const { Document } = require("../models");
|
||||
const { generateId, generateDocumentReferenceNo } = require("./idGen.util");
|
||||
const {log} = require("./consoleLog.utill");
|
||||
|
||||
const DOCUMENT_STATUS = {
|
||||
DRAFT: "DRAFT",
|
||||
FINAL: "FINAL",
|
||||
};
|
||||
|
||||
const validateStatus = (status) => {
|
||||
if (!Object.values(DOCUMENT_STATUS).includes(status)) {
|
||||
throw new Error(
|
||||
`Invalid status "${status}". Allowed values: ${Object.values(
|
||||
DOCUMENT_STATUS,
|
||||
).join(", ")}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const createDraftDocument = async (document, doc_data) => {
|
||||
log("Creating draft document data...");
|
||||
log("Incoming document data:", JSON.stringify(doc_data, null, 2));
|
||||
const result = await Document.create({
|
||||
doc_id: generateId(),
|
||||
reference_no: doc_data.reference_no || "N/A",
|
||||
doc_type: document,
|
||||
data: doc_data,
|
||||
status: DOCUMENT_STATUS.DRAFT,
|
||||
});
|
||||
|
||||
log("Draft document created with ID:", result.doc_id);
|
||||
|
||||
return result;
|
||||
|
||||
};
|
||||
|
||||
const finalizeDocument = async (document, doc_data) => {
|
||||
if (!doc_data.doc_id) {
|
||||
throw new Error("Document data ID is required for FINAL status.");
|
||||
}
|
||||
|
||||
const [updatedRows] = await Document.update(
|
||||
{
|
||||
reference_no: doc_data.reference_no || "N/A",
|
||||
doc_type: document,
|
||||
data: doc_data,
|
||||
status: DOCUMENT_STATUS.FINAL,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
doc_id: doc_data.doc_id,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (updatedRows === 0) {
|
||||
throw new Error("Document data not found or already updated.");
|
||||
}
|
||||
|
||||
return await Document.findOne({
|
||||
where: {
|
||||
doc_id: doc_data.doc_id,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createDocumentData = async (document, doc_data, status) => {
|
||||
try {
|
||||
validateStatus(status);
|
||||
|
||||
switch (status) {
|
||||
case DOCUMENT_STATUS.DRAFT:
|
||||
return await createDraftDocument(document, doc_data);
|
||||
|
||||
case DOCUMENT_STATUS.FINAL:
|
||||
return await finalizeDocument(document, doc_data);
|
||||
|
||||
default:
|
||||
throw new Error(`Unhandled document status: ${status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("❌ Document data operation failed:", error.message);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
createDocumentData,
|
||||
DOCUMENT_STATUS,
|
||||
};
|
||||
Reference in New Issue
Block a user