/
structure_component.js
executable file
·1667 lines (1472 loc) · 101 KB
/
structure_component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require("fs-extra");
const domHelper = require('../utils/jsDomHelper');
const translateHelper = require("../utils/translate");
const helpers = require("../utils/helpers");
const printHelper = require("../utils/print_helper");
const moment = require("moment");
function setupComponentModel(idApplication, folderComponent, componentName, filename, callback) {
// CREATE MODEL FILE
var modelTemplate = fs.readFileSync('./structure/pieces/component/' + folderComponent + '/models/model_' + filename + '.js', 'utf8');
modelTemplate = modelTemplate.replace(/COMPONENT_NAME_LOWER/g, componentName);
modelTemplate = modelTemplate.replace(/COMPONENT_NAME/g, componentName.charAt(0).toUpperCase() + componentName.toLowerCase().slice(1));
modelTemplate = modelTemplate.replace(/TABLE_NAME/g, idApplication + '_' + componentName);
var writeStream = fs.createWriteStream('./workspace/' + idApplication + '/models/' + componentName + '.js');
writeStream.write(modelTemplate);
writeStream.end();
writeStream.on('finish', function () {
callback();
});
}
function createComponentAttributesAndOptionsFiles(idApplication, folderComponent, componentName, filename, source, callback) {
// CREATE MODEL ATTRIBUTES FILE
var attributesTemplate = fs.readFileSync('./structure/pieces/component/' + folderComponent + '/models/attributes/attributes_' + filename + '.json', 'utf8');
var writeStream = fs.createWriteStream('./workspace/' + idApplication + '/models/attributes/' + componentName + '.json');
writeStream.write(attributesTemplate);
writeStream.end();
writeStream.on('finish', function () {
// CREATE MODEL OPTIONS (ASSOCIATIONS) FILE
var optionsTemplate = fs.readFileSync('./structure/pieces/component/' + folderComponent + '/models/options/options_' + filename + '.json', 'utf8');
optionsTemplate = optionsTemplate.replace(/SOURCE_ENTITY_LOWER/g, source);
var writeStreamOption = fs.createWriteStream('./workspace/' + idApplication + '/models/options/' + componentName + '.json');
writeStreamOption.write(optionsTemplate);
writeStreamOption.end();
writeStreamOption.on('finish', function () {
callback();
});
});
}
function setupComponentRoute(idApplication, folderComponent, componentName, urlSource, filename, source, callback) {
// CREATE ROUTE FILE
var routeTemplate = fs.readFileSync('./structure/pieces/component/' + folderComponent + '/routes/route_' + filename + '.js', 'utf8');
routeTemplate = routeTemplate.replace(/COMPONENT_NAME_LOWER/g, componentName.toLowerCase());
routeTemplate = routeTemplate.replace(/COMPONENT_NAME_URL/g, componentName.toLowerCase().substring(2));
routeTemplate = routeTemplate.replace(/COMPONENT_NAME/g, componentName.charAt(0).toUpperCase() + componentName.toLowerCase().slice(1));
routeTemplate = routeTemplate.replace(/SOURCE_ENTITY_LOWER/g, source.toLowerCase());
routeTemplate = routeTemplate.replace(/SOURCE_URL_ENTITY_LOWER/g, urlSource.toLowerCase());
var writeStream = fs.createWriteStream('./workspace/' + idApplication + '/routes/' + componentName.toLowerCase() + '.js');
writeStream.write(routeTemplate);
writeStream.end();
writeStream.on('finish', function () {
callback();
});
}
function addTab(attr, file, newLi, newTabContent) {
return new Promise(function (resolve, reject) {
var source = attr.options.source.toLowerCase();
domHelper.read(file).then(function ($) {
// Tabs structure doesn't exist, create it
var tabs = '';
var context;
if ($("#tabs").length == 0) {
tabs = '\
<div class="nav-tabs-custom" id="tabs">\n\
<!--{^hideTab}-->\n\
<ul class="nav nav-tabs">\n\
<li class="active">\n\
<a data-toggle="tab" href="#home">\n\
<!--{#__ key="entity.' + source + '.label_entity" /}-->\n\
</a>\n\
</li>\n\
</ul>\n\
<!--{/hideTab}-->\n\
<div class="tab-content" style="min-height:275px;">\n\
<div id="home" class="tab-pane fade in active"></div>\n\
</div>\n\
</div>\n';
context = $(tabs);
$("#home", context).append($("#fields"));
$("#home", context).append($(".actions"));
} else
context = $("#tabs");
// Append created elements to `context` to handle presence of tab or not
$(".nav-tabs", context).append(newLi);
$(".tab-content", context).append('<!--{^hideTab}-->');
$(".tab-content", context).append(newTabContent);
$(".tab-content", context).append('<!--{/hideTab}-->');
$('body').empty().append(context);
domHelper.write(file, $).then(function () {
resolve();
});
}).catch(function (err) {
console.error(err);
reject(err);
});
});
}
function addAccessManagment(idApplication, urlComponent, urlModule, callback) {
// Write new data entity to access.json file, within module's context
var accessPath = __dirname + '/../workspace/' + idApplication + '/config/access.json';
var accessLockPath = __dirname + '/../workspace/' + idApplication + '/config/access.lock.json';
var accessObject = JSON.parse(fs.readFileSync(accessPath, 'utf8'));
accessObject[urlModule.toLowerCase()].entities.push({
name: urlComponent,
groups: [],
actions: {
create: [],
update: [],
read: [],
delete: []
}
});
fs.writeFileSync(accessPath, JSON.stringify(accessObject, null, 4), "utf8");
fs.writeFileSync(accessLockPath, JSON.stringify(accessObject, null, 4), "utf8");
callback();
}
function deleteAccessManagment(idApplication, urlComponent, urlModule, callback) {
// Write new data entity to access.json file, within module's context
var accessPath = __dirname + '/../workspace/' + idApplication + '/config/access.json';
var accessLockPath = __dirname + '/../workspace/' + idApplication + '/config/access.lock.json';
var accessObject = JSON.parse(fs.readFileSync(accessPath, 'utf8'));
if (accessObject[urlModule.toLowerCase()] && accessObject[urlModule.toLowerCase()].entities) {
var entities = accessObject[urlModule.toLowerCase()].entities;
var dataIndexToRemove = -1;
for (var i = 0; i < entities.length; i++) {
if (entities[i].name === urlComponent) {
dataIndexToRemove = i;
break;
}
}
if (dataIndexToRemove !== -1)
entities.splice(dataIndexToRemove, 1);
fs.writeFileSync(accessPath, JSON.stringify(accessObject, null, 4), "utf8");
fs.writeFileSync(accessLockPath, JSON.stringify(accessObject, null, 4), "utf8");
callback();
} else
callback();
}
function replaceValuesInFile(filePath, valueToFind, replaceWith) {
var fileContent = fs.readFileSync(filePath, 'utf8');
var reg = new RegExp(valueToFind, "g");
fileContent = fileContent.replace(reg, replaceWith);
fs.writeFileSync(filePath, fileContent);
}
exports.newLocalFileStorage = function (attr, callback) {
var componentName = attr.options.value;
var componentNameLower = componentName.toLowerCase();
var urlComponent = attr.options.urlValue.toLowerCase();
var showComponentName = attr.options.showValue;
var source = attr.options.source;
var sourceLower = source.toLowerCase();
var urlSource = attr.options.urlSource;
var filename = "local_file_storage";
setupComponentModel(attr.id_application, filename, componentNameLower, filename, function () {
createComponentAttributesAndOptionsFiles(attr.id_application, filename, componentName, filename, source, function () {
setupComponentRoute(attr.id_application, filename, componentName, urlSource, filename, source, function () {
// Add access managment to the component route
addAccessManagment(attr.id_application, urlComponent, attr.options.moduleName.substring(2), function () {
/* --------------- New translation --------------- */
translateHelper.writeLocales(attr.id_application, "component", componentName, showComponentName, attr.googleTranslate, function () {
// GET COMPONENT PIECES TO BUILD STRUCTURE FILE
var componentPiece = fs.readFileSync('./structure/pieces/component/' + filename + '/views/view_' + filename + '.dust', 'utf8');
var componentContent = componentPiece.replace(/COMPONENT_NAME_LOWER/g, componentNameLower);
componentContent = componentContent.replace(/COMPONENT_URL_NAME_LOWER/g, urlComponent);
componentContent = componentContent.replace(/SOURCE_LOWER/g, sourceLower);
fs.mkdirSync(__dirname + '/../workspace/' + attr.id_application + '/views/' + componentName, 0766);
fs.writeFileSync(__dirname + '/../workspace/' + attr.id_application + '/views/' + componentName + '/list_fields.dust', componentContent, 'utf8');
var newLi = '<li><a id="' + componentNameLower + '-click" data-toggle="tab" href="#' + componentNameLower + '"><!--{#__ key="component.' + componentNameLower + '.label_component" /}--></a></li>';
var fileBase = __dirname + '/../workspace/' + attr.id_application + '/views/' + sourceLower;
var file = fileBase + '/show_fields.dust';
// printHelper.addLocalFileStorage(fileBase, componentNameLower).then(function(){
// CREATE THE TAB IN SHOW FIELDS
var newTab = '<div id="' + componentNameLower + '" class="ajax-tab tab-pane fade" data-tabtype="localfilestorage" data-asso-flag="{' + sourceLower + '.id}" data-asso-alias="' + componentNameLower + '"><div class="ajax-content"></div></div>';
addTab(attr, file, newLi, newTab).then(callback);
// });
});
});
});
});
});
}
exports.newPrint = function (attr, callback) {
let nameComponent = attr.options.value;
let nameComponentLower = nameComponent.toLowerCase();
let showComponentName = attr.options.showValue;
let entityLower = attr.options.source.toLowerCase();
let appID = attr.id_application;
let showFieldsPath = __dirname + '/../workspace/' + appID + '/views/' + entityLower + '/show_fields.dust';
domHelper.read(showFieldsPath).then(function ($) {
let newLi = '\
<li>\n\
<a id="' + nameComponentLower + '-click" data-toggle="tab" href="#' + nameComponentLower + '">\n\
<!--{#__ key="component.' + nameComponentLower + '.label_component" /}-->\n\
</a>\n\
</li>\n';
let cssPrintContent = fs.readFileSync(__dirname + '/../workspace/' + appID + '/public/css/print.css', 'utf8');
cssPrintContent = cssPrintContent.replace(/COMPONENT_NAME/g, nameComponent);
fs.writeFileSync(__dirname + '/../workspace/' + appID + '/public/css/print_' + nameComponent + '.css', cssPrintContent, 'utf8');
let tabContent = " \
<div id='" + nameComponentLower + "' class='tab-pane ajax-tab fade' data-tabtype='print'>\n \
<link href='/public/css/print_" + nameComponent + ".css' rel='stylesheet' type='text/css'>\n \
<button data-component='" + nameComponentLower + "' class='component-print-button btn btn-info'><i class='fa fa-print' aria-hidden='true' style='margin-right:5px;'></i><!--{#__ key=\"global_component.print.action\"/}--></button>\n \
<div id='" + nameComponent + "-content' class='ajax-content print-tab'>\n \
</div>\n \
</div>\n";
translateHelper.writeLocales(appID, "component", nameComponent, showComponentName, attr.googleTranslate, function () {
addTab(attr, showFieldsPath, newLi, tabContent).then(callback);
});
});
}
exports.deletePrint = function (attr, callback) {
var entityLower = attr.options.source.toLowerCase();
var idApp = attr.id_application;
var componentNameLower = attr.options.value.toLowerCase();
var showFieldsPath = __dirname + '/../workspace/' + idApp + '/views/' + entityLower + '/show_fields.dust';
domHelper.read(showFieldsPath).then(function ($) {
try {
$("#" + componentNameLower).remove();
$("#" + componentNameLower + "-click").parents("li").remove();
domHelper.write(showFieldsPath, $).then(function () {
callback();
});
} catch (err) {
callback(err, null);
}
});
}
exports.newContactForm = function (attr, callback) {
var idApp = attr.id_application;
// Contact Form entity
var codeName = attr.options.value;
var showName = attr.options.showValue;
var urlName = attr.options.urlValue.toLowerCase();
// Contact Form Settings entity
var codeNameSettings = attr.options.valueSettings;
var showNameSettings = attr.options.showValueSettings;
var urlNameSettings = attr.options.urlValueSettings;
var workspacePath = __dirname + '/../workspace/' + idApp;
var piecesPath = __dirname + '/../structure/pieces/component/contact_form';
var toSyncObject = JSON.parse(fs.readFileSync(workspacePath + '/models/toSync.json'));
if (typeof toSyncObject.queries !== "object")
toSyncObject.queries = [];
toSyncObject[idApp + "_" + codeNameSettings] = {};
var mailConfigPath = workspacePath + "/config/mail.js";
delete require.cache[require.resolve(mailConfigPath)];
var mailConfig = require(mailConfigPath);
let isSecure = mailConfig.transport.secure ? 1 : 0;
var insertSettings = "INSERT INTO `" + idApp + "_" + codeNameSettings + "`(`version`, `f_transport_host`, `f_port`, `f_secure`, `f_user`, `f_pass`, `f_form_recipient`, `createdAt`, `updatedAt`)" +
" VALUES(1,'" + mailConfig.transport.host + "'," +
"'" + mailConfig.transport.port + "'," +
isSecure + "," +
"'" + mailConfig.transport.auth.user + "'," +
"'" + mailConfig.transport.auth.pass + "'," +
"'" + mailConfig.administrateur + "'," +
"'" + moment().format("YYYY-MM-DD HH:mm:ss") + "'," +
"'" + moment().format("YYYY-MM-DD HH:mm:ss") + "');";
toSyncObject.queries.push(insertSettings);
fs.writeFileSync(workspacePath + '/models/toSync.json', JSON.stringify(toSyncObject, null, 4));
// Contact Form View
fs.copySync(piecesPath + '/views/', workspacePath + '/views/' + codeName + '/');
fs.unlinkSync(workspacePath + '/views/' + codeName + '/update.dust');
fs.unlinkSync(workspacePath + '/views/' + codeName + '/update_fields.dust');
// Contact Form Route
// Unlink generated route to replace with our custom route file
fs.unlinkSync(workspacePath + '/routes/' + codeName + '.js');
fs.copySync(piecesPath + '/routes/route_contact_form.js', workspacePath + '/routes/' + codeName + '.js');
var workspaceRoutePath = workspacePath + '/routes/' + codeName + '.js';
var workspaceViewPath = workspacePath + '/views/' + codeName;
replaceValuesInFile(workspaceRoutePath, "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceRoutePath, "URL_VALUE_SETTINGS", urlNameSettings);
replaceValuesInFile(workspaceRoutePath, "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceRoutePath, "CODE_VALUE_SETTINGS", codeNameSettings);
replaceValuesInFile(workspaceRoutePath, "MODEL_VALUE_CONTACT", codeName.charAt(0).toUpperCase() + codeName.toLowerCase().slice(1));
replaceValuesInFile(workspaceRoutePath, "MODEL_VALUE_SETTINGS", codeNameSettings.charAt(0).toUpperCase() + codeNameSettings.toLowerCase().slice(1));
replaceValuesInFile(workspaceViewPath + '/create.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/create.dust', "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceViewPath + '/create.dust', "CODE_VALUE_MODULE", attr.options.moduleName);
replaceValuesInFile(workspaceViewPath + '/create_fields.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/show_fields.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/show_fields.dust', "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceViewPath + '/list.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/list.dust', "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceViewPath + '/list.dust', "CODE_VALUE_MODULE", attr.options.moduleName);
replaceValuesInFile(workspaceViewPath + '/list_fields.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/list_fields.dust', "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceViewPath + '/settings.dust', "CODE_VALUE_CONTACT", codeName);
replaceValuesInFile(workspaceViewPath + '/settings.dust', "URL_VALUE_CONTACT", urlName);
replaceValuesInFile(workspaceViewPath + '/settings.dust', "CODE_VALUE_MODULE", attr.options.moduleName);
replaceValuesInFile(workspaceViewPath + '/settings_fields.dust', "CODE_VALUE_SETTINGS", codeNameSettings);
// Delete Contact Form Settings Route and Views
fs.unlinkSync(workspacePath + '/routes/' + codeNameSettings + '.js');
helpers.rmdirSyncRecursive(workspacePath + '/views/' + codeNameSettings + '/');
// Locales FR
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "f_name"], "Nom");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "f_sender"], "Expediteur");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "f_recipient"], "Destinataire");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "r_user"], "Utilisateur");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "f_title"], "Titre");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "f_content"], "Contenu");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeName, "sendMail"], "Send a mail");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeName, "inbox"], "Sent box");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeName, "settings"], "Settings");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeName, "successSendMail"], "The email has been sent!");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "sendMail"], "Envoyer un mail");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "inbox"], "Boîte de réception");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "settings"], "Paramètres");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "successSendMail"], "Le mail a bien été envoyé !");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeNameSettings, "label_entity"], "Settings");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeNameSettings, "name_entity"], "Settings");
translateHelper.updateLocales(idApp, "en-EN", ["entity", codeNameSettings, "plural_entity"], "Settings");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "label_entity"], "Paramètres");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "name_entity"], "Paramètres");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "plural_entity"], "Paramètres");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_transport_host"], "Hôte");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_port"], "Port");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_secure"], "Sécurisé");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_user"], "Utilisateur");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_pass"], "Mot de passe");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeNameSettings, "f_form_recipient"], "Destinataire du formulaire");
// If default name
if (codeName == "e_contact_form")
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "label_entity"], "Formulaire de contact");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "name_entity"], "Formulaire de contact");
translateHelper.updateLocales(idApp, "fr-FR", ["entity", codeName, "plural_entity"], "Formulaires de contact");
var layoutFileName = __dirname + '/../workspace/' + idApp + '/views/layout_' + attr.options.moduleName.toLowerCase() + '.dust';
domHelper.read(layoutFileName).then(function ($) {
$("#" + urlName + "_menu_item").remove();
$("#" + urlNameSettings + "_menu_item").remove();
var li = '';
li += "<!--{#entityAccess entity=\"" + urlName + "\"}-->\n";
li += " <li id=\"" + urlName + "_menu_item\" style=\"display:block;\" class=\"treeview\">\n";
li += " <a href=\"#\">\n";
li += " <i class=\"fa fa-envelope\"></i>\n";
li += " <span><!--{#__ key=\"entity." + codeName + ".label_entity\" /}--></span>\n";
li += " <i class=\"fa fa-angle-left pull-right\"></i>\n";
li += " </a>\n";
li += " <ul class=\"treeview-menu\">\n";
li += " <!--{#actionAccess entity=\"" + urlName + "\" action=\"create\"}-->\n";
li += " <li>\n";
li += " <a href=\"/" + urlName + "/create_form\">\n";
li += " <i class=\"fa fa-paper-plane\"></i>\n";
li += " <!--{#__ key=\"entity." + codeName + ".sendMail\" /}-->\n";
li += " </a>\n";
li += " </li>\n";
li += " <!--{/actionAccess}-->\n";
li += " <!--{#actionAccess entity=\"" + urlName + "\" action=\"read\"}-->\n";
li += " <li>\n";
li += " <a href=\"/" + urlName + "/list\">\n";
li += " <i class=\"fa fa-inbox\"></i>\n";
li += " <!--{#__ key=\"entity." + codeName + ".inbox\" /}-->\n";
li += " </a>\n";
li += " </li>\n";
li += " <!--{/actionAccess}-->\n";
li += " <!--{#actionAccess entity=\"" + urlNameSettings + "\" action=\"create\"}-->\n";
li += " <li>\n";
li += " <a href=\"/" + urlName + "/settings\">\n";
li += " <i class=\"fa fa-cog\"></i>\n";
li += " <!--{#__ key=\"entity." + codeName + ".settings\" /}-->\n";
li += " </a>\n";
li += " </li>\n";
li += " <!--{/actionAccess}-->\n";
li += " </ul>\n";
li += " </li>\n\n";
li += "<!--{/entityAccess}-->\n";
// Add new html to document
$('#sortable').append(li);
// Write back to file
domHelper.write(layoutFileName, $).then(function () {
// Clean empty and useless dust helper created by removing <li>
var layoutContent = fs.readFileSync(layoutFileName, 'utf8');
// Remove empty dust helper
layoutContent = layoutContent.replace(/{#entityAccess entity=".+"}\W*{\/entityAccess}/g, "");
var writeStream = fs.createWriteStream(layoutFileName);
writeStream.write(layoutContent);
writeStream.end();
writeStream.on('finish', function () {
callback();
});
});
}).catch(function (err) {
callback(err, null);
});
}
exports.newAgenda = function (attr, callback) {
function setupComponentRouteForAgenda(idApplication, valueAgenda, valueEvent, valueCategory, callback) {
var valueAgendaModel = valueAgenda.charAt(0).toUpperCase() + valueAgenda.toLowerCase().slice(1);
var valueEventModel = valueEvent.charAt(0).toUpperCase() + valueEvent.toLowerCase().slice(1);
var valueCategoryModel = valueCategory.charAt(0).toUpperCase() + valueCategory.toLowerCase().slice(1);
var urlRouteAgenda = valueAgenda.substring(2).toLowerCase();
// CREATE ROUTE FILE
var routeTemplate = fs.readFileSync('./structure/pieces/component/agenda/routes/route_agenda.js', 'utf8');
routeTemplate = routeTemplate.replace(/CODE_NAME_LOWER/g, valueAgenda);
routeTemplate = routeTemplate.replace(/URL_ROUTE/g, urlRouteAgenda);
routeTemplate = routeTemplate.replace(/CODE_NAME_EVENT_MODEL/g, valueEventModel);
routeTemplate = routeTemplate.replace(/CODE_NAME_EVENT_URL/g, valueEvent.substring(2));
routeTemplate = routeTemplate.replace(/CODE_NAME_CATEGORY_MODEL/g, valueCategoryModel);
routeTemplate = routeTemplate.replace(/CODE_NAME_CATEGORY_URL/g, valueCategory.substring(2));
var writeStream = fs.createWriteStream('./workspace/' + idApplication + '/routes/' + valueAgenda + '.js');
writeStream.write(routeTemplate);
writeStream.end();
writeStream.on('finish', function () {
callback();
});
}
function setupComponentViewForAgenda(idApplication, valueComponent, valueEvent, moduleName, callback) {
// Calendar View
var codeName = valueComponent.toLowerCase();
var componentViewFolder = __dirname + '/pieces/component/agenda/views';
var viewsFolder = __dirname + '/../workspace/' + idApplication + '/views/' + codeName;
fs.copySync(componentViewFolder, viewsFolder);
var viewPiece = __dirname + '/../workspace/' + idApplication + '/views/agenda/view_agenda.dust';
var viewFile = __dirname + '/../workspace/' + idApplication + '/views/' + codeName + '/view_agenda.dust';
var urlEvent = valueEvent.toLowerCase().substring(2);
var viewTemplate = fs.readFileSync(viewFile, 'utf8');
viewTemplate = viewTemplate.replace(/CODE_NAME_LOWER/g, codeName);
viewTemplate = viewTemplate.replace(/CODE_NAME_EVENT_LOWER/g, valueEvent);
viewTemplate = viewTemplate.replace(/MODULE_NAME/g, moduleName);
viewTemplate = viewTemplate.replace(/URL_ROUTE/g, codeName.substring(2));
viewTemplate = viewTemplate.replace(/URL_EVENT/g, urlEvent);
var writeStream = fs.createWriteStream(viewFile);
writeStream.write(viewTemplate);
writeStream.end();
writeStream.on('finish', function () {
// Copy the event view folder
var componentEventViewFolder = __dirname + '/pieces/component/agenda/views_event';
var eventViewsFolder = __dirname + '/../workspace/' + idApplication + '/views/' + valueEvent;
fs.copySync(componentEventViewFolder, eventViewsFolder);
// Replace variable in each files
var fileToReplace = ["show_fields", "create_fields", "update_fields", "create", "update"];
for (var i = 0; i < fileToReplace.length; i++) {
var eventFile = __dirname + '/../workspace/' + idApplication + '/views/' + valueEvent + '/' + fileToReplace[i] + '.dust';
var eventTemplate = fs.readFileSync(eventFile, 'utf8');
eventTemplate = eventTemplate.replace(/CODE_NAME_EVENT_LOWER/g, valueEvent);
eventTemplate = eventTemplate.replace(/URL_EVENT/g, urlEvent);
eventTemplate = eventTemplate.replace(/MODULE_NAME/g, moduleName);
fs.writeFileSync(eventFile, eventTemplate, 'utf8');
}
// Inject custom_js
// var fileToInject = ["create", "update"];
// for (var i = 0; i < fileToInject.length; i++) {
// var eventFile = __dirname + '/../workspace/' + idApplication + '/views/' + valueEvent + '/' + fileToInject[i] + '.dust';
// var eventTemplate = fs.readFileSync(eventFile, 'utf8');
// eventTemplate += "\n\n" +
// "{<custom_js}\n" +
// " <script type='text/javascript'>\n" +
// " var format;\n" +
// " if (lang_user == 'fr-FR')\n" +
// " format = 'DD/MM/YYYY HH:mm';\n" +
// " else\n" +
// " format = 'YYYY-MM-DD HH:mm';\n" +
// " $(document).on('click', 'button[type=\"submit\"]', function(){\n" +
// " if($('input[name=\"f_start_date\"]').val() != '' && $('input[name=\"f_end_date\"]').val() != ''){\n" +
// " var start = moment($('input[name=\"f_start_date\"]').val(), format);\n" +
// " var end = moment($('input[name=\"f_end_date\"]').val(), format);\n" +
// " if(end.diff(start) < 0){\n" +
// " toastr.error(\"Error: Start date is after end date.\");\n" +
// " return false;\n" +
// " }\n" +
// " }\n" +
// " if($('input[name=\"f_end_date\"]').val() != '' && $('input[name=\"f_start_date\"]').val() != ''){\n" +
// " var start = moment($('input[name=\"f_start_date\"]').val(), format);\n" +
// " var end = moment($('input[name=\"f_end_date\"]').val(), format);\n" +
// " if(end.diff(start) < 0){\n" +
// " toastr.error(\"Error: End date is before start date.\");\n" +
// " return false;\n" +
// " }\n" +
// " }\n" +
// " return true;" +
// " });\n" +
// " $(document).on('dp.change', 'input[name=\"f_start_date\"]', function(){\n" +
// " if($(this).val() != '' && $('input[name=\"f_end_date\"]').val() != ''){\n" +
// " var start = moment($(this).val(), format);\n" +
// " var end = moment($('input[name=\"f_end_date\"]').val(), format);\n" +
// " if(end.diff(start) < 0){\n" +
// " $(this).val('');\n" +
// " }\n" +
// " }\n" +
// " });\n" +
// " $(document).on('dp.change', 'input[name=\"f_end_date\"]', function(){\n" +
// " if($(this).val() != '' && $('input[name=\"f_start_date\"]').val() != ''){\n" +
// " var start = moment($('input[name=\"f_start_date\"]').val(), format);\n" +
// " var end = moment($(this).val(), format);\n" +
// " if(end.diff(start) < 0){\n" +
// " $(this).val('');\n" +
// " }\n" +
// " }\n" +
// " });\n" +
// " </script>\n" +
// "{/custom_js}\n";
// fs.writeFileSync(eventFile, eventTemplate, 'utf8');
// }
callback();
});
}
var idApplication = attr.id_application;
var valueComponent = attr.options.value;
var valueComponentLower = valueComponent.toLowerCase();
var showComponentName = attr.options.showValue;
var showComponentNameLower = showComponentName.toLowerCase();
var urlComponent = attr.options.urlValue.toLowerCase();
var valueEvent = "e_" + urlComponent + "_event";
var valueCategory = "e_" + urlComponent + "_category";
var urlEvent = valueEvent.substring(2);
var urlCategory = valueCategory.substring(2);
// Update the event options.json to add an belongsToMany relation between event and user
// var eventOptionsPath = './workspace/' + idApplication + '/models/options/' + valueEvent.toLowerCase() + '.json';
// var eventOptionFile = fs.readFileSync(eventOptionsPath);
// var eventOptionObj = JSON.parse(eventOptionFile);
// eventOptionObj.push({
// "target": "e_user",
// "relation": "belongsToMany",
// "through": idApplication + "_" + urlComponent + "_event_user",
// "as": "r_users",
// "foreignKey": "event_id",
// "otherKey": "user_id"
// });
// fs.writeFileSync(eventOptionsPath, JSON.stringify(eventOptionObj, null, 4));
// Agenda Route
setupComponentRouteForAgenda(idApplication, valueComponent, valueEvent, valueCategory, function () {
// Agenda view
setupComponentViewForAgenda(idApplication, valueComponent, valueEvent, attr.options.moduleName, function () {
// Add access managment to Agenda
addAccessManagment(idApplication, urlComponent, attr.options.moduleName.substring(2), function () {
// Add Event translation
translateHelper.writeLocales(idApplication, "component", valueComponentLower, showComponentName, attr.googleTranslate, function () {
// FR translation of the component
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "label_entity"], "Événement");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "name_entity"], "Événement");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "plural_entity"], "Événement");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "f_title"], "Titre");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "f_place"], "Lieu");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "f_start_date"], "Date de début");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "f_end_date"], "Date de fin");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "f_all_day"], "Toute la journée");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueEvent, "r_category"], "Catégorie");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueCategory, "label_entity"], "Catégorie");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueCategory, "name_entity"], "Catégorie");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueCategory, "plural_entity"], "Catégorie");
translateHelper.updateLocales(idApplication, "fr-FR", ["entity", valueCategory, "f_color"], "Couleur");
var layoutFileName = __dirname + '/../workspace/' + idApplication + '/views/layout_' + attr.options.moduleName.toLowerCase() + '.dust';
domHelper.read(layoutFileName).then(function ($) {
$("#" + urlEvent + "_menu_item").remove();
$("#" + urlCategory + "_menu_item").remove();
var li = '';
li += "<li id='" + urlComponent + "_menu_item' style='display:block;' class='treeview'>\n";
li += " <a href='#'>\n";
li += " <i class='fa fa-calendar-o'></i> <span><!--{#__ key=\"component." + valueComponentLower + ".label_component\" /}--></span>\n";
li += " <i class='fa fa-angle-left pull-right'></i>\n";
li += " </a>\n";
li += " <ul class='treeview-menu'>\n";
li += " <li><a href='/" + urlComponent + "'><i class='fa fa-calendar'></i> <!--{#__ key=\"global_component.agenda.menu\" /}--></a></li>\n";
li += " <li id='" + urlEvent + "_menu_item' style='display:block;' class='treeview'>\n";
li += " <a href='#'><i class='fa fa-calendar-plus-o'></i> <!--{#__ key=\"entity." + valueEvent + ".label_entity\" /}-->\n";
li += " <i class='fa fa-angle-left pull-right'></i>\n";
li += " </a>\n";
li += " <ul class='treeview-menu'>\n";
li += " <li><a href='/" + urlEvent + "/create_form'><i class='fa fa-plus'></i><!--{#__ key=\"operation.create\" /}--> <!--{#__ key=\"entity." + valueEvent + ".label_entity\" /}--></a></li>\n";
li += " <li><a href='/" + urlEvent + "/list'><i class='fa fa-list'></i><!--{#__ key=\"operation.list\" /}--> <!--{#__ key=\"entity." + valueEvent + ".plural_entity\" /}--></a></li>\n";
li += " </ul>\n";
li += " </li>\n";
li += " <li id='" + urlCategory + "_menu_item' style='display:block;' class='treeview'>\n";
li += " <a href='#'><i class='fa fa-bookmark'></i> <!--{#__ key=\"entity." + valueCategory + ".label_entity\" /}-->\n";
li += " <i class='fa fa-angle-left pull-right'></i>\n";
li += " </a>\n";
li += " <ul class='treeview-menu'>\n";
li += " <li><a href='/" + urlCategory + "/create_form'><i class='fa fa-plus'></i><!--{#__ key=\"operation.create\" /}--> <!--{#__ key=\"entity." + valueCategory + ".label_entity\" /}--></a></li>\n";
li += " <li><a href='/" + urlCategory + "/list'><i class='fa fa-list'></i><!--{#__ key=\"operation.list\" /}--> <!--{#__ key=\"entity." + valueCategory + ".plural_entity\" /}--></a></li>\n";
li += " </ul>\n";
li += " </li>\n";
li += " </ul>\n";
li += "</li>\n";
// Add new html to document
$('#sortable').append(li);
// Write back to file
domHelper.write(layoutFileName, $).then(function () {
// Clean empty and useless dust helper created by removing <li>
var layoutContent = fs.readFileSync(layoutFileName, 'utf8');
// Remove empty dust helper
layoutContent = layoutContent.replace(/{#entityAccess entity=".+"}\W*{\/entityAccess}/g, "");
var writeStream = fs.createWriteStream(layoutFileName);
writeStream.write(layoutContent);
writeStream.end();
writeStream.on('finish', function () {
callback();
});
});
}).catch(function (err) {
callback(err, null);
});
});
});
});
});
}
exports.deleteAgenda = (attr, callback) => {
let appID = attr.id_application;
let urlComponent = attr.options.urlValue.toLowerCase();
let baseFolder = __dirname + '/../workspace/' + appID;
let layoutFileName = baseFolder + '/views/layout_' + attr.options.moduleName.toLowerCase() + '.dust';
// Remove agenda controller
fs.unlinkSync(baseFolder + '/routes/' + attr.options.value + '.js');
// Delete views folder
helpers.rmdirSyncRecursive(baseFolder + '/views/' + attr.options.value);
domHelper.read(layoutFileName).then($ => {
$("#" + urlComponent + "_menu_item").remove();
// Write back to file
domHelper.write(layoutFileName, $).then(_ => {
// Clean empty and useless dust helper created by removing <li>
let layoutContent = fs.readFileSync(layoutFileName, 'utf8');
// Remove empty dust helper
layoutContent = layoutContent.replace(/{#entityAccess entity=".+"}\W*{\/entityAccess}/g, "");
let writeStream = fs.createWriteStream(layoutFileName);
writeStream.write(layoutContent);
writeStream.end();
writeStream.on('finish', _ => {
callback();
});
});
}).catch(err => {
callback(err, null);
});
}
exports.newCra = function (attr, callback) {
try {
var workspacePath = __dirname + '/../workspace/' + attr.id_application;
var piecesPath = __dirname + '/../structure/pieces/component/cra';
// Copy pieces
fs.copySync(piecesPath + '/routes/e_cra.js', workspacePath + '/routes/e_cra.js');
fs.copySync(piecesPath + '/routes/e_cra_team.js', workspacePath + '/routes/e_cra_team.js');
fs.copySync(piecesPath + '/views/e_cra/', workspacePath + '/views/e_cra/');
fs.copySync(piecesPath + '/js/', workspacePath + '/public/js/Newmips/component/');
// Replace layout to point to current module
var files = ['admin_declare.dust', 'declare.dust', 'list.dust'];
for (var i = 0; i < files.length; i++) {
var view = fs.readFileSync(piecesPath + '/views/e_cra/' + files[i], 'utf8');
view = view.replace(/MODULE_NAME/g, attr.module.codeName);
fs.writeFileSync(workspacePath + '/views/e_cra/' + files[i], view, 'utf8');
}
// Create belongsToMany relation between team and activity for default activities
var teamOptionsPath = workspacePath + '/models/options/e_cra_team.json';
var teamOptionObj = require(teamOptionsPath);
teamOptionObj.push({
"target": "e_cra_activity",
"relation": "belongsToMany",
"through": attr.id_application + "_cra_activity_team",
"as": "r_default_cra_activity",
"foreignKey": "team_id",
"otherKey": "activity_id"
});
fs.writeFileSync(teamOptionsPath, JSON.stringify(teamOptionObj, null, 4));
var teamAttributesPath = workspacePath + '/models/attributes/e_cra_team.json';
var teamAttributesObj = require(teamAttributesPath);
teamAttributesObj.fk_id_admin_user = {type: "INTEGER", newmipsType: "integer"};
fs.writeFileSync(teamAttributesPath, JSON.stringify(teamAttributesObj, null, 4));
// Update user translations
translateHelper.updateLocales(attr.id_application, "fr-FR", ["entity", "e_user", "as_r_users"], "Utilisateurs");
translateHelper.updateLocales(attr.id_application, "fr-FR", ["entity", "e_user", "as_r_user"], "Utilisateur");
// Add all cra locales EN/FR
translateHelper.writeTree(attr.id_application, require(piecesPath + '/locales/en-EN'), 'en-EN');
translateHelper.writeTree(attr.id_application, require(piecesPath + '/locales/fr-FR'), 'fr-FR');
// Change CRA sidebar entry in current layout
domHelper.read(workspacePath + '/views/layout_' + attr.module.codeName + '.dust').then(function ($) {
var newLayoutLI = '';
newLayoutLI += '<li>\n';
newLayoutLI += ' <a href="/cra/declare">\n';
newLayoutLI += ' <i class="fa fa-angle-double-right"></i>\n';
newLayoutLI += ' <!--{#__ key="entity.e_cra.custom_button_declare" /}-->\n';
newLayoutLI += ' </a>\n';
newLayoutLI += '</li>\n';
$("#cra_menu_item").find('li:first').replaceWith(newLayoutLI);
domHelper.write(workspacePath + '/views/layout_' + attr.module.codeName + '.dust', $).then(function () {
// Remove unwanted tab from user
domHelper.read(workspacePath + '/views/e_user/show_fields.dust').then(function ($) {
$("#r_cra-click").parents('li').remove();
$("#r_cra").remove();
domHelper.write(workspacePath + '/views/e_user/show_fields.dust', $).then(function () {
callback(null, {message: 'Module C.R.A created'});
}).catch(callback);
}).catch(callback);
}).catch(callback);
}).catch(callback);
} catch (err) {
callback(err);
}
};
exports.newStatus = function (attr, callback) {
var workspacePath = __dirname + '/../workspace/' + attr.id_application;
var piecesPath = __dirname + '/../structure/pieces/component/status';
// Rename history model, options, attributes files and view folder
fs.renameSync(workspacePath + '/models/e_' + attr.history_table_db_name + '.js', workspacePath + '/models/e_' + attr.history_table + '.js');
fs.renameSync(workspacePath + '/models/attributes/e_' + attr.history_table_db_name + '.json', workspacePath + '/models/attributes/e_' + attr.history_table + '.json');
fs.renameSync(workspacePath + '/models/options/e_' + attr.history_table_db_name + '.json', workspacePath + '/models/options/e_' + attr.history_table + '.json');
fs.renameSync(workspacePath + '/views/e_' + attr.history_table_db_name, workspacePath + '/views/e_' + attr.history_table);
// Delete useless route and api history controllers
fs.unlinkSync(workspacePath + '/routes/e_' + attr.history_table_db_name + '.js');
fs.unlinkSync(workspacePath + '/api/e_' + attr.history_table_db_name + '.js');
// Change model name of history table
var historyModel = fs.readFileSync(workspacePath + '/models/e_' + attr.history_table + '.js', 'utf8');
historyModel = historyModel.replace(/([^_]e_)history_[^.]+.json/g, '$1' + attr.history_table + '.json');
historyModel = historyModel.replace(/(buildAssociation\(')([^']+)'/, '$1E_' + attr.history_table + '\'');
historyModel = historyModel.replace(/(sequelize.define\(')([^']+)'/, '$1E_' + attr.history_table + '\'');
historyModel = historyModel.replace(/(addHooks\(Model, ')([^']+)'/, '$1' + attr.history_table + '\'');
fs.writeFileSync(workspacePath + '/models/e_' + attr.history_table + '.js', historyModel, 'utf8');
// Add virtual status field to source entity (s_statusName)
var attributesObj = JSON.parse(fs.readFileSync(workspacePath + '/models/attributes/' + attr.source + '.json'));
attributesObj[attr.options.value] = {
type: "VIRTUAL",
history_table: 'e_' + attr.history_table_db_name,
history_model: 'e_' + attr.history_table
};
fs.writeFileSync(workspacePath + '/models/attributes/' + attr.source + '.json', JSON.stringify(attributesObj, null, 4), 'utf8');
// Replace history table name with history model name in access file
var access = JSON.parse(fs.readFileSync(workspacePath + '/config/access.json', 'utf8'));
for (var npsModule in access)
for (var i = 0; i < access[npsModule].entities.length; i++)
if (access[npsModule].entities[i].name == attr.history_table_db_name)
access[npsModule].entities[i].name = attr.history_table;
fs.writeFileSync(workspacePath + '/config/access.json', JSON.stringify(access, null, 4), 'utf8');
fs.writeFileSync(workspacePath + '/config/access.lock.json', JSON.stringify(access, null, 4), 'utf8');
// Change target of source entity to match history MODEL name (instead of TABLE name)
var optionsObj = JSON.parse(fs.readFileSync(workspacePath + '/models/options/' + attr.source + '.json'));
for (var opt in optionsObj)
if (optionsObj[opt].target == 'e_' + attr.history_table_db_name)
{optionsObj[opt].target = 'e_' + attr.history_table;break;}
fs.writeFileSync(workspacePath + '/models/options/' + attr.source + '.json', JSON.stringify(optionsObj, null, 4), 'utf8');
// Remove useless options on e_status
var statusModel = JSON.parse(fs.readFileSync(workspacePath + '/models/options/e_status.json'));
for (var i = 0; i < statusModel.length; i++)
if (statusModel[i].target == 'e_' + attr.history_table_db_name)
{statusModel.splice(i, 1);break;}
fs.writeFileSync(workspacePath + '/models/options/e_status.json', JSON.stringify(statusModel, null, 4), 'utf8');
// Remove useless options on e_user (association hasMany with history table needs to be removed)
var userModel = JSON.parse(fs.readFileSync(workspacePath + '/models/options/e_user.json'));
for (var i = 0; i < userModel.length; i++)
if (userModel[i].target == 'e_' + attr.history_table_db_name)
{userModel.splice(i, 1);break;}
fs.writeFileSync(workspacePath + '/models/options/e_user.json', JSON.stringify(userModel, null, 4), 'utf8');
// Remove useless options in toSync
var toSync = JSON.parse(fs.readFileSync(workspacePath + '/models/toSync.json', 'utf8'));
for (var prop in toSync) {
if (prop.indexOf('_e_status') > 0) {
for (var i = 0; i < toSync[prop].options.length; i++) {
if (toSync[prop].options[i].target.indexOf("e_history_") != -1) {
toSync[prop].options.splice(i, 1);
}
}
}
if (prop.indexOf('_e_history_') > 0)
toSync[prop].options = undefined;
}
fs.writeFileSync(workspacePath + '/models/toSync.json', JSON.stringify(toSync, null, 4), 'utf8');
// Remove useless history tab from Status views
domHelper.read(workspacePath + "/views/e_status/show_fields.dust").then(function ($) {
var historyId = 'r_' + attr.history_table;
$("#" + historyId + "-click").parent().remove();
$("#" + historyId).remove();
domHelper.write(workspacePath + "/views/e_status/show_fields.dust", $).then(function () {
// Replace traduction keys in show_fields
var show_fieldsFILE = fs.readFileSync(workspacePath + "/views/" + attr.source + "/show_fields.dust", 'utf8');
var reg = new RegExp(attr.history_table_db_name, 'g');
show_fieldsFILE = show_fieldsFILE.replace(reg, attr.history_table);
fs.writeFileSync(workspacePath + "/views/" + attr.source + "/show_fields.dust", show_fieldsFILE, 'utf8');
var statusAlias = 'r_' + attr.options.value.substring(2);
var statusAliasHTML = 'f_' + attr.options.value.substring(2);
var statusAliasSubstring = statusAlias.substring(2);
// Customize history tab list
domHelper.read(workspacePath + '/views/e_' + attr.history_table + '/list_fields.dust').then(function ($) {
// History list
{
// Remove buttons i.e last two th/td
$("tbody tr td").slice(5, 7).remove();
$("thead").each(function () {
$(this).find("tr th").slice(5, 7).remove();
});
// Remove id column
$("[data-field=id]").remove();
// Add createdAt column in thead/tbody
var newTh = '';
newTh += '<th data-field="createdAt" data-col="createdAt" data-type="date">\n';
newTh += ' <!--{#__ key="defaults.createdAt"/}-->\n';
newTh += '</th>\n';
$(".fields").each(function () {
$(this).find("th:eq(0)").before(newTh);
});
$("#bodyTR td:eq(2)").after('<td data-field="createdAt" data-type="text">{createdAt|datetime}</td>');
// Remove delete button
$("#bodyTR td:last").remove();
}
// LOCALS
{
// Change history tab locales
var localesFR = JSON.parse(fs.readFileSync(workspacePath + '/locales/fr-FR.json', 'utf8'));
localesFR.entity['e_' + attr.history_table_db_name]['as_r_history_' + attr.options.urlValue] = "Historique " + attr.options.showValue;
localesFR.entity['e_' + attr.history_table_db_name]['f_comment'] = "Commentaire";
localesFR.entity['e_' + attr.history_table_db_name]['r_modified_by'] = "Modifié par";
localesFR.entity['e_' + attr.history_table_db_name]['as_r_' + attr.history_table] = "Historique " + statusAliasSubstring + " " + attr.source.substring(2);
localesFR.entity['e_' + attr.history_table_db_name].label_entity = "Historique " + statusAliasSubstring + " " + attr.source.substring(2);
localesFR.entity['e_' + attr.history_table_db_name].name_entity = "Historique " + statusAliasSubstring + " " + attr.source.substring(2);
localesFR.entity['e_' + attr.history_table_db_name].plural_entity = "Historique " + statusAliasSubstring + " " + attr.source.substring(2);
// Rename traduction key to use history MODEL value, delete old traduction key
localesFR.entity['e_' + attr.history_table] = localesFR.entity['e_' + attr.history_table_db_name];
localesFR.entity['e_' + attr.history_table_db_name] = undefined;
// Change entity's status tab name for FR (Historique instead of History)
localesFR.entity[attr.source]['r_history_'+attr.options.urlValue] = "Historique "+attr.options.showValue;
fs.writeFileSync(workspacePath + '/locales/fr-FR.json', JSON.stringify(localesFR, null, 4), 'utf8');
var localesEN = JSON.parse(fs.readFileSync(workspacePath + '/locales/en-EN.json', 'utf8'));
localesEN.entity['e_' + attr.history_table_db_name]['as_r_' + attr.history_table] = "History " + attr.source.substring(2) + " " + statusAliasSubstring;
localesEN.entity['e_' + attr.history_table_db_name].label_entity = "History " + attr.source.substring(2) + " " + statusAliasSubstring;
localesEN.entity['e_' + attr.history_table_db_name].name_entity = "History " + attr.source.substring(2) + " " + statusAliasSubstring;
localesEN.entity['e_' + attr.history_table_db_name].plural_entity = "History " + attr.source.substring(2) + " " + statusAliasSubstring;
// Rename traduction key to use history MODEL value, delete old traduction key
localesEN.entity['e_' + attr.history_table] = localesEN.entity['e_' + attr.history_table_db_name];
localesEN.entity['e_' + attr.history_table_db_name] = undefined;
fs.writeFileSync(workspacePath + '/locales/en-EN.json', JSON.stringify(localesEN, null, 4), 'utf8');
}
domHelper.write(workspacePath + '/views/e_' + attr.history_table + '/list_fields.dust', $).then(function () {
// Replace history traductions with history_table key
var listFields = fs.readFileSync(workspacePath + '/views/e_' + attr.history_table + '/list_fields.dust', 'utf8');
var reg = new RegExp(attr.history_table_db_name, 'g');
listFields = listFields.replace(reg, attr.history_table);
fs.writeFileSync(workspacePath + '/views/e_' + attr.history_table + '/list_fields.dust', listFields, 'utf8');
// Display status as a badge instead of an input
// Also add next status buttons after status field
domHelper.read(workspacePath + '/views/' + attr.source + '/show_fields.dust').then(function ($) {
var statusBadgeHtml = '<br>\n<span class="badge" style="background: {' + statusAlias + '.f_color};">{' + statusAlias + '.f_name}</span>';
var nextStatusHtml = '';
nextStatusHtml += '<div class="form-group">\n';
nextStatusHtml += ' {#' + statusAlias + '.r_children ' + attr.source.substring(2) + 'id=id}\n';
nextStatusHtml += ' {#checkStatusPermission status=.}\n';
nextStatusHtml += ' <a data-href="/' + attr.source.substring(2) + '/set_status/{' + attr.source.substring(2) + 'id}/{f_field}/{id}" data-comment="{f_comment}" class="status btn btn-info" style="margin-right: 5px;"><!--{^f_button_label}{f_name}{:else}{f_button_label}{/f_button_label}--></a>\n';
nextStatusHtml += ' {/checkStatusPermission}\n';
nextStatusHtml += ' {/' + statusAlias + '.r_children}\n';
nextStatusHtml += '</div>\n';
$("div[data-field='" + statusAliasHTML + "']").find('input').replaceWith(statusBadgeHtml);
$("div[data-field='" + statusAliasHTML + "']").append(nextStatusHtml);
// Input used for default ordering
// Remove create button
var historyTabId = "#r_history_" + attr.options.urlValue;
$(historyTabId).find('a.btn-success').remove();
domHelper.write(workspacePath + '/views/' + attr.source + '/show_fields.dust', $).then(function () {
// Remove status field from update_fields and create_fields
domHelper.read(workspacePath + '/views/' + attr.source + '/create_fields.dust').then(function ($) {
$("div[data-field='" + statusAliasHTML + "']").remove();
domHelper.write(workspacePath + '/views/' + attr.source + '/create_fields.dust', $).then(function () {
domHelper.read(workspacePath + '/views/' + attr.source + '/update_fields.dust').then(function ($) {
$("div[data-field='" + statusAliasHTML + "']").remove();
domHelper.write(workspacePath + '/views/' + attr.source + '/update_fields.dust', $).then(function () {
// Update list field to show status color in datalist
domHelper.read(workspacePath + '/views/' + attr.source + '/list_fields.dust').then(function ($) {
$("th[data-field='" + statusAlias + "']").each(function () {
$(this).attr("data-type", "status");
});
$("td[data-field='" + statusAlias + "']").attr("data-type", "status");
$("td[data-field='" + statusAlias + "']").attr("data-color", "{" + statusAlias + ".f_color}");
domHelper.write(workspacePath + '/views/' + attr.source + '/list_fields.dust', $).then(function () {
translateHelper.writeLocales(attr.id_application, 'field', attr.source, [attr.options.value, attr.options.showValue], false, function () {