Revert to version c0ba6a1

This commit is contained in:
Flatlogic Bot 2025-07-02 18:10:07 +00:00
parent 9fa9f88c01
commit 638e0fe130
20 changed files with 45 additions and 283 deletions

5
.gitignore vendored
View File

@ -1,8 +1,3 @@
node_modules/ node_modules/
*/node_modules/ */node_modules/
*/build/ */build/
**/node_modules/
**/build/
.DS_Store
.env

File diff suppressed because one or more lines are too long

View File

@ -23,11 +23,6 @@ module.exports = class DocumentsDBApi {
document_type: data.document_type document_type: data.document_type
|| ||
null
,
fileurl: data.fileurl
||
null null
, ,
@ -57,11 +52,6 @@ module.exports = class DocumentsDBApi {
document_type: item.document_type document_type: item.document_type
|| ||
null null
,
fileurl: item.fileurl
||
null
, ,
importHash: item.importHash || null, importHash: item.importHash || null,
@ -88,8 +78,6 @@ module.exports = class DocumentsDBApi {
if (data.document_type !== undefined) updatePayload.document_type = data.document_type; if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.fileurl !== undefined) updatePayload.fileurl = data.fileurl;
updatePayload.updatedById = currentUser.id; updatePayload.updatedById = currentUser.id;
await documents.update(updatePayload, {transaction}); await documents.update(updatePayload, {transaction});
@ -196,17 +184,6 @@ module.exports = class DocumentsDBApi {
}; };
} }
if (filter.fileurl) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'fileurl',
filter.fileurl,
),
};
}
if (filter.active !== undefined) { if (filter.active !== undefined) {
where = { where = {
...where, ...where,

View File

@ -1,54 +0,0 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'documents',
'fileurl',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction }
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn(
'documents',
'fileurl',
{ transaction }
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
}
};

View File

@ -38,11 +38,6 @@ document_type: {
}, },
fileurl: {
type: DataTypes.TEXT,
},
importHash: { importHash: {
type: DataTypes.STRING(255), type: DataTypes.STRING(255),
allowNull: true, allowNull: true,

View File

@ -79,8 +79,6 @@ require('./auth/auth');
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
app.use('/api/auth', authRoutes); app.use('/api/auth', authRoutes);
app.enable('trust proxy'); app.enable('trust proxy');

View File

@ -1,34 +1,11 @@
const util = require('util'); const util = require('util');
const Multer = require('multer'); const Multer = require('multer');
const path = require('path');
const fs = require('fs');
const maxSize = 10 * 1024 * 1024; const maxSize = 10 * 1024 * 1024;
// Ensure uploads directory exists
const uploadDir = path.join(__dirname, '../../uploads/documents');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// Configure disk storage
const storage = Multer.diskStorage({
destination: (req, file, cb) => cb(null, uploadDir),
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
const base = path.basename(file.originalname, ext);
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
cb(null, `${base}-${uniqueSuffix}${ext}`);
},
});
// Create multer instance
let processFile = Multer({ let processFile = Multer({
storage, storage: Multer.memoryStorage(),
limits: { fileSize: maxSize }, limits: { fileSize: maxSize },
}).single('file'); }).single("file");
// Promisify for async/await
let processFileMiddleware = util.promisify(processFile); let processFileMiddleware = util.promisify(processFile);
module.exports = processFileMiddleware; module.exports = processFileMiddleware;

View File

@ -3,7 +3,6 @@ const express = require('express');
const DocumentsService = require('../services/documents'); const DocumentsService = require('../services/documents');
const DocumentsDBApi = require('../db/api/documents'); const DocumentsDBApi = require('../db/api/documents');
const processFile = require('../middlewares/upload');
const wrapAsync = require('../helpers').wrapAsync; const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router(); const router = express.Router();
@ -21,9 +20,6 @@ const { parse } = require('json2csv');
* title: * title:
* type: string * type: string
* default: title * default: title
* fileurl:
* type: string
* default: fileurl
* *
*/ */
@ -67,28 +63,14 @@ const { parse } = require('json2csv');
* description: Invalid input data * description: Invalid input data
* 500: * 500:
* description: Some server error * description: Some server error
router.post('/', processFile, wrapAsync(async (req, res) => { */
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`; const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer); const link = new URL(referer);
// Parse data from multipart/form-data or JSON await DocumentsService.create(req.body.data, req.currentUser, true, link.host);
let data = {};
if (req.body.data) {
data = req.body.data;
} else {
data = {
title: req.body.title,
document_type: req.body.document_type,
};
}
// Attach file URL if file was uploaded
if (req.file) {
data.fileurl = `/uploads/documents/${req.file.filename}`;
}
await DocumentsService.create(data, req.currentUser, true, link.host);
const payload = true; const payload = true;
res.status(200).send(payload); res.status(200).send(payload);
})); }));
}));
/** /**
* @swagger * @swagger
@ -166,24 +148,11 @@ router.post('/bulk-import', wrapAsync(async (req, res) => {
* required: * required:
* - id * - id
* responses: * responses:
router.put('/:id', processFile, wrapAsync(async (req, res) => { * 200:
// Parse data from multipart/form-data or JSON * description: The item data was successfully updated
let data = {}; * content:
if (req.body.data) { * application/json:
data = req.body.data; * schema:
} else {
data = {
title: req.body.title,
document_type: req.body.document_type,
};
}
// Attach file URL if file was uploaded
if (req.file) {
data.fileurl = `/uploads/${req.file.filename}`;
data.fileurl = `/uploads/documents/${req.file.filename}`;
await DocumentsService.update(data, req.params.id, req.currentUser);
res.status(200).send(true);
}));
* $ref: "#/components/schemas/Documents" * $ref: "#/components/schemas/Documents"
* 400: * 400:
* description: Invalid ID supplied * description: Invalid ID supplied
@ -194,6 +163,11 @@ router.put('/:id', processFile, wrapAsync(async (req, res) => {
* 500: * 500:
* description: Some server error * description: Some server error
*/ */
router.put('/:id', wrapAsync(async (req, res) => {
await DocumentsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/** /**
* @swagger * @swagger
@ -303,7 +277,7 @@ router.get('/', wrapAsync(async (req, res) => {
req.query, { currentUser } req.query, { currentUser }
); );
if (filetype && filetype === 'csv') { if (filetype && filetype === 'csv') {
const fields = ['id','title','fileurl', const fields = ['id','title',
]; ];
const opts = { fields }; const opts = { fields };

View File

@ -67,8 +67,6 @@ module.exports = class SearchService {
"title", "title",
"fileurl",
], ],
"inspections": [ "inspections": [

View File

@ -1 +0,0 @@
{}

View File

@ -88,15 +88,6 @@ const CardDocuments = ({
</dd> </dd>
</div> </div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className='text-gray-500 dark:text-dark-600'>Fileurl</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{ item.fileurl }
</div>
</dd>
</div>
</dl> </dl>
</li> </li>
))} ))}

View File

@ -50,11 +50,6 @@ const ListDocuments = ({ documents, loading, onDelete, currentPage, numPages, on
<p className={'line-clamp-2'}>{ item.file }</p> <p className={'line-clamp-2'}>{ item.file }</p>
</div> </div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500'}>Fileurl</p>
<p className={'line-clamp-2'}>{ item.fileurl }</p>
</div>
</Link> </Link>
<ListActionsPopover <ListActionsPopover
onDelete={onDelete} onDelete={onDelete}

View File

@ -65,21 +65,6 @@ export const loadColumns = async (
editable: true, editable: true,
}, },
{
field: 'fileurl',
headerName: 'File',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
renderCell: (params: GridValueGetterParams) =>
params.value ? (
<a href={params.value as string} download>
Download
</a>
) : null,
},
{ {
field: 'actions', field: 'actions',

View File

@ -36,8 +36,6 @@ const EditDocuments = () => {
document_type: '', document_type: '',
'fileurl': '',
} }
const [initialValues, setInitialValues] = useState(initVals) const [initialValues, setInitialValues] = useState(initVals)
@ -113,15 +111,6 @@ const EditDocuments = () => {
</Field> </Field>
</FormField> </FormField>
<FormField
label="Fileurl"
>
<Field
name="fileurl"
placeholder="Fileurl"
/>
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type="submit" color="info" label="Submit" /> <BaseButton type="submit" color="info" label="Submit" />

View File

@ -37,12 +37,8 @@ const EditDocumentsPage = () => {
document_type: '', document_type: '',
'fileurl': '',
} }
const [initialValues, setInitialValues] = useState(initVals) const [initialValues, setInitialValues] = useState(initVals)
const [file, setFile] = useState<File | null>(null)
const { documents } = useAppSelector((state) => state.documents) const { documents } = useAppSelector((state) => state.documents)
@ -65,13 +61,10 @@ const EditDocumentsPage = () => {
setInitialValues(newInitialVal); setInitialValues(newInitialVal);
} }
}, [documents]) }, [documents])
const handleSubmit = async (data) => { const handleSubmit = async (data) => {
const formData = new FormData(); await dispatch(update({ id: id, data }))
formData.append('title', data.title); await router.push('/documents/documents-list')
formData.append('document_type', data.document_type);
if (file) formData.append('file', file);
await dispatch(update({ id: id, data: formData }));
await router.push('/documents/documents-list');
} }
return ( return (
@ -116,25 +109,6 @@ const EditDocumentsPage = () => {
</Field> </Field>
</FormField> </FormField>
<FormField label="File" labelFor="file">
{initialValues.fileurl && (
<a
href={initialValues.fileurl}
download
className="block mb-2 text-blue-600 hover:underline"
>
Download current file
</a>
)}
<input
id="file"
name="file"
type="file"
onChange={e => setFile(e.currentTarget.files ? e.currentTarget.files[0] : null)}
/>
</FormField>
<BaseDivider />
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type="submit" color="info" label="Submit" /> <BaseButton type="submit" color="info" label="Submit" />

View File

@ -22,7 +22,7 @@ const DocumentsTablesPage = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const [filters] = useState([{label: 'Title', title: 'title'},{label: 'Fileurl', title: 'fileurl'}, const [filters] = useState([{label: 'Title', title: 'title'},
{label: 'DocumentType', title: 'document_type', type: 'enum', options: ['Checklist','Form','Policy','Procedure','Plan']}, {label: 'DocumentType', title: 'document_type', type: 'enum', options: ['Checklist','Form','Policy','Procedure','Plan']},
]); ]);

View File

@ -1,4 +1,6 @@
import React, { ReactElement, useState } from 'react'; import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement } from 'react'
import CardBox from '../../components/CardBox' import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated' import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain' import SectionMain from '../../components/SectionMain'
@ -27,26 +29,16 @@ const initialValues = {
document_type: 'Checklist', document_type: 'Checklist',
fileurl: '',
} }
const DocumentsNew = () => { const DocumentsNew = () => {
const router = useRouter() const router = useRouter()
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const [file, setFile] = useState<File | null>(null)
const handleSubmit = async (data) => {
const handleSubmit = async (data) => { await dispatch(create(data))
const formData = new FormData(); await router.push('/documents/documents-list')
formData.append('title', data.title);
formData.append('document_type', data.document_type);
if (file) {
formData.append('file', file);
} }
await dispatch(create(formData));
await router.push('/documents/documents-list');
}
return ( return (
<> <>
<Head> <Head>
@ -88,16 +80,6 @@ const handleSubmit = async (data) => {
<option value="Plan">Plan</option> <option value="Plan">Plan</option>
</Field> </Field>
<FormField label="File" labelFor="file">
<input
id="file"
name="file"
type="file"
onChange={e => setFile(e.currentTarget.files ? e.currentTarget.files[0] : null)}
/>
</FormField>
<BaseDivider />
</FormField> </FormField>
<BaseDivider /> <BaseDivider />

View File

@ -22,7 +22,7 @@ const DocumentsTablesPage = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const [filters] = useState([{label: 'Title', title: 'title'},{label: 'Fileurl', title: 'fileurl'}, const [filters] = useState([{label: 'Title', title: 'title'},
{label: 'DocumentType', title: 'document_type', type: 'enum', options: ['Checklist','Form','Policy','Procedure','Plan']}, {label: 'DocumentType', title: 'document_type', type: 'enum', options: ['Checklist','Form','Policy','Procedure','Plan']},
]); ]);

View File

@ -59,11 +59,6 @@ const DocumentsView = () => {
<p>{documents?.document_type ?? 'No data'}</p> <p>{documents?.document_type ?? 'No data'}</p>
</div> </div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Fileurl</p>
<p><a href={documents?.fileurl} download>Download</a></p>
</div>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -65,24 +65,21 @@ export const deleteItem = createAsyncThunk('documents/deleteDocuments', async (i
} }
}) })
export const create = createAsyncThunk('documents/createDocuments', async (payload: any, { rejectWithValue }) => { export const create = createAsyncThunk('documents/createDocuments', async (data: any, { rejectWithValue }) => {
try { try {
let result; const result = await axios.post(
if (payload instanceof FormData) { 'documents',
// FormData upload { data }
result = await axios.post('documents', payload); )
} else { return result.data
// JSON fallback
result = await axios.post('documents', { data: payload });
}
return result.data;
} catch (error) { } catch (error) {
if (!error.response) { if (!error.response) {
throw error; throw error;
} }
return rejectWithValue(error.response.data); return rejectWithValue(error.response.data);
} }
}); })
export const uploadCsv = createAsyncThunk( export const uploadCsv = createAsyncThunk(
'documents/uploadCsv', 'documents/uploadCsv',
@ -111,23 +108,19 @@ export const uploadCsv = createAsyncThunk(
export const update = createAsyncThunk('documents/updateDocuments', async (payload: any, { rejectWithValue }) => { export const update = createAsyncThunk('documents/updateDocuments', async (payload: any, { rejectWithValue }) => {
try { try {
let result; const result = await axios.put(
const { id, data } = payload; `documents/${payload.id}`,
if (data instanceof FormData) { { id: payload.id, data: payload.data }
// Multipart upload )
result = await axios.put(`documents/${id}`, data); return result.data
} else {
// JSON fallback
result = await axios.put(`documents/${id}`, { id, data });
}
return result.data;
} catch (error) { } catch (error) {
if (!error.response) { if (!error.response) {
throw error; throw error;
} }
return rejectWithValue(error.response.data); return rejectWithValue(error.response.data);
} }
}); })
export const documentsSlice = createSlice({ export const documentsSlice = createSlice({
name: 'documents', name: 'documents',