Skip to content

Commit

Permalink
Workaround for extraData bug implemented for begrotingen upload and f…
Browse files Browse the repository at this point in the history
…ix publishAsConcept
  • Loading branch information
LorenzoJokhan committed Sep 12, 2023
1 parent 6bd1be9 commit fff20c7
Show file tree
Hide file tree
Showing 8 changed files with 283 additions and 30 deletions.
9 changes: 9 additions & 0 deletions packages/cms/lib/modules/resource-form-widgets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module.exports = {
extend: 'map-widgets',
label: 'Resource form',
addFields: fields,
playerData: ['siteUrl'],
beforeConstruct: function (self, options) {

if (options.resources) {
Expand Down Expand Up @@ -121,6 +122,7 @@ module.exports = {
require('./lib/helpers.js')(self, options);
require('./lib/api.js')(self, options);
require('./lib/submit.js')(self, options);
require('./lib/budget.js')(self, options);

self.on('apostrophe-docs:afterSave', 'syncConfirmationFields');
self.on('apostrophe-docs:afterTrash', 'deleteConfirmationFields');
Expand Down Expand Up @@ -178,6 +180,13 @@ module.exports = {

// Todo: refactor this to get resourceId in a different way
const activeResource = req.data.activeResource;
if(activeResource && activeResource.extraData.budgetDocuments) {
try {
activeResource.extraData.budgetDocuments = JSON.parse(activeResource.extraData.budgetDocuments);
} catch (error) {

}
}
const resources = activeResource ? [activeResource] : [];
const googleMapsApiKey = self.apos.settings.getOption(req, 'googleMapsApiKey');

Expand Down
75 changes: 75 additions & 0 deletions packages/cms/lib/modules/resource-form-widgets/lib/budget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const eventEmitter = require('../../../../events').emitter;
const fetch = require('node-fetch');

module.exports = async function(self, options) {

self.route('put', 'budget', async function(req, res) {
eventEmitter.emit('resourceCrud');
const apiUrl = self.apos.settings.getOption(req, 'apiUrl');
const siteUrl = self.apos.settings.getOption(req, 'siteUrl');
const siteId = req.data.global.siteId;

const data = req.body;
const getUrl = `${apiUrl}/api/site/${siteId}/idea/${data.id}`;
const postUrl = `${apiUrl}/api/site/${siteId}/idea/${data.id}`;

/**
* Format header
*/
const httpHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};

if (req.session.jwt) {
httpHeaders['X-Authorization'] = `Bearer ${req.session.jwt}`;
}

const response = await fetch(getUrl, {
headers: httpHeaders
});

if(response.ok) {
const idea = await response.json();
let ideaBudgets = [];

try {
ideaBudgets = JSON.parse(idea?.extraData?.budgetDocuments);
}
catch(e) {

}

const indexToDelete = ideaBudgets.findIndex(d =>{
return d.name === data.name});

if(indexToDelete > -1) {
ideaBudgets.splice(indexToDelete, 1);
}

console.log(JSON.stringify({
extraData: {
budgetDocuments: JSON.stringify(ideaBudgets)
},
}));

const putResponse = await fetch(postUrl, {
method: 'PUT',
headers: httpHeaders,
body: JSON.stringify({
extraData: {
budgetDocuments: JSON.stringify(ideaBudgets)
},
}),
});

if(putResponse.ok) {
const ideaResponse = await putResponse.json();
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
id: ideaResponse.id
}));
}
}
});
}
47 changes: 45 additions & 2 deletions packages/cms/lib/modules/resource-form-widgets/lib/submit.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
const rp = require('request-promise');
const eventEmitter = require('../../../../events').emitter;
const multer = require('multer');
const upload = multer();
const fs = require('fs');

module.exports = async function(self, options) {

Expand All @@ -8,15 +11,17 @@ module.exports = async function(self, options) {
// Server side validation is done by the API
// In future form can probably talk directly with api proxy,
// Only images need to be refactored
self.route('post', 'submit', function(req, res) {
self.route('post', 'submit', upload.any('docFilePond'), async function(req, res) {
// emit event
eventEmitter.emit('resourceCrud');

/**
* Format API Url
*/
const apiUrl = self.apos.settings.getOption(req, 'apiUrl');
const siteUrl = self.apos.settings.getOption(req, 'siteUrl');
const siteId = req.data.global.siteId;

const postUrl = `${apiUrl}/api/site/${siteId}/${req.body.resourceEndPoint}`;

/**
Expand All @@ -30,9 +35,47 @@ module.exports = async function(self, options) {
httpHeaders['X-Authorization'] = `Bearer ${req.session.jwt}`;
}
const data = req.body;

data.extraData = data.extraData ? data.extraData : {};


if(req.files) {
console.log({files: req.files});
const promises = [];
req.files.forEach((file, i) => {
const attachmentsPath = 'public/uploads/attachments/resource-form-uploads/' + req.body.resourceId;
const path = `${attachmentsPath}/${file.originalname}`;

if(fs.existsSync(attachmentsPath) === false) {
fs.mkdirSync(attachmentsPath, { recursive: true });
}

promises.push(
new Promise( (resolve,reject) => {
const fileCopy = {name: file.originalname, url: path}
// existing files are ignored; it is more then likely the same file
fs.access(path, fs.constants.F_OK, (err) => {
if (!err) {
return resolve(fileCopy)
};
console.log('Create file', file.originalname);
fs.writeFile(path, file.buffer, err => {
err ? reject(err) : resolve(fileCopy)
});
});
})
);
});

const results = await Promise.all(promises);
try {
const files = results.map(file =>
Object.assign({}, {...file, url: file.url.replace("public", siteUrl)}));
data.extraData.budgetDocuments = JSON.stringify(files);
}catch(e) {
console.error("Budget documenten konden niet worden geupload");
}
}

//format image
if (data.image) {
// when only one image filepondjs sadly just returns object, not array with one file,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,26 @@
}
}

.filepond-uploaded-items {
display: flex;
padding: 8px;
justify-content: center;
align-items: center;
background-color: #f1f0ef;

a {
text-align: center;
flex-grow: 1;
p {
margin: 0;
}
}

button {
border-radius: 50%;
}
}

.idea-form {
.form-info:before, .form-warning:before {
position: absolute;
Expand Down
108 changes: 89 additions & 19 deletions packages/cms/lib/modules/resource-form-widgets/public/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,20 @@
// a reference to each uploaded file. This reference list is used
// by the server to connect the correct image uploads to this idea.

var fieldsetElement = document.querySelector('.filepondFieldset');
var fieldsetElements = document.querySelectorAll('.filepondFieldset');


if (fieldsetElement) {
if (fieldsetElements) {
FilePond.registerPlugin(FilePondPluginImagePreview);
FilePond.registerPlugin(FilePondPluginFileValidateSize);
FilePond.registerPlugin(FilePondPluginFileValidateType);
FilePond.registerPlugin(FilePondPluginFilePoster);
FilePond.registerPlugin(FilePondPluginImageExifOrientation);

/*FilePond.setOptions({
server: {
process: '/image',
fetch: null,
revert: null
}
});*/

var filePondSettings = {
var filePondSettings = function (options={}){

return Object.assign({},{
// set allowed file types with mime types
acceptedFileTypes: ['image/*'],
allowFileSizeValidation: true,
Expand Down Expand Up @@ -62,13 +57,34 @@ if (fieldsetElement) {
labelButtonUndoItemProcessing: "Undo",
labelButtonRetryItemProcessing: "Retry",
labelButtonProcessItem: "Upload"
}

var pond = FilePond.create(fieldsetElement, filePondSettings);

var sortableInstance;
}, options)
}

var pondEl = document.querySelector('.filepond--root');
for(var fieldsetElement of fieldsetElements) {
if(fieldsetElement.classList.contains("docs")) {
var documentPond = FilePond.create(fieldsetElement, filePondSettings(
{
name: 'begrotingen',
files: [],
acceptedFileTypes: [
'.csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'application/pdf',
'.doc'
],
server: undefined,
labelIdle:"Sleep begrotingen naar deze plek of <span class='filepond--label-action'>klik hier</span>",
labelFileProcessingComplete: "Begrotingen geladen"
})
);
}else {
var pond = FilePond.create(fieldsetElement, filePondSettings());
}
var sortableInstance;

var pondEl = document.querySelector('.filepond--root');
}
}

var formHasChanged = false;
Expand All @@ -91,6 +107,18 @@ $(document).ready(function () {
}, "Plaatjes zijn nog aan het uploaden.");


$.validator.addMethod("validateDocFilePondProcessing", function() {
var files = documentPond ? documentPond.getFiles() : [];
var docPondFileStates = FilePond.FileStatus;

var processingDocFiles = files.filter(function (file) {
return file.status !== docPondFileStates.PROCESSING_COMPLETE;
});

return processingDocFiles.length === 0;
}, "Begrotingen zijn nog aan het uploaden.");



$.validator.addMethod("minLengthWithoutHTML", function(val, el, params) {
var mainEditor = document.getElementById('js-editor');
Expand Down Expand Up @@ -160,6 +188,10 @@ $(document).ready(function () {
validateFilePond: true,
validateFilePondProcessing: true
},
validateBudgetDocs: {
validateDocFilePond: true,
validateDocFilePondProcessing:true
},
firstName: {
required: true
},
Expand Down Expand Up @@ -195,13 +227,21 @@ $(document).ready(function () {
}
$(this).attr('disabled', 'true')
});


const formdata = new FormData(form);
const pondFiles = documentPond? documentPond.getFiles() : [];
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('docFilePond', pondFiles[i].file);
}


$.ajax({
url: $(form).attr('action'),
// context: document.body,
type: 'POST',
data: $(form).serialize(),
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success:function(response) {
formHasChanged = false;
var redirect = $(form).find('.form-redirect-uri').val();
Expand Down Expand Up @@ -277,7 +317,24 @@ $(document).ready(function () {
}

}, "Eén of meerdere plaatjes zijn verplicht.");

$.validator.addMethod("validateDocFilePond", function() {
if ($('.docFilePond').prop('required')) {
var files = documentPond ? documentPond.getFiles() : [];
var pondFileStates = FilePond.FileStatus;

files = files.filter(function (file) {
return file.status === pondFileStates.PROCESSING_COMPLETE;
});

return files && files.length > 0;
} else {
return true;
}

}, "Eén of meerdere begrotingen zijn verplicht.");



$('#locationField').on('change', function () {
validator.element($(this))
Expand Down Expand Up @@ -414,6 +471,19 @@ window.addEventListener('load', function() {

// einde characters counters ------------------------------


function deleteBudgetDocument(name, id, siteUrl) {
console.log(name, id, siteUrl);
$.ajax({
url: siteUrl + "/modules/resource-form-widgets/budget",
type: 'PUT',
data: { name, id},
success: function(data) {
console.log('ok');
}
});
}

function initLeavePageWarningForForm () {
if ($('.add-warning-when-leaving-page').length > 0) {

Expand Down
Loading

0 comments on commit fff20c7

Please sign in to comment.