-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathProjectService.groovy
2314 lines (1962 loc) · 101 KB
/
ProjectService.groovy
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
package au.org.ala.merit
import au.org.ala.merit.config.EmailTemplate
import au.org.ala.merit.config.ProgramConfig
import au.org.ala.merit.config.ReportConfig
import au.org.ala.merit.reports.ReportGenerationOptions
import au.org.ala.merit.reports.ReportGenerator
import au.org.ala.merit.reports.ReportOwner
import grails.converters.JSON
import grails.plugin.cache.Cacheable
import groovy.util.logging.Slf4j
import org.apache.commons.lang.CharUtils
import org.apache.http.HttpStatus
import org.grails.web.json.JSONArray
import org.grails.web.json.JSONObject
import org.joda.time.*
import java.text.SimpleDateFormat
@Slf4j
class ProjectService {
static final String OUTCOMES_OUTPUT_TYPE = 'Outcomes'
static final String STAGE_OUTCOMES_OUTPUT_TYPE = ''
static final String COMPLETE = 'completed'
static final String APPLICATION_STATUS = 'Application'
static final String ACTIVE = 'active'
static final String OTHER_EMSA_MODULE = 'Other'
static final String PARATOO_FORM_TAG_SURVEY = 'survey'
static dateWithTime = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss")
static dateWithTimeFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
static convertTo = new SimpleDateFormat("dd MMM yyyy")
static final String PLAN_APPROVED = 'approved'
static final String PLAN_NOT_APPROVED = 'not approved'
static final String PLAN_SUBMITTED = 'submitted'
static final String PLAN_UNLOCKED = 'unlocked for correction'
public static final String DOCUMENT_ROLE_APPROVAL = 'approval'
public static final String FLATTEN_BY_SUM = "SUM"
public static final String FLATTEN_BY_COUNT = "COUNT"
public static final String DEFAULT_GROUP_BY = 'scientificName,vernacularName,scientificNameID,individualsOrGroups'
// All projects can use the Plot Selection and Layout, Plot Description and Opportune modules, but
// we don't want users recording data sets for Plot Selection and Layout so it's not included here.
final List DEFAULT_EMSA_MODULES = Collections.synchronizedList(['Plot Description', 'Opportune'])
def webService, grailsApplication, siteService, activityService, emailService, documentService, userService, metadataService, settingService, reportService, auditService, speciesService, commonService
ProjectConfigurationService projectConfigurationService
def programService
LockService lockService
DataSetSummaryService dataSetSummaryService
def get(id, levelOfDetail = "", includeDeleted = false) {
def params = '?'
params += levelOfDetail ? "view=${levelOfDetail}&" : ''
params += "includeDeleted=${includeDeleted}"
Map project = webService.getJson(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/' + id + params)
if (!project.reports) {
project.reports = reportService.getReportsForProject(id)
}
else {
project.reports.sort ({ it.toDate })
}
project
}
Map findStateAndElectorateForProject(String projectId) {
Map result = webService.getJson(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/findStateAndElectorateForProject?projectId=' + projectId) as Map
if (result.error) {
result = [:]
}
result
}
void filterDataSetSummaries(List dataSetSummaries) {
List<Map> forms = activityService.monitoringProtocolForms()
dataSetSummaries.removeAll { Map dataSetSummary ->
Map protocolForm = forms.find{it.externalId == dataSetSummary.protocol}
(protocolForm != null) && (!protocolForm.tags.contains(PARATOO_FORM_TAG_SURVEY))
}
}
/**
* Returns a filtered project view based on user needs. This will be implemented in ecodata as a part of the
* API changes but for now implementing it here is OK
*/
Map get(String id, Map user, levelOfDetail = "") {
Map project = get(id, levelOfDetail, false)
// Improving the project view will be done in ecodata
// This is a workaround until that's done.
if (!user?.hasViewAccess) {
project.documents = new JSONArray(project.documents.findAll{it.public})
project.remove('sites')
project.remove('activities')
project.remove('reports')
}
project
}
def getRich(id) {
get(id, 'rich')
}
/**
* This does a 'soft' delete. The record is marked as inactive but not removed from the DB.
* @param id the record to delete
* @return the returned status
*/
def delete(id) {
webService.doDelete(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/' + id)
}
/**
* This does a 'hard' delete. The record is removed from the DB.
* @param id the record to destroy
* @return the returned status
*/
def destroy(id) {
webService.doDelete(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/' + id + '?destroy=true')
}
boolean isComplete(Map project) {
return COMPLETE.equalsIgnoreCase(project.status)
}
/**
* Retrieves a summary of project metrics (including planned output targets)
* and groups them by output type.
* @param id the id of the project to get summary information for.
* @return TODO document this structure.
*/
def summary(String id, boolean approvedDataOnly = false, List scoreIds = null) {
Map result = projectSummary(id, approvedDataOnly, scoreIds)
def scores = result?.resp
def scoresWithTargetsByOutput = [:]
def scoresWithoutTargetsByOutputs = [:]
if (scores) { // If there was an error, it would be returning a map containing the error.
// There are some targets that have been saved as Strings instead of numbers.
scoresWithTargetsByOutput = scores.grep{ it.hasTarget() }.groupBy { it.outputType }
scoresWithoutTargetsByOutputs = scores.grep{ it.result && it.result.count && (it.result.result || it.result.groups) && !it.hasTarget() }.groupBy { it.outputType }
}
[targets:scoresWithTargetsByOutput, other:scoresWithoutTargetsByOutputs]
}
def search(params) {
webService.doPost(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/search', params)
}
/**
* Returns summary data derived from project activities.
* @param id The project id.
* @param approvedDataOnly If true, only data from approved activities will be used.
* @param scoreIds If supplied, only data for the supplied score ids will be returned.
* @return If the call to ecodata is successful a Map of the form: [resp: [<list of Score>]].
* If the call to ecodata fails, a Map of the form: [error: <message>, (optional)statusCode: <HTTP status of the call>]
*
*/
private Map projectSummary(String id, boolean approvedDataOnly = false, List scoreIds = null) {
String url = grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/projectMetrics/' + id
Map params = [approvedOnly:approvedDataOnly]
if (scoreIds) {
params.scoreIds = scoreIds
}
Map result = webService.doPost(url, params)
if (result.resp) {
result.resp = result.resp.collect{new Score(it)}
}
result
}
Map targetsAndScoresForActivity(String activityId) {
String url = grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/scoreDataForActivityAndProject/' + activityId
Map result = webService.getJson2(url)
if (result.statusCode == HttpStatus.SC_OK) {
List projectScores = result.resp?.projectScores?.collect{new Score(it)}.findAll({it.hasTarget()})
List scoreIdsWithTargets = projectScores.collect{it.scoreId}
result.resp.projectScores = projectScores
result.resp.activityScores = result.resp?.activityScores.collect{new Score(it)}.findAll{it.scoreId in scoreIdsWithTargets}
}
result
}
/**
* Returns true if the report identified by reportId belongs to the project identified by projectId.
*/
boolean doesReportBelongToProject(String projectId, String reportId) {
Map report = reportService.get(reportId)
report?.projectId == projectId
}
/**
* Returns true if the report identified by reportId belongs to the project identified by projectId.
*/
boolean doesActivityBelongToProject(String projectId, String activityId) {
Map activity = activityService.get(activityId)
activity?.projectId == projectId
}
/**
* Get the list of users (members) who have any level of permission for the requested projectId
*
* @param projectId
* @return
*/
def getMembersForProjectId(projectId) {
def url = grailsApplication.config.getProperty('ecodata.baseUrl') + "permissions/getMembersForProject/${projectId}"
webService.getJson(url)
}
/**
* Sends an email related to a project.
* @param emailTemplate a closure that will be passed the project configuration and should return an EmailTemplate
* @param project the project the email is about.
* @param initiatorRole the role of the user that initiated the email - this will determine whether grant managers
* or admins will be sent/copied on the email.
* @param senderEmail the email to use for the from address. Defaults to the current logged in user but
* is a parameter so a scheduled task can specify the merit support email address.
* @param model The model containing substitution parameters to be used by the email template
*/
void sendEmail(Closure<ProgramConfig> emailTemplate, Map project, String initiatorRole, String senderEmail = null, Map model = null) {
ProgramConfig config = projectConfigurationService.getProjectConfiguration(project)
List roles = getMembersForProjectId(project.projectId)
EmailTemplate template = emailTemplate(config)
if (!model) {
model = [project:project]
}
emailService.sendEmail(template, model, roles, initiatorRole, senderEmail)
}
/**
* Does the current user have permission to administer the requested projectId?
* Checks for the ADMIN role in CAS and then checks the UserPermission
* lookup in ecodata.
*
* @param userId
* @param projectId
* @return boolean
*/
def isUserAdminForProject(userId, projectId) {
def userIsAdmin
if (userService.userIsSiteAdmin()) {
userIsAdmin = true
} else {
def url = grailsApplication.config.getProperty('ecodata.baseUrl') + "permissions/isUserAdminForProject?projectId=${projectId}&userId=${userId}"
userIsAdmin = webService.getJson(url)?.userIsAdmin // either will be true or false
}
userIsAdmin
}
/**
* Does the current user have caseManager permission for the requested projectId?
*
* @param userId
* @param projectId
* @return
*/
def isUserCaseManagerForProject(userId, projectId) {
def url = grailsApplication.config.getProperty('ecodata.baseUrl') + "permissions/isUserCaseManagerForProject?projectId=${projectId}&userId=${userId}"
webService.getJson(url)?.userIsCaseManager // either will be true or false
}
/**
* Does the current user have permission to view details of the requested projectId?
* @param userId the user to test.
* @param the project to test.
*/
def canUserViewProject(userId, projectId) {
def userCanView
if (userService.userIsSiteAdmin() || userService.userHasReadOnlyAccess()) {
userCanView = true
}
else {
userCanView = canUserEditProject(userId, projectId)
}
userCanView
}
/**
* Returns the programs model for use by a particular project. At the moment, this method just delegates to the metadataservice,
* however a per organisation programs model is something being discussed.
*/
def programsModel() {
metadataService.programsModel()
}
/**
* Returns a filtered list of activities for use by a project
*/
public List activityTypesList(String projectId) {
def projectSettings = settingService.getProjectSettings(projectId)
def activityTypes = metadataService.activityTypesList()
def allowedActivities = activityTypes
if (projectSettings?.allowedActivities) {
allowedActivities = []
activityTypes.each { category ->
def matchingActivities = []
category.list.each { nameAndDescription ->
if (nameAndDescription.name in projectSettings.allowedActivities) {
matchingActivities << nameAndDescription
}
}
if (matchingActivities) {
allowedActivities << [name:category.name, list:matchingActivities]
}
}
}
allowedActivities
}
/**
* Updates a project, taking actions as required where important fields (e.g. dates) are changed.
* @param id the projectId
* @param projectDetails the data to update
* @param byPassLockCheck Updates to the MERI plan by users need a lock, however some operations
* (e.g. data set updates need to merge the custom object, the org report can bulk update annoucements) can
* be performed without a lock.
* @return
*/
def update(String id, Map projectDetails, boolean bypassMeriPlanLockCheck = true) {
def defaultTimeZone = TimeZone.default
TimeZone.setDefault(TimeZone.getTimeZone('UTC'))
def resp = [:]
Map options = projectDetails.remove('options')
// Changing project dates requires some extra validation and updates to the stage reports. Only
// do this check for existing projects for which the planned start and/or end date is being changed
boolean regenerateReports = false
if (id) {
String plannedStartDate = projectDetails.remove('plannedStartDate')
String plannedEndDate = projectDetails.remove('plannedEndDate')
def currentProject = get(id)
if (plannedStartDate || plannedEndDate) {
if (currentProject.plannedStartDate != plannedStartDate || currentProject.plannedEndDate != plannedEndDate) {
resp = changeProjectDates(id, plannedStartDate ?: currentProject.plannedStartDate, plannedEndDate ?: currentProject.plannedEndDate, options)
}
}
// If the project name has changed, we need to regenerate reports to update any occurrences of the project name
if (projectDetails.name) {
if (currentProject.name != projectDetails.name) {
if (nameChangeAllowed(currentProject)) {
regenerateReports = true
}
else {
projectDetails.remove('name')
}
}
}
// Don't allow MERI plan updates unless the user holds the lock.
// Since it is modelled as an embedded object, we manually update the lastUpdated date as GORM
// won't do it automatically.
// The MERI Plan and data set summaries should be modelled as separate entities in a future change.
if (projectDetails.custom) {
if (projectDetails.custom.details && !bypassMeriPlanLockCheck && !lockService.userHoldsLock(currentProject.lock)) {
return [error:'MERI plan is locked by another user', noLock:true]
}
projectDetails.custom.details?.lastUpdated = DateUtils.formatAsISOStringNoMillis(new Date())
}
}
if (projectDetails) {
resp = updateUnchecked(id, projectDetails)
}
// We need to regenerate the reports because of the name change. We do this after the update so the name
// change has occurred.
if (!resp?.error && regenerateReports) {
generateProjectStageReports(id, new ReportGenerationOptions())
}
TimeZone.setDefault(defaultTimeZone)
return resp
}
/**
* For most projects, only FC_ADMINs can change the project name. RLP projects are allowed name changes
* via the MERI plan workflow.
*/
private boolean nameChangeAllowed(Map project) {
ProgramConfig config = projectConfigurationService.getProjectConfiguration(project)
return userService.userIsAlaOrFcAdmin() || (!isMeriPlanSubmittedOrApproved(project) && config.getProjectTemplate() == ProgramConfig.ProjectTemplate.RLP)
}
/** Extracts date change options from a payload */
ReportGenerationOptions dateChangeOptions(Map payload) {
Map options = [:]
// These are configuration items containing instructions for how to modify dates, not project information.
options.updateActivities = Boolean.valueOf(payload?.changeActivityDates)
options.includeSubmittedAndApprovedReports = Boolean.valueOf(payload?.includeSubmittedReports)
options.keepExistingReportDates = Boolean.valueOf(payload?.keepReportEndDates)
options.dateChangeReason = payload?.dateChangeReason
new ReportGenerationOptions(options)
}
private updateUnchecked(String id, Map projectDetails) {
webService.doPost(grailsApplication.config.getProperty('ecodata.baseUrl') + 'project/' + id, projectDetails)
}
/**
* Does the current user have permission to edit the requested projectId?
* Checks for the ADMIN role in CAS and then checks the UserPermission
* lookup in ecodata.
*
* @param userId
* @param projectId
* @return boolean
*/
def canUserEditProject(userId, projectId) {
def userCanEdit
if (userService.userIsSiteAdmin()) {
userCanEdit = true
} else {
def url = grailsApplication.config.getProperty('ecodata.baseUrl') + "permissions/canUserEditProject?projectId=${projectId}&userId=${userId}"
userCanEdit = webService.getJson(url)?.userIsEditor?:false
}
userCanEdit
}
Map lockMeriPlanForEditing(String projectId) {
Map project = get(projectId)
if (!project.planStatus || project.planStatus == PLAN_NOT_APPROVED) {
Map resp = lockService.lock(projectId)
if (resp.resp && !resp.resp.error) {
return [message:'success']
}
else {
return [error:resp?.resp?.error]
}
}
return [error:'Invalid plan status']
}
Map overrideLock(String projectId, String entityUrl) {
Map project = get(projectId)
lockService.stealLock(projectId, project, entityUrl, SettingPageType.PROJECT_LOCK_STOLEN_EMAIL_SUBJECT, SettingPageType.PROJECT_LOCK_STOLEN_EMAIL)
// This is done in the projectService instead of the lockService as the
// same use case for an Activity has the lock aquired as a part of the redirect
lockService.lock(projectId)
}
def submitPlan(String projectId) {
def project = get(projectId)
if (!project.planStatus || project.planStatus == PLAN_NOT_APPROVED) {
if (project.lock && project.lock?.userId != userService.getCurrentUserId()) {
return [error:'MERI plan is locked by another user']
}
else {
if (project.lock) {
lockService.unlock(projectId)
}
def resp = update(projectId, [planStatus: PLAN_SUBMITTED])
if (resp.resp && !resp.resp.error) {
sendEmail({ ProgramConfig programConfig -> programConfig.getPlanSubmittedTemplate() }, project, RoleService.PROJECT_ADMIN_ROLE)
return [message: 'success']
} else {
return [error: "Update failed: ${resp?.resp?.error}"]
}
}
}
return [error:'Invalid plan status']
}
def approvePlan(String projectId, Map approvalDetails) {
def project = get(projectId)
if (project.planStatus == PLAN_SUBMITTED) {
//The MERI plan cannot be approved until an internal order number has been supplied for the project.
if (!validateExternalIds(project.externalIds)) {
return [error: 'A SAP internal order or TechOne code must be supplied before the MERI Plan can be approved']
}
//When the MERI plan is first approved, the status is changed to "active"
def resp = project.status == APPLICATION_STATUS ? update(projectId, [planStatus:PLAN_APPROVED, status:ACTIVE])
: update(projectId, [planStatus:PLAN_APPROVED])
if (resp.resp && !resp.resp.error) {
createMeriPlanApprovalDocument(project, approvalDetails)
sendEmail({ProgramConfig programConfig -> programConfig.getPlanApprovedTemplate()}, project, RoleService.GRANT_MANAGER_ROLE)
return [message:'success']
}
else {
return [error:"Update failed: ${resp?.resp?.error}"]
}
}
return [error:'Invalid plan status']
}
/** The list of external ids needs to include at least one SAP Internal Order or one Tech One Project Code */
private boolean validateExternalIds(List externalIds) {
List requiredIdTypes = ["INTERNAL_ORDER_NUMBER", "TECH_ONE_CODE"]
externalIds?.find{it.idType in requiredIdTypes && it.externalId}
}
boolean requiresMERITAdminToModifyPlan(Map project) {
ProgramConfig config = projectConfigurationService.getProjectConfiguration(project)
config.requireMeritAdminToReturnMeriPlan
}
def rejectPlan(String projectId) {
def project = get(projectId)
if (project.planStatus == PLAN_APPROVED && requiresMERITAdminToModifyPlan(project) && !userService.userIsAlaOrFcAdmin()) {
return [error: 'Only MERIT admins can return MERI plans for this program']
}
if (project.planStatus in [PLAN_SUBMITTED, PLAN_APPROVED]) {
def resp = update(projectId, [planStatus:PLAN_NOT_APPROVED])
if (resp.resp && !resp.resp.error) {
sendEmail({ProgramConfig programConfig -> programConfig.getPlanReturnedTemplate()}, project, RoleService.GRANT_MANAGER_ROLE)
return [message:'success']
}
else {
return [error:"Update failed: ${resp?.resp?.error}"]
}
}
return [error:'Invalid plan status']
}
Map unlockPlanForCorrection(String projectId, String approvalText) {
Map project = get(projectId)
if (isComplete(project) && project.planStatus == PLAN_APPROVED) {
Map resp = update(projectId, [planStatus:PLAN_UNLOCKED])
if (resp.resp && !resp.resp.error) {
Map doc = [name:"Approval to correct project information for "+project.projectId, projectId:projectId, type:'text', role: DOCUMENT_ROLE_APPROVAL, labels:['correction'], filename:project.projectId+'-correction-approval.txt', readOnly:true, "public":false]
String user = userService.getCurrentUserDisplayName()
String content = "User ${user} has unlocked project "+project.projectId+" for correction. \nDeclaration:\n"+approvalText
documentService.createTextDocument(doc, content)
return [message:'success']
}
else {
return [error:"Update failed: ${resp?.resp?.error}"]
}
}
return [error:'Cannot unlock the plan: invalid project status']
}
Map finishedCorrectingPlan(String projectId) {
Map project = get(projectId)
if (isComplete(project) && project.planStatus == PLAN_UNLOCKED) {
Map resp = update(projectId, [planStatus:PLAN_APPROVED])
if (resp.resp && !resp.resp.error) {
return [message:'success']
}
else {
return [error:"Update failed: ${resp?.resp?.error}"]
}
}
return [error:'Cannot finish correcting the plan: invalid project status']
}
/**
* Retrieves / sets up the data that is required by project report state changes (submission / approval / rejection).
*/
private Map prepareReport(String projectId, Map reportDetails) {
reportDetails.projectId = projectId
Map project = get(projectId, 'all')
Map report = project?.reports?.find{it.reportId == reportDetails.reportId}
if (!report) {
return [error:'Invalid reportId supplied']
}
ProgramConfig config = projectConfigurationService.getProjectConfiguration(project)
List roles = getMembersForProjectId(project.projectId)
return [project: project, roles: roles, report:report, config: config]
}
/**
* Submits a report of the activities performed during a specific time period (a project stage).
* @param projectId the project the performing the activities.
* @param reportDetails details of the report, including the ids of the activities being reported against.
* @return a Map containing a boolean flag "success" and a String "error" if success == false
*/
Map submitReport(String projectId, Map reportDetails) {
Map reportInformation = prepareReport(projectId, reportDetails)
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
EmailTemplate emailTemplate = ((ProgramConfig)reportInformation.config).getReportSubmittedTemplate()
Map result = reportService.submitReport(reportDetails.reportId, reportDetails.activityIds, reportInformation.project, reportInformation.roles, emailTemplate)
if (result.success) {
createStageReportDocument(reportInformation.project, reportDetails, reportInformation.report)
}
result
}
/**
* Creates a PDF document containing details of the report and attaches it as a document to the project.
*/
private void createStageReportDocument(Map project, Map reportDetails, Map report) {
String projectId = project.projectId
String stageName = reportDetails.stage ?: report.name
String stageNum = ''
if (stageName.indexOf('Stage ') == 0) {
stageNum = stageName.substring('Stage '.length(), stageName.length())
}
def param = [project: project, activities: project.activities, report: report, status: "Report submitted"]
def htmlTxt = createHTMLStageReport(param)
def dateWithTime = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss")
def name = project?.grantId + '_' + stageName + '_' + dateWithTime.format(new Date()) + ".pdf"
def doc = [name: name, projectId: projectId, saveAs: 'pdf', type: 'pdf', role: 'stageReport', filename: name, readOnly: true, "public": false, stage: stageNum]
documentService.createTextDocument(doc, htmlTxt)
}
/**
* Approves a submitted report.
* @param projectId the owner of the report.
* @param reportDetails details of the report and the related activities, specifically a list of activity ids.
*/
Map approveReport(String projectId, Map reportDetails) {
Map reportInformation = prepareReport(projectId, reportDetails)
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
EmailTemplate emailTemplate = ((ProgramConfig)reportInformation.config).getReportApprovedTemplate()
Map result = reportService.approveReport(reportDetails.reportId, reportDetails.activityIds, reportDetails.reason, reportInformation.project, reportInformation.roles, emailTemplate)
if (result && result.success) {
createReportApprovalDocument(reportInformation.project, reportDetails)
// Close the project when the last stage report is approved.
if (isFinalReportApproved(reportInformation.project, reportDetails.reportId)) {
completeProject(projectId)
}
}
result
}
private boolean isFinalReportApproved(Map project, String approvedReportId) {
// Close the project when the last stage report is approved.
// Some projects have extra stage reports after the end date due to legacy data so this checks we've got the last stage within the project dates
List validReports = project.reports?.findAll{it.fromDate < project.plannedEndDate ? it.fromDate : project.plannedStartDate}
List incompleteReports = (validReports?.findAll{PublicationStatus.requiresAction(it.publicationStatus)})?:[]
return incompleteReports.size() ==1 && incompleteReports[0].reportId == approvedReportId
}
private void createReportApprovalDocument(Map project, Map reportDetails) {
def readableId = project.grantId + (project.externalId?'-'+project.externalId:'')
def name = "${readableId} ${reportDetails.stage} approval"
def doc = [name:name, projectId:project.projectId, type:'text', role: DOCUMENT_ROLE_APPROVAL, filename:name, readOnly:true, "public":false, reportId:reportDetails.reportId]
documentService.createTextDocument(doc, (project as JSON).toString())
}
/**
* Records the details of the MERI plan approval in a text document.
* @param project the project that has had the MERI plan approved
* @param approvalDetails information supplied by the approver.
*/
private void createMeriPlanApprovalDocument(Map project, Map approvalDetails) {
def readableId = project.grantId + (project.externalId?'-'+project.externalId:'')
def name = "${readableId} MERI plan approved ${approvalDetails.dateApproved}"
if (!approvalDetails.dateApproved) {
approvalDetails.dateApproved = DateUtils.format(new DateTime().withZone(DateTimeZone.UTC))
}
approvalDetails.approvedBy = userService.getCurrentUserId()
DateTime dateApproved = DateUtils.parse(approvalDetails.dateApproved)
String filename = 'meri-approval-'+project.projectId+"-"+dateApproved.getMillis()+'.txt'
Map approvalContent = new HashMap(approvalDetails)
approvalContent.project = project
def doc = [name:name, projectId:project.projectId, type:'text', role: DOCUMENT_ROLE_APPROVAL, filename:filename, readOnly:true, "public":false, labels:['MERI']]
documentService.createTextDocument(doc, (approvalContent as JSON).toString())
}
private void completeProject(String projectId) {
Map values = [status:COMPLETE]
update(projectId, values)
}
/**
* Rejects / returns for rework a submitted report.
* @param projectId the project the performing the activities.
* @param reportDetails details of the activities, specifically a list of activity ids.
*/
def rejectReport(String projectId, Map reportDetails) {
Map reportInformation = prepareReport(projectId, reportDetails)
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
EmailTemplate emailTemplate = ((ProgramConfig)reportInformation.config).getReportReturnedTemplate()
Map result = reportService.rejectReport(reportDetails.reportId, reportDetails.activityIds, reportDetails.reason, reportDetails.categories, reportInformation.project, reportInformation.roles, emailTemplate)
result
}
def cancelReport(String projectId, Map reportDetails) {
Map reportInformation = prepareReport(projectId, reportDetails)
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
Map result = reportService.cancelReport(reportDetails.reportId, reportDetails.activityIds, reportDetails.reason, reportInformation.project, reportInformation.roles)
result
}
def unCancelReport(String projectId, Map reportDetails) {
Map reportInformation = prepareReport(projectId, reportDetails)
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
Map result = reportService.unCancelReport(reportDetails.reportId, reportDetails.activityIds, reportDetails.reason, reportInformation.project, reportInformation.roles)
result
}
/**
* Creates a report to offset the scores produced by the supplied report without having to unapprove the original report and edit the data.
* @param projectId the project the report belongs to.
* @param reportId identifies the report to adjust
* @param adjustmentReason the reason for the adjustment.
* @return a Map containing the result of the adjustment, including a error key it if failed.
*/
Map adjustReport(String projectId, String reportId, String adjustmentReason) {
Map reportInformation = prepareReport(projectId, [reportId:reportId])
if (reportInformation.error) {
return [success:false, error:reportInformation.error]
}
EmailTemplate emailTemplate = ((ProgramConfig)reportInformation.config).getReportAdjustedTemplate()
reportService.createAdjustmentReport(reportId, adjustmentReason, reportInformation.config, reportInformation.project, reportInformation.roles, emailTemplate)
}
/**
* Deletes the activities associated with a report.
*/
Map deleteReportActivities(String reportId, List<String> activityIds) {
Map report = reportService.get(reportId)
Map result
if (!reportService.excludesNotApproved(report)) {
result = activityService.bulkDeleteActivities(activityIds)
}
else {
result = [status:HttpStatus.SC_BAD_REQUEST, error:"Cannot delete submitted or approved stages"]
}
return result
}
/**
* This method changes a project start and end date
*
* @param projectId the ID of the project
* @param plannedStartDate an ISO 8601 formatted date string describing the new start date of the project.
* * @param plannedStartDate an ISO 8601 formatted date string describing the new end date of the project.
* @param updateActivities set to true if existing activities should be modified to fit into the new schedule
*/
def changeProjectDates(String projectId, String plannedStartDate, String plannedEndDate, Map options = [:]) {
Map response
Map project = get(projectId)
String previousStartDate = project.plannedStartDate
ReportGenerationOptions dateChangeOptions = dateChangeOptions(options)
String validationResult = validateProjectDates(projectId, plannedStartDate, plannedEndDate, dateChangeOptions)
if (validationResult == null) {
// The update method in this class treats dates specially and delegates the updates to this method.
response = updateUnchecked(projectId, [plannedStartDate:plannedStartDate, plannedEndDate:plannedEndDate])
//user explicitly generates the report from the reporting tab
generateProjectStageReports(projectId, dateChangeOptions)
if (dateChangeOptions.updateActivities) {
updateActivityDates(projectId, previousStartDate)
}
}
else {
response = [resp:[error: validationResult]]
}
response
}
boolean isMeriPlanSubmittedOrApproved(Map project) {
return (project.planStatus == PLAN_SUBMITTED || project.planStatus == PLAN_APPROVED)
}
String validateProjectDates(String projectId, String plannedStartDate, String plannedEndDate, ReportGenerationOptions options) {
if (plannedStartDate > plannedEndDate) {
return "Start date must be before end date"
}
Map project = get(projectId, 'all')
ProgramConfig config = projectConfigurationService.getProjectConfiguration(project)
String startDateMessage = validateProjectStartDate(project, config, plannedStartDate, options)
String endDateMessage = validateProjectEndDate(project, config, plannedEndDate, options)
String message = [startDateMessage, endDateMessage].findAll().join('\n')
message ?: null // Return null rather than an empty string
}
private String validateProjectEndDate(Map project, ProgramConfig config, String plannedEndDate, ReportGenerationOptions options) {
if (project.plannedEndDate == plannedEndDate) {
// The start date hasn't changed
return null
}
String message
if (config.activityBasedReporting) {
if (!options.updateActivities) {
Map lastActivity = project.activities?.max{it.plannedEndDate}
if (lastActivity && plannedEndDate < lastActivity.plannedEndDate) {
message = "The project end date must be on or after ${DateUtils.isoToDisplayFormat(lastActivity.plannedEndDate)}"
}
}
}
else {
Map lastReport = reportService.lastReportWithDataByCriteria(project.reports, {it.toDate})
String plannedEndDateAlignedToReportingSchedule = DateUtils.format(DateUtils.parse(plannedEndDate).plusDays(1))
// We allow reports to be generated up to 24 hours after the end of a project due to
// project end dates being 00:00 of the last day of the project instead of 23:59:...
if (lastReport) {
ReportConfig reportConfig = config.findProjectReportConfigForReport(lastReport)
String lastReportFromDate = DateUtils.format(DateUtils.parse(lastReport?.fromDate).plusDays(reportConfig.minimumReportDurationInDays))
if (plannedEndDateAlignedToReportingSchedule < lastReportFromDate) {
message = "The project end date must be on or after ${DateUtils.isoToDisplayFormat(DateUtils.format(DateUtils.parse(lastReportFromDate).minusDays(1)))}"
}
}
}
message
}
/**
* Returns null if the project dates can be changed. Otherwise returns an error message. Rules for
* date changes for activity based (non-RLP) projects are different to RLP projects.
*/
private String validateProjectDatesForActivityBasedProjects(Map project, String plannedStartDate, ReportGenerationOptions options) {
String result = null
// Allow FC_ADMINS to change project dates even with an approved plan as they are likely just
// correcting bad data.
boolean projectHasApprovedOrSubmittedReports = reportService.includesSubmittedOrApprovedReports(project.reports)
if (!userService.userIsAlaOrFcAdmin()) {
if (isMeriPlanSubmittedOrApproved(project)) {
result = "Cannot change project dates when the MERI plan is approved"
}
if (project.plannedStartDate != plannedStartDate && projectHasApprovedOrSubmittedReports) {
result = "Cannot change the start date of a project with submitted or approved reports"
}
}
else {
if (projectHasApprovedOrSubmittedReports && !options.includeSubmittedAndApprovedReports) {
result = "Cannot change the start date of a project with submitted or approved reports"
}
}
if (!result && !options.updateActivities) {
Map firstActivity = project.activities?.min{it.plannedStartDate}
if (firstActivity && plannedStartDate > firstActivity.plannedStartDate) {
result = "The project start date must be before the first activity in the project ( ${DateUtils.isoToDisplayFormat(firstActivity.plannedStartDate)} )"
}
}
return result
}
String validateProjectStartDate(Map project, ProgramConfig config, String plannedStartDate, ReportGenerationOptions options) {
if (project.plannedStartDate == plannedStartDate) {
// The start date hasn't changed
return null
}
String message
if (config.activityBasedReporting) {
message = validateProjectDatesForActivityBasedProjects(project, plannedStartDate, options)
}
else {
Map firstReport = reportService.firstReportWithDataByCriteria(project.reports, {report -> report.toDate})
if (firstReport) {
if (plannedStartDate > firstReport.toDate) {
message = "Data exists for ${firstReport.name}. The project start date must be before ${DateUtils.isoToDisplayFormat(firstReport.toDate)}."
} else {
// If there are reports containing data, don't allow the start date to be moved backwards in time
// far enough to introduce a new report as the rules for that are not implemented.
ReportGenerator generator = new ReportGenerator()
ReportOwner owner = projectReportOwner(project)
owner.periodStart = plannedStartDate
config.projectReports?.each { Map reportConfig ->
List reports = generator.generateReports(new ReportConfig(reportConfig), owner, 1, null)
int matchingReportIndex = reports.findIndexOf{DateUtils.within(DateUtils.parse(firstReport.toDate), DateUtils.parse(it.toDate), Period.days(1))}
int currentReportIndex = project.reports.findIndexOf{it == firstReport}
if (matchingReportIndex > currentReportIndex) {
message = "The project start date must be on or after ${DateUtils.isoToDisplayFormat(reports[matchingReportIndex - currentReportIndex].fromDate)}"
}
}
}
}
}
return message
}
Map getProgramConfiguration(Map project) {
if (!project) {
return [:]
}
projectConfigurationService.getProjectConfiguration(project)
}
private ReportOwner projectReportOwner(Map project) {
new ReportOwner(
id:[projectId:project.projectId],
name:project.name,
periodStart:project.plannedStartDate,
periodEnd:project.plannedEndDate
)
}
/**
* Creates or re-creates project reports according the supplied configuration and project dates.
*
* @param reportConfig defines the type of report and the dates required.
* @param project the project the reports are for
* @param includeSubmittedAndApproved if true, submitted and approved reports can be regenerated or moved. This should be used with caution.
* @param deleteReportsBeforeNewStartDate if true, if the project start date is after the end date of a report, the report will be deleted
* rather than the dates changed to match the new project dates. This was designed for situations (e.g.) RLP where
* empty reports exist because the projects were loaded with a start date earlier than the actual execution date
* (due to those dates not being known) and the dates being updated after more than one reporting period has passed.
* (e.g the 2nd report has data against correct dates, so we dont' want to move this, instead we delete the first report).
*/
private void generateProjectReports(String category, List<Map> reportConfig, Map project, ReportGenerationOptions options) {
if (canRegenerateReports(project)) {
ReportOwner reportOwner = projectReportOwner(project)
List<ReportConfig> configs = reportConfig.collect{new ReportConfig(it)}
List reportsOfType = project.reports?.findAll{it.category == category}?.sort{it.toDate}
if (options.includeSubmittedAndApprovedReports) {
int index = 0
// To keep existing reporting dates when we move the start date forward we may need to delete reports
// that have been excluded by the new start date. (rather than moving it forward)
if (options.keepExistingReportDates) {
Map report = reportsOfType ? reportsOfType[index] : null
// Handle reports that may have been cut off by the start date change.
while (report && report.toDate <= project.plannedStartDate) {
if (!reportService.hasData(report)) {
reportService.delete(report.reportId)
}
else {
log.warn("Unable to delete report ${report.name} with toDate ${report.toDate} as it has data.")
}
report = reportsOfType ? reportsOfType[++index] : null
}
}
reportService.regenerateReports(reportsOfType, configs, reportOwner, index-1)
}