UNPKG

@opengis/admin

Version:

This project Softpro Admin

100 lines (81 loc) 2.81 kB
import path from 'path'; import { getMeta, dataInsert, dataUpdate, applyHook, uploadMultiPart, } from '@opengis/fastify-table/utils.js'; const tableList = { comment: 'crm.communications', gallery: 'crm.files', checklist: 'crm.checklists', }; const pkList = { comment: 'communication_id', checklist: 'checklist_id', gallery: 'file_id', }; const galleryExtList = ['png', 'svg', 'jpg', 'jpeg', 'gif', 'mp4', 'mov', 'avi']; export default async function widgetSet(req, reply) { const { pg, params = {}, session = {}, headers = {}, body = {}, user = {}, unittest, } = req; const { type, id, objectid } = params; if (!['comment', 'checklist', 'file', 'gallery'].includes(type)) { return reply.status(400).send('param type not valid'); } if (!objectid) { return reply.status(400).send('not enough params: id'); } const table = tableList[type]; // dsadasdad if (['gallery', 'file'].includes(type) && headers['content-type']?.split?.(';')?.shift?.() === "multipart/form-data") { const file = await uploadMultiPart(req); const extName = path.extname(file.filepath).slice(1).toLowerCase(); const data = { uploaded_name: file?.originalFilename?.toLocaleLowerCase()?.replace(/'/g, '\'\''), file_path: file?.relativeFilepath?.replace(/\\/g, '/'), ext: extName, size: file?.size, file_status: 1, uid: user?.uid || 1, entity_id: objectid, }; if (type === 'gallery' && !galleryExtList.includes(extName.toLowerCase())) { return reply.status(400).send('invalid file extension'); } const { rows = [] } = await dataInsert({ pg, table: 'crm.files', data, uid: user?.uid, }); if (type === 'gallery') { await pg.query(`update crm.files set ismain=true where entity_id=$1 and file_id=$2 and (select count(*) = 0 from crm.files where entity_id=$1 and ismain)`, [objectid, rows[0]?.file_id]); } return { rowCount: 1, data: 'ok', command: 'UPLOAD', id: rows[0]?.file_id, entity_id: rows[0]?.entity_id, }; } const { pk } = await getMeta({ pg, table }); if (!pk) { return reply.status(404).send('table not found'); } const data = { ...body, uid: user?.uid, entity_id: objectid }; await applyHook('onWidgetSet', { pg, link: req.path, id, objectid, session, type, payload: data, }); const result = id ? await dataUpdate({ pg, table, data, id, uid: user?.uid, }) : await dataInsert({ pg, table, data, uid: user?.uid, }); return { rowCount: result.rowCount, data: 'ok', command: result.command, id: result.rows?.[0]?.[pkList[type]] || result?.[pkList[type]], }; }