@tasolutions/express-core
Version:
All libs for express
289 lines (249 loc) • 11.4 kB
JavaScript
const queryUtil = require('../../../../utils/query.util');
const Response = require('../../../../utils/response');
const { httpStatus } = require('../../../../utils/httpStatus');
const { genFile } = require('../helpers/document');
const { DocumentTemplate, DocumentMedia } = require('../models');
const { flattenObject, calculateYearDifferenceForFlattenedData } = require('../utils/document');
const { uploadFile } = require('../../../../utils/upload');
module.exports = {
/**
* Export document theo record ID và template ID
* GET /v0/examples/document/:_id/templates/:_templateId/export?type=PDF
*/
exportByRecordAndTemplate: async (req, res, Collection) => {
try {
const { _id, _templateId } = req.params;
const { type = 'PDF' } = req.query;
// Validate type
if (!['PDF', 'WORD'].includes(type.toUpperCase())) {
return Response.error(res, 'Type must be PDF or WORD', httpStatus.BAD_REQUEST);
}
// Tìm record
const record = await Collection.findById(_id);
if (!record) {
return Response.error(res, `Record not found with id=${_id}`, httpStatus.NOT_FOUND);
}
// Tìm template
const documentTemplate = await DocumentTemplate.findById(_templateId);
if (!documentTemplate) {
return Response.error(res, `Template not found with id=${_templateId}`, httpStatus.NOT_FOUND);
}
// Kiểm tra template có thuộc collection này không
if (documentTemplate.collection_name !== Collection.modelName) {
return Response.error(res, 'Template does not belong to this collection', httpStatus.BAD_REQUEST);
}
// Tạo file
const collection_name = Collection.modelName;
const qrFields = documentTemplate.qrcode_fields || [];
const barcodeFields = documentTemplate.barcode_fields || [];
const results = await genFile(
documentTemplate,
collection_name,
record.toObject(),
qrFields,
barcodeFields,
{},
Collection
);
// Lưu vào DocumentMedia
const documentMedia = new DocumentMedia({
document_template_id: _templateId,
collection_name: collection_name,
ref_id: _id,
name: `${record.name || record._id}_${documentTemplate.name}`,
file_url: type.toUpperCase() === 'PDF' ? results.pdf_url : results.doc_url,
file_type: type.toUpperCase() === 'PDF' ? 'PDF' : 'DOCX'
});
await documentMedia.save();
return Response.success(res, {
file_url: documentMedia.file_url,
file_type: documentMedia.file_type,
media_id: documentMedia._id
}, 'Export document successfully');
} catch (e) {
console.error('Export by record and template error:', e);
return Response.error(res, e.message || 'Lỗi khi export document');
}
},
/**
* Export document theo record ID và template key
* GET /v0/examples/:_id/templates/key/:_templateKey/export?type=PDF
*/
exportByRecordAndKey: async (req, res, Collection) => {
try {
const { _id, _templateKey } = req.params;
const { type = 'PDF' } = req.query;
// Validate type
if (!['PDF', 'WORD'].includes(type.toUpperCase())) {
return Response.error(res, 'Type must be PDF or WORD', httpStatus.BAD_REQUEST);
}
// Tìm record
const record = await Collection.findById(_id);
if (!record) {
return Response.error(res, `Record not found with id=${_id}`, httpStatus.NOT_FOUND);
}
// Tìm template theo key (name)
const documentTemplate = await DocumentTemplate.findOne({
collection_name: Collection.modelName,
name: _templateKey
});
if (!documentTemplate) {
return Response.error(res, `Template not found with key=${_templateKey}`, httpStatus.NOT_FOUND);
}
// Tạo file
const collection_name = Collection.modelName;
const qrFields = documentTemplate.qrcode_fields || [];
const barcodeFields = documentTemplate.barcode_fields || [];
const results = await genFile(
documentTemplate,
collection_name,
record.toObject(),
qrFields,
barcodeFields,
{},
Collection
);
// Lưu vào DocumentMedia
const documentMedia = new DocumentMedia({
document_template_id: documentTemplate._id,
collection_name: collection_name,
ref_id: _id,
name: `${record.name || record._id}_${documentTemplate.name}`,
file_url: type.toUpperCase() === 'PDF' ? results.pdf_url : results.doc_url,
file_type: type.toUpperCase() === 'PDF' ? 'PDF' : 'DOCX'
});
await documentMedia.save();
return Response.success(res, {
file_url: documentMedia.file_url,
file_type: documentMedia.file_type,
media_id: documentMedia._id
}, 'Export document successfully');
} catch (e) {
console.error('Export by record and key error:', e);
return Response.error(res, e.message || 'Lỗi khi export document');
}
},
/**
* Kiểm tra và trả về file URL nếu đã tồn tại
*/
getExistingFile: async (req, res, Collection) => {
try {
const { _id, _templateId, _templateKey, _key } = req.params;
const { type = 'PDF' } = req.query;
let templateId = _templateId;
// Nếu có _templateKey, tìm template theo key
if (_templateKey) {
const template = await DocumentTemplate.findOne({
collection_name: Collection.modelName,
name: _templateKey
});
if (!template) {
return Response.error(res, `Template not found with key=${_templateKey}`, httpStatus.NOT_FOUND);
}
templateId = template._id;
}
// Fallback cho _key (backward compatibility)
else if (_key) {
const template = await DocumentTemplate.findOne({
collection_name: Collection.modelName,
name: _key
});
if (!template) {
return Response.error(res, `Template not found with key=${_key}`, httpStatus.NOT_FOUND);
}
templateId = template._id;
}
// Tìm file đã tồn tại
const existingMedia = await DocumentMedia.findOne({
document_template_id: templateId,
collection_name: Collection.modelName,
ref_id: _id,
file_type: type.toUpperCase()
});
if (existingMedia) {
return Response.success(res, {
file_url: existingMedia.file_url,
file_type: existingMedia.file_type,
media_id: existingMedia._id,
cached: true
}, 'File already exists');
}
return Response.error(res, 'File not found', httpStatus.NOT_FOUND);
} catch (e) {
console.error('Get existing file error:', e);
return Response.error(res, e.message || 'Lỗi khi kiểm tra file');
}
},
/**
* Export document theo record ID và templateKeyOrId (gộp)
* GET /v0/:collection/:_id/templates/:_templateKeyOrId/export
*/
documentExportByRecordAndKeyOrId: async (req, res, Collection) => {
try {
const { _id, _templateKeyOrId } = req.params;
const { type = 'PDF' } = req.query;
// Validate type
if (!['PDF', 'WORD'].includes(type.toUpperCase())) {
return Response.error(res, 'Type must be PDF or WORD', httpStatus.BAD_REQUEST);
}
// Tìm record
const record = await Collection.findById(_id);
if (!record) {
return Response.error(res, `Record not found with id=${_id}`, httpStatus.NOT_FOUND);
}
// Xác định là ObjectId hay key
let documentTemplate = null;
if (/^[a-fA-F0-9]{24}$/.test(_templateKeyOrId)) {
// Nếu là ObjectId
documentTemplate = await DocumentTemplate.findById(_templateKeyOrId);
if (!documentTemplate) {
return Response.error(res, `Template not found with id=${_templateKeyOrId}`, httpStatus.NOT_FOUND);
}
} else {
// Nếu là key
documentTemplate = await DocumentTemplate.findOne({
collection_name: Collection.modelName,
key: _templateKeyOrId
});
if (!documentTemplate) {
return Response.error(res, `Template not found with key=${_templateKeyOrId}`, httpStatus.NOT_FOUND);
}
}
// Kiểm tra template có thuộc collection này không
if (documentTemplate.collection_name !== Collection.modelName) {
return Response.error(res, 'Template does not belong to this collection', httpStatus.BAD_REQUEST);
}
// Tạo file
const collection_name = Collection.modelName;
const qrFields = documentTemplate.qrcode_fields || [];
const barcodeFields = documentTemplate.barcode_fields || [];
const results = await genFile(
documentTemplate,
collection_name,
record.toObject(),
qrFields,
barcodeFields,
{},
Collection
);
// Lưu vào DocumentMedia
const documentMedia = new DocumentMedia({
document_template_id: documentTemplate._id,
collection_name: collection_name,
ref_id: _id,
name: `${record.name || record._id}_${documentTemplate.name}`,
file_url: type.toUpperCase() === 'PDF' ? results.pdf_url : results.doc_url,
file_type: type.toUpperCase() === 'PDF' ? 'PDF' : 'DOCX'
});
await documentMedia.save();
return Response.success(res, {
file_url: documentMedia.file_url,
file_type: documentMedia.file_type,
media_id: documentMedia._id
}, 'Export document successfully');
} catch (e) {
console.error('Export by record and keyOrId error:', e);
return Response.error(res, e.message || 'Lỗi khi export document');
}
}
};