-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathOrganisationService.groovy
457 lines (368 loc) · 17.9 KB
/
OrganisationService.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
package au.org.ala.merit
import au.org.ala.merit.config.EmailTemplate
import au.org.ala.merit.config.ReportConfig
import au.org.ala.merit.reports.ReportOwner
import org.grails.web.json.JSONArray
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.Period
/**
* Extends the plugin OrganisationService to provide Green Army reporting capability.
*/
class OrganisationService {
public static final String RCS_CONTRACTED_FUNDING = 'rcsContractedFunding'
def grailsApplication, webService, metadataService, projectService, userService, searchService, activityService, emailService, reportService, documentService
AbnLookupService abnLookupService
private static def APPROVAL_STATUS = ['unpublished', 'pendingApproval', 'published']
public static Comparator<String> APPROVAL_STATUS_COMPARATOR = {a,b -> APPROVAL_STATUS.indexOf(a) <=> APPROVAL_STATUS.indexOf(b)}
// This is the behaviour we want for green army. it may be extendible to other programs (e.g.
// biodiversity fund has a stage report and end of project report)
private static def GREEN_ARMY_REPORT_CONFIG = [
[type: 'Performance expectations framework - self assessment worksheet', period: Period.years(1), bulkEditable: true, businessDaysToCompleteReport:5, adhoc:true]
]
def get(String id, view = '') {
String url = "${grailsApplication.config.getProperty('ecodata.baseUrl')}organisation/$id?view=$view"
Map resp = webService.getJson2(url)
Map organisation = resp?.resp
if (view != 'flat') {
organisation.reports = getReportsForOrganisation(organisation, getReportConfig(id))
}
// If the user is an admin for a management unit or has the FC_READ_ONLY role, they are allowed
// to view the reports and all documents.
boolean hasExtendedAccess = userService.isUserAdminForOrganisation(userService.getCurrentUserId(), id) || userService.userHasReadOnlyAccess()
Map documentSearchParameters = [organisationId: id]
if (!hasExtendedAccess) {
documentSearchParameters['public'] = true
}
Map results = documentService.search(documentSearchParameters)
if (results && results.documents) {
List categorisedDocs = results.documents.split{it.type == DocumentService.TYPE_LINK}
organisation.documents = new JSONArray(categorisedDocs[1])
}
Map orgContractNames = [:]
organisation.projects?.each { Map project ->
project.associatedOrgs?.each { Map associatedOrg ->
if (associatedOrg.organisationId == id) {
if (!orgContractNames[associatedOrg.name]) {
orgContractNames[associatedOrg.name] = []
}
orgContractNames[associatedOrg.name] << [projectId: project.projectId, projectName: project.name]
}
}
}
organisation.contractNamesAndProjects = orgContractNames
organisation
}
def list() {
metadataService.organisationList()
}
Map findOrgByAbn(String abnNumber) {
return list().list.find({ it.abn == abnNumber }) as Map
}
String checkExistingAbnNumber(String organisationId, String abnNumber) {
String error = null
// We are allowing a blank ABN for now, this rule may change
if (abnNumber) {
Map organisation = findOrgByAbn(abnNumber)
if (organisation && organisation.organisationId != organisationId) {
error = "Abn Number is not unique"
}
}
return error
}
Map update(String id, Map organisation) {
Map result = [:]
String abn = organisation.abn
String error = null
if (organisation.organisationId && organisation.organisationId != id) {
// We don't want to update the organisationId
error = 'Invalid organisationId supplied'
}
else {
error = checkExistingAbnNumber(id,abn)
}
if (error) {
result.error = error
result.detail = error
}
else {
if (!id) {
// Assign the MERIT hubId to the organisation when creating a new organisation
organisation.hubId = SettingService.hubConfig?.hubId
id = ''
}
def url = "${grailsApplication.config.getProperty('ecodata.baseUrl')}organisation/$id"
result = webService.doPost(url, organisation)
metadataService.clearOrganisationList()
result
}
return result
}
void regenerateReports(String id, List<String> organisationReportCategories = null) {
Map organisation = get(id)
regenerateOrganisationReports(organisation, organisationReportCategories)
}
List<Map> generateTargetPeriods(String id) {
Map organisation = get(id)
generateTargetPeriods(organisation)
}
List<Map> generateTargetPeriods(Map organisation) {
Map targetsConfig = organisation.config?.targets
if (!targetsConfig) {
log.info("No target configuration defined for organisation ${organisation.organisationId}")
return null
}
ReportConfig targetsReportConfig = new ReportConfig(targetsConfig.periodGenerationConfig)
ReportOwner owner = new ReportOwner(
id:[organisationId:organisation.organisationId],
name:organisation.name
)
reportService.generateTargetPeriods(targetsReportConfig, owner, targetsConfig.periodLabelFormat)
}
double getRcsFundingForPeriod(Map organisation, String periodEndDate) {
int index = findIndexOfPeriod(organisation, periodEndDate)
def result = 0
if (index >= 0) {
Map rcsFunding = getRcsFunding(organisation)
result = rcsFunding?.costs[index]?.dollar ?: 0
}
result
}
private static int findIndexOfPeriod(Map organisation, String periodEndDate) {
List fundingHeaders = organisation.custom?.details?.funding?.headers
String previousPeriod = ''
fundingHeaders.findIndexOf {
String period = it.data.value
boolean result = previousPeriod < periodEndDate && period >= periodEndDate
previousPeriod = period
result
}
}
/** Returns the funding row used to collect RCS funding data */
private static Map getRcsFunding(Map organisation) {
// The funding recorded for an organisation is specific to RCS reporting.
// Instead of being a "funding per financial year" it is a annually revised total funding amount.
// This is used in calculations alongside data reported in the RCS report.
List fundingRows = organisation.custom?.details?.funding?.rows
fundingRows?.find{it.shortLabel == RCS_CONTRACTED_FUNDING }
}
void checkAndUpdateFundingTotal(Map organisation) {
String today = DateUtils.formatAsISOStringNoMillis(new Date())
Map rcsFunding = getRcsFunding(organisation)
if (!rcsFunding) {
return
}
double funding = 0
int index = findIndexOfPeriod(organisation, today)
while (index >= 0 && funding == 0) {
def fundingStr = rcsFunding.costs[index]?.dollar
if (fundingStr) {
try {
funding = Double.parseDouble(fundingStr)
} catch (NumberFormatException e) {
log.error("Error parsing funding amount for organisation ${organisation.organisationId} at index $index")
}
}
index--
}
if (funding != rcsFunding.rowTotal) {
rcsFunding.rowTotal = funding
organisation.custom.details.funding.overallTotal = rcsFunding.rowTotal
log.info("Updating the funding information for organisation ${organisation.organisationId} to $funding")
update(organisation.organisationId, organisation.custom)
}
}
private void regenerateOrganisationReports(Map organisation, List<String> reportCategories = null) {
ReportOwner owner = new ReportOwner(
id:[organisationId:organisation.organisationId],
name:organisation.name
)
List organisationReportConfig = organisation.config?.organisationReports?.collect{new ReportConfig(it)}
reportService.regenerateAll(organisation.reports, organisationReportConfig, owner, reportCategories)
}
def isUserAdminForOrganisation(organisationId) {
def userIsAdmin
if (!userService.user) {
return false
}
if (userService.userIsSiteAdmin()) {
userIsAdmin = true
} else {
userIsAdmin = userService.isUserAdminForOrganisation(userService.user.userId, organisationId)
}
userIsAdmin
}
def isUserGrantManagerForOrganisation(organisationId) {
def userIsAdmin
if (!userService.user) {
return false
}
if (userService.userIsSiteAdmin()) {
userIsAdmin = true
} else {
userIsAdmin = userService.isUserGrantManagerForOrganisation(userService.user.userId, organisationId)
}
userIsAdmin
}
/**
* Adds a user with the supplied role to the identified organisation.
*
* @param userId the id of the user to add permissions for.
* @param organisationId the organisation to add permissions for.
* @param role the role to assign to the user.
*/
def addUserAsRoleToOrganisation(String userId, String organisationId, String role) {
userService.addUserAsRoleToOrganisation(userId, organisationId, role)
}
/**
* Removes the user access with the supplied role from the identified organisation.
*
* @param userId the id of the user to remove permissions for.
* @param organisationId the organisation to remove permissions for.
*/
def removeUserWithRoleFromOrganisation(String userId, String organisationId, String role) {
userService.removeUserWithRoleFromOrganisation(userId, organisationId, role)
}
def search(Integer offset = 0, Integer max = 100, String searchTerm = null, String sort = null) {
Map params = [
offset:offset,
max:max,
query:searchTerm,
fq:"className:au.org.ala.ecodata.Organisation"
]
if (sort) {
params.sort = sort
}
def results = searchService.fulltextSearch(
params, false
)
results
}
/** May be useful to make this configurable per org or something? */
def getReportConfig(organisationId) {
return GREEN_ARMY_REPORT_CONFIG
}
def getSupportedAdHocReports(projectId) {
def adHocReports = getReportConfig(null).findAll{it.adhoc}
if (userService.userIsSiteAdmin() || projectService.isUserCaseManagerForProject(userService.getUser()?.userId, projectId)) {
return adHocReports.collect{it.type}
}
return adHocReports.findAll{!it.grantManagerOnly}.collect{it.type}
}
/**
* Returns all activities of the specified type that are being undertaken by projects that are run
* by this organisation (or that have a service provider relationship with this organisation).
*
* @param organisation the organisation - must include a project attribute that contains the projects
* @param activityTypes the types of activities to return.
* @return the activities that were found.
*/
List findActivitiesForOrganisation(organisation, List activityTypes) {
if (!organisation.projects) {
return
}
def startDate = organisation.projects.min { it.plannedStartDate }.plannedStartDate
def endDate = organisation.projects.max { it.plannedEndDate }.plannedEndDate
def projectIds = organisation.projects.collect { it.projectId }
def criteria = [type: activityTypes, projectId: projectIds, dateProperty:'plannedEndDate', startDate : startDate, endDate: endDate]
def response = activityService.search(criteria)
List activities = response?.resp?.activities ?: []
return activities
}
/**
* Returns a list of pseudo activities that represent the reports that are required to be
* completed by this organisation. Note that the pseduo activities aren't in the database, instead they
* are derived from the existence of reports to be completed by projects related to the organisation.
* @param organisation the organisation - must include a project attribute that contains the projects
* @param reportConf defines the activity type and grouping period for the bulk reports.
* @return the reports that need to be completed.
*/
def getReportsForOrganisation(organisation, reportConf) {
reportService.findReportsForOrganisation(organisation.organisationId)
}
Map submitReport(String organisationId, String reportId) {
Map reportData = setupReportLifeCycleChange(organisationId, reportId)
return reportService.submitReport(reportId, reportData.reportActivities, reportData.organisation, reportData.members, EmailTemplate.ORGANISATION_REPORT_SUBMITTED_EMAIL_TEMPLATE)
}
Map approveReport(String organisationId, String reportId, String reason) {
Map reportData = setupReportLifeCycleChange(organisationId, reportId)
return reportService.approveReport(reportId, reportData.reportActivities, reason, reportData.organisation, reportData.members, EmailTemplate.ORGANISATION_REPORT_APPROVED_EMAIL_TEMPLATE)
}
def rejectReport(String organisationId, String reportId, String reason, List categories) {
Map reportData = setupReportLifeCycleChange(organisationId, reportId)
return reportService.rejectReport(reportId, reportData.reportActivities, reason, categories, reportData.organisation, reportData.members, EmailTemplate.ORGANISATION_REPORT_RETURNED_EMAIL_TEMPLATE)
}
def cancelReport(String organisationId, String reportId, String reason) {
Map reportData = setupReportLifeCycleChange(organisationId, reportId)
return reportService.cancelReport(reportId, reportData.reportActivities, reason, reportData.organisation, reportData.members)
}
def unCancelReport(String organisationId, Map reportDetails) {
Map reportData = setupReportLifeCycleChange(organisationId, reportDetails.reportId)
Map result = reportService.unCancelReport(reportDetails.reportId, reportDetails.activityIds, reportDetails.reason, reportData.organisation, reportData.members)
result
}
/**
* Performs the common setup required for a report lifecycle state change (e.g. submit/approve/return)
* @param organisationId the ID of the program that owns the report
* @param reportId The report about to undergo a change.
* @return a Map with keys [organisation, reportActivities, programMembers]
*/
private Map setupReportLifeCycleChange(String organisationId, String reportId) {
Map organisation = get(organisationId)
List members = userService.getMembersOfOrganisation(organisationId)
Map report = reportService.get(reportId)
// All MU reports are of type "Single Activity" at the moment.
List reportActivities = [report.activityId]
[organisation:organisation, reportActivities:reportActivities, members:members]
}
Map getAbnDetails(String abnNumber){
Map result
result = abnLookupService.lookupOrganisationDetailsByABN(abnNumber)
if (result.abn == ''){
result.error = "invalid"
}
return result
}
Map scoresForOrganisationReport(String organisationId, String reportId, List scoreIds) {
Map organisation = get(organisationId)
Map report = organisation.reports?.find{it.reportId == reportId}
Map result = [:]
if (report) {
String format = 'YYYY-MM'
List dateBuckets = [report.fromDate, report.toDate]
Map results = reportService.dateHistogramOrgsForScores(organisationId, dateBuckets, format, scoreIds)
// Match the algorithm used in ecodata to determine the algorithm so we can determine
DateTime start = DateUtils.parse(report.fromDate).withZone(DateTimeZone.getDefault())
DateTime end = DateUtils.parse(report.toDate).withZone(DateTimeZone.getDefault())
String matchingGroup = DateUtils.format(start, format) + ' - ' + DateUtils.format(end.minusDays(1), format)
result = results.resp?.find{ it.group == matchingGroup } ?: [:]
}
scoreIds.collectEntries{ String scoreId ->[(scoreId):result.results?.find{it.scoreId == scoreId}?.result?.result ?: 0]}
}
List scoresForOrganisation(Map organisation, List<String> scoreIds, boolean approvedOnly = true) {
String url = grailsApplication.config.getProperty('ecodata.baseUrl')+"organisation/organisationMetrics/"+organisation.organisationId
Map params = [approvedOnly: approvedOnly, scoreIds: scoreIds]
Map result = webService.doPost(url, params)
List scores = result?.resp?.collect { Map score ->
Map target = organisation?.custom?.details?.services?.targets?.find { it.scoreId == score.scoreId }
score.target = target?.target
score
}
scores
}
/**
* Filter services to those supported by organisation.
*/
def findApplicableServices(Map organisation, List allServices) {
List supportedServices = organisation.config?.organisationReports?.collect{it.activityType}?.findAll{it}
List result = []
if (supportedServices) {
result = allServices.findAll{ supportedServices.intersect(it.outputs.formName) }
result.each {
List scores = it.scores?.findAll{Map score -> score.isOutputTarget}
it.scores = scores
}
}
result
}
}