source: trunk/grails-app/services/TaskService.groovy @ 739

Last change on this file since 739 was 728, checked in by gav, 13 years ago

Domain change, split Task.mandatoryRegulatory into regulatoryRequirement and mandatoryRequirement.

File size: 39.9 KB
Line 
1import grails.util.Environment
2
3/**
4* Provides a service class for the Task domain class.
5*
6*/
7class TaskService {
8
9    boolean transactional = false
10
11    def authService
12    def dateUtilService
13    def authenticateService
14    def assignedGroupService
15    def assignedPersonService
16
17    /**
18    * Determines and returns a possible parent list for a task.
19    * @todo Create and use another method that limits the results to say the latest 20 or 100 tasks?
20    * @param taskInstance The task to use when determining the possible parent list.
21    * @returns A list of the possible parents.
22    */
23    def possibleParentList(taskInstance) {
24        def criteria = taskInstance.createCriteria()
25        def possibleParentList = criteria {
26            and {
27                notEqual('trash', true)
28                notEqual('id', taskInstance.id)
29                taskInstance.subTasks.each() { notEqual('id', it.id) }
30                }
31        }
32    }
33
34    /**
35    * Determines and returns a list of possible task types for scheduled tasks.
36    * @returns A list of the possible task types.
37    */
38    def getScheduledTaskTypes() {
39        def criteria = TaskType.createCriteria()
40        def scheduledTaskTypes = criteria {
41            and {
42                eq('isActive', true)
43                gt('id', 2L)
44                }
45        }
46    }
47
48    /**
49    * Determines and returns a list of possible task priorites for Scheduled tasks.
50    * @returns A list of the possible task priorites.
51    */
52    def getScheduledTaskPriorities() {
53        def criteria = TaskPriority.createCriteria()
54        def scheduledTaskPriorities = [:]
55        scheduledTaskPriorities.list = criteria {
56            and {
57                eq('isActive', true)
58                gt('id', 1L)
59                }
60        }
61        scheduledTaskPriorities.default = scheduledTaskPriorities.list.find { it.id == 4L } //  1-Normal.
62        return scheduledTaskPriorities
63    }
64
65    /**
66    * Determines and returns a list of possible task priorites for Unscheduled tasks.
67    * @returns A map containing a list of the possible task priorites and the default priority.
68    */
69    def getUnscheduledTaskPriorities() {
70        def criteria = TaskPriority.createCriteria()
71        def unscheduledTaskPriorities = [:]
72        unscheduledTaskPriorities.list = criteria {
73            and {
74                eq('isActive', true)
75                lt('id', 5L)
76                ne('id', 1L)
77            }
78        }
79        unscheduledTaskPriorities.default = unscheduledTaskPriorities.list.find { it.id == 3L } // 2-High.
80        return unscheduledTaskPriorities
81    }
82
83    /**
84    * Creates a new task with the given params.
85    * @param params The params to use when creating the new task.
86    * @returns A map containing result.error (if any error) and result.taskInstance.
87    */
88    def save(params) {
89        Task.withTransaction { status ->
90            def result = [:]
91
92            def fail = { Map m ->
93                status.setRollbackOnly()
94                if(result.taskInstance && m.field)
95                    result.taskInstance.errors.rejectValue(m.field, m.code)
96                result.error = [ code: m.code, args: ["Task", params.id] ]
97                return result
98            }
99
100            def taskInstance = new Task(params)
101            result.taskInstance = taskInstance
102
103            // Set taskStatus if not supplied.
104            if(!params.taskStatus)
105                taskInstance.taskStatus = TaskStatus.read(1) // Not Started
106
107            // Set budgetStatus if not supplied.
108            if(!params.taskBudgetStatus) {
109                if(taskInstance.taskType?.id == 1 || taskInstance.taskType?.id == 2) // Immediate Callout or Unsheduled Breakin.
110                    taskInstance.taskBudgetStatus = TaskBudgetStatus.read(1) // Unplanned.
111                else
112                    taskInstance.taskBudgetStatus = TaskBudgetStatus.read(2) // Planned.
113            }
114
115            if(result.taskInstance.parentTask?.trash)
116                return fail(field:"parentTask", code:"task.operationNotPermittedOnTaskInTrash")
117
118            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
119                return fail(code:"default.create.failure")
120
121            def taskModification = new TaskModification(person: authService.currentUser,
122                                                taskModificationType: TaskModificationType.get(1),
123                                                task: taskInstance)
124
125            if(taskModification.hasErrors() || !taskModification.save())
126                return fail(field:"taskModifications", code:"task.modifications.failedToSave")
127
128            //Add the assignedGroups, provided by a new ArrayList(task.assignedGroups)
129            if(params.assignedGroups) {
130                def assignedGroupsResult
131                def assignedGroupParams = [:]
132                params.assignedGroups.each() {
133
134                    assignedGroupParams = [personGroup: it.personGroup,
135                                                                task: taskInstance,
136                                                                estimatedHour: it.estimatedHour,
137                                                                estimatedMinute: it.estimatedMinute]
138
139                    assignedGroupsResult = assignedGroupService.save(assignedGroupParams)
140
141                    if(assignedGroupsResult.error)
142                        return fail(field:"assignedGroups", code:"task.assignedGroups.failedToSave")
143
144                }
145            }
146
147            //Add the assignedPersons, provided by a new ArrayList(task.assignedPersons)
148            if(params.assignedPersons) {
149                def assignedPersonsResult
150                def assignedPersonsParams = [:]
151                params.assignedPersons.each() {
152
153                    assignedPersonsParams = [person: it.person,
154                                                                task: taskInstance,
155                                                                estimatedHour: it.estimatedHour,
156                                                                estimatedMinute: it.estimatedMinute]
157
158                    assignedPersonsResult = assignedPersonService.save(assignedPersonsParams)
159
160                    if(assignedPersonsResult.error)
161                        return fail(field:"assignedPersons", code:"task.assignedPersons.failedToSave")
162
163                }
164            }
165
166            // Success.
167            return result
168
169        } //end withTransaction
170    } // end save()
171
172    /**
173    * Creates a subTask copying sane attributes from the parentTask unless otherwise specified in params.
174    * The targetStartDate and targetCompletionDate default to today since that is the sane thing to do.
175    * The taskProcedure is only assigned to the sub task if supplied in params.
176    * The assignedPersons and assignedGroups are only added to the sub task if supplied in params.
177    * The positiveFault property is never set on the subTask.
178    * Collections in params must be supplied as new ArrayList's.
179    * This method is not intended to be a copyTask method.
180    * There should be no reason to copy tasks, recurrence can be used to create similar tasks.
181    * @param parentTask The parent task to get attributes from, also set as the parent.
182    * @param params Overrides the parent task values if specified.
183    * @returns A map containing result.error=true (if any error) and result.taskInstance.
184    */
185    def createSubTask(parentTask, params = [:]) {
186
187        def result = [:]
188
189        //Make our new Task a subTask and set the required properties.
190        def p = [:]
191        p.parentTask = parentTask
192        p.description = params.description ?: parentTask.description
193        p.comment = params.comment ?: parentTask.comment
194        p.targetStartDate = params.targetStartDate ?: dateUtilService.today
195        p.targetCompletionDate = params.targetCompletionDate ?: dateUtilService.today
196
197        p.safetyRequirement = params.safetyRequirement ?: parentTask.safetyRequirement
198        p.regulatoryRequirement = params.regulatoryRequirement ?: parentTask.regulatoryRequirement
199        p.mandatoryRequirement = params.mandatoryRequirement ?: parentTask.mandatoryRequirement
200
201        p.taskGroup = params.taskGroup ?: parentTask.taskGroup
202        p.taskStatus = TaskStatus.get(1) // A new subTask must always be "Not Started".
203        p.taskPriority = parentTask.taskPriority
204        p.taskType = params.taskType ?: parentTask.taskType
205        p.leadPerson = params.leadPerson ?: parentTask.leadPerson
206        p.primaryAsset = params.primaryAsset ?: parentTask.primaryAsset
207        p.associatedAssets = params.associatedAssets ?: new ArrayList(parentTask.associatedAssets) // Collection.
208
209        // Supplied by recurring tasks.
210        if(params.taskProcedure) p.taskProcedure = params.taskProcedure
211        if(params.assignedGroups) p.assignedGroups = params.assignedGroups // Collection.
212        if(params.assignedPersons) p.assignedPersons = params.assignedPersons // Collection.
213
214        // trash: A new subTask must always have trash=false, which is already the domain class default.
215
216        // These would be considered copying, hence not done.
217        // taskRecurringSchedule, entries, taskModifications, subTasks, inventoryMovements.
218
219        // Create the sub task and return the result.
220        result = save(p)
221
222        // Approve.
223        if(!result.error && parentTask.approved) {
224            p = [:]
225            p.id = result.taskInstance.id
226            approve(p)
227        }
228
229        // Success.
230        return result
231
232    } // end createSubTask()
233
234    /**
235    * In production tasks are NEVER deleted, only the trash flag is set!
236    * However during testing it may be required to delete a task and that
237    * is why this method exists.
238    */
239    def delete(params) {
240        Task.withTransaction { status ->
241            def result = [:]
242
243            def fail = { Map m ->
244                status.setRollbackOnly()
245                if(result.taskInstance && m.field)
246                    result.taskInstance.errors.rejectValue(m.field, m.code)
247                result.error = [ code: m.code, args: ["Task", params.id] ]
248                return result
249            }
250
251            if(Environment.current == Environment.PRODUCTION)
252                return fail(code:"task.delete.failure.production")
253
254            result.taskInstance = Task.get(params.id)
255
256            if(!result.taskInstance)
257                return fail(code:"default.not.found")
258
259            // Handle taskModifications.
260            def taskModifications = TaskModification.findAllByTask(result.taskInstance)
261            taskModifications.each() {
262                result.taskInstance.removeFromTaskModifications(it)
263                it.delete()
264            }
265
266            // Handle assignedPersons.
267            def taskAssignedPersons = AssignedPerson.findAllByTask(result.taskInstance)
268            taskAssignedPersons.each() {
269                result.taskInstance.removeFromAssignedPersons(it)
270                it.delete()
271            }
272
273            // Handle assignedGroups.
274            def taskAssignedGroups = AssignedGroup.findAllByTask(result.taskInstance)
275            taskAssignedGroups.each() {
276                result.taskInstance.removeFromAssignedGroups(it)
277                it.delete()
278            }
279
280            if(result.error)
281                return result
282
283            try {
284                result.taskInstance.delete(flush:true)
285                return result //Success.
286            }
287            catch(org.springframework.dao.DataIntegrityViolationException e) {
288                return fail(code:"default.delete.failure")
289            }
290
291        } // end withTransaction
292    } // delete()
293
294    /**
295    * Creates a new task entry.
296    * @param params The params to use when creating the new entry.
297    * @returns A map containing result.error=true (if any error), result.entryInstance and result.taskId.
298    */
299    def saveEntry(params) {
300        Task.withTransaction { status ->
301            def result = [:]
302
303            def fail = { Map m ->
304                status.setRollbackOnly()
305                if(result.taskInstance && m.field)
306                    result.taskInstance.errors.rejectValue(m.field, m.code)
307                result.error = [ code: m.code, args: ["Entry", params.id] ]
308                return result
309            }
310
311            result.entryInstance = new Entry(params)
312            result.entryInstance.enteredBy = authService.currentUser
313
314            def taskInstance
315            if(result.entryInstance.task?.id) {
316                result.taskId = result.entryInstance.task.id
317                taskInstance = Task.lock(result.entryInstance.task.id)
318            }
319
320            if(!taskInstance)
321                return fail(field:"task", code:"task.notFound")
322
323            if(result.entryInstance.hasErrors() || !result.entryInstance.save())
324                return fail(code:"default.create.failure")
325
326            if(taskInstance.taskStatus.id == 3)
327                return fail(field:"task", code:"task.operationNotPermittedOnCompleteTask")
328
329            // Check for authorisation on recurring tasks.
330            if(taskInstance.taskRecurringSchedule) {
331                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
332                    return fail(field:"task", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
333            }
334
335            // If task status is "Not Started" and entry type is "Work Done" and time has been booked.
336            // Then we create the started modification and set task status.
337            if(taskInstance.taskStatus.id == 1 && result.entryInstance.entryType.id == 3
338                && (result.entryInstance.durationHour + result.entryInstance.durationMinute > 0)) {
339
340                // Create the "Started" task modification, this provides the "Actual Started Date".
341                def taskModification = new TaskModification(person: authService.currentUser,
342                                                        taskModificationType: TaskModificationType.read(2),
343                                                        task: taskInstance)
344
345                if(taskModification.hasErrors() || !taskModification.save())
346                    return fail(field:"task", code:"task.modifications.failedToSave")
347
348                // Set task status to "In Progress".
349                taskInstance.taskStatus = TaskStatus.read(2)
350
351                if(taskInstance.hasErrors() || !taskInstance.save())
352                    return fail(field:"task", code:"task.failedToSave")
353            }
354
355            // Success.
356            return result
357
358        } // end withTransaction
359    } // end saveEntry()
360
361    /**
362    * Updates an existing task.
363    * @param params The params to update for task with id of params.id.
364    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
365    */
366    def update(params) {
367        Task.withTransaction { status ->
368            def result = [:]
369
370            def fail = { Map m ->
371                status.setRollbackOnly()
372                if(result.taskInstance && m.field)
373                    result.taskInstance.errors.rejectValue(m.field, m.code)
374                result.error = [ code: m.code, args: ["Task", params.id] ]
375                return result
376            }
377
378            result.taskInstance = Task.get(params.id)
379
380            if(!result.taskInstance)
381                return fail('id', "task.notFound")
382
383            // Optimistic locking check.
384            if(params.version) {
385                if(result.taskInstance.version > params.version.toLong())
386                    return fail(field:"version", code:"default.optimistic.locking.failure")
387            }
388
389            // Check for authorisation on recurring tasks.
390            if(result.taskInstance.taskRecurringSchedule) {
391                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
392                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
393            }
394
395            result.taskInstance.properties = params
396
397            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
398                return fail(code:"default.update.failure")
399
400            def taskModification = new TaskModification(person:authService.currentUser,
401                                                    taskModificationType: TaskModificationType.get(3),
402                                                    task: result.taskInstance)
403
404            if(taskModification.hasErrors() || !taskModification.save())
405                return fail(code:"task.modifications.failedToSave")
406
407            // Success.
408            return result
409
410        } //end withTransaction
411    }  // end update()
412
413    /**
414    * Completes an existing task.
415    * @param params The params for task with id of params.id.
416    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
417    */
418    def complete(params) {
419        Task.withTransaction { status ->
420            def result = [:]
421
422            def fail = { Map m ->
423                status.setRollbackOnly()
424                if(result.taskInstance && m.field)
425                    result.taskInstance.errors.rejectValue(m.field, m.code)
426                result.error = [ code: m.code, args: ["Task", params.id] ]
427                return result
428            }
429
430            result.taskInstance = Task.get(params.id)
431
432            if(!result.taskInstance)
433                return fail(code:"default.not.found")
434
435            // Optimistic locking check.
436            if(params.version) {
437                if(result.taskInstance.version > params.version.toLong())
438                    return fail(field:"version", code:"default.optimistic.locking.failure")
439            }
440
441            // Check for authorisation on recurring tasks.
442            if(result.taskInstance.taskRecurringSchedule) {
443                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
444                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
445            }
446
447            result.taskInstance.taskStatus = TaskStatus.get(3)
448            result.taskInstance.attentionFlag = false
449            result.taskInstance.taskRecurringSchedule?.enabled = false
450
451            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
452                return fail(code:"default.update.failure")
453
454            def taskModification = new TaskModification(person:authService.currentUser,
455                                                    taskModificationType: TaskModificationType.get(4),
456                                                    task: result.taskInstance)
457
458
459            if(taskModification.hasErrors() || !taskModification.save())
460                return fail(code:"task.modifications.failedToSave")
461
462            // Success.
463            return result
464
465        } //end withTransaction
466    }  // end complete()
467
468    /**
469    * Sets the attentionFlag on an existing task.
470    * @param params The params for task with id of params.id.
471    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
472    */
473    def setAttentionFlag(params) {
474        Task.withTransaction { status ->
475            def result = [:]
476
477            def fail = { Map m ->
478                status.setRollbackOnly()
479                if(result.taskInstance && m.field)
480                    result.taskInstance.errors.rejectValue(m.field, m.code)
481                result.error = [ code: m.code, args: ["Task", params.id] ]
482                return result
483            }
484
485            result.taskInstance = Task.get(params.id)
486
487            if(!result.taskInstance)
488                return fail(code:"default.not.found")
489
490            // Optimistic locking check.
491            if(params.version) {
492                if(result.taskInstance.version > params.version.toLong())
493                    return fail(field:"version", code:"default.optimistic.locking.failure")
494            }
495
496            // Check for authorisation on recurring tasks.
497            if(result.taskInstance.taskRecurringSchedule) {
498                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
499                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
500            }
501
502            result.taskInstance.attentionFlag = true
503
504            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
505                return fail(code:"default.update.failure")
506
507            def taskModification = new TaskModification(person:authService.currentUser,
508                                                    taskModificationType: TaskModificationType.get(12),
509                                                    task: result.taskInstance)
510
511            if(taskModification.hasErrors() || !taskModification.save())
512                return fail(code:"task.modifications.failedToSave")
513
514            // Success.
515            return result
516
517        } //end withTransaction
518    }  // end flag()
519
520    /**
521    * Clears the attentionFlag on an existing task.
522    * @param params The params for task with id of params.id.
523    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
524    */
525    def clearAttentionFlag(params) {
526        Task.withTransaction { status ->
527            def result = [:]
528
529            def fail = { Map m ->
530                status.setRollbackOnly()
531                if(result.taskInstance && m.field)
532                    result.taskInstance.errors.rejectValue(m.field, m.code)
533                result.error = [ code: m.code, args: ["Task", params.id] ]
534                return result
535            }
536
537            result.taskInstance = Task.get(params.id)
538
539            if(!result.taskInstance)
540                return fail(code:"default.not.found")
541
542            // Optimistic locking check.
543            if(params.version) {
544                if(result.taskInstance.version > params.version.toLong())
545                    return fail(field:"version", code:"default.optimistic.locking.failure")
546            }
547
548            // Check for authorisation on recurring tasks.
549            if(result.taskInstance.taskRecurringSchedule) {
550                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
551                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
552            }
553
554            result.taskInstance.attentionFlag = false
555
556            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
557                return fail(code:"default.update.failure")
558
559            def taskModification = new TaskModification(person:authService.currentUser,
560                                                    taskModificationType: TaskModificationType.get(13),
561                                                    task: result.taskInstance)
562
563            if(taskModification.hasErrors() || !taskModification.save())
564                return fail(code:"task.modifications.failedToSave")
565
566            // Success.
567            return result
568
569        } //end withTransaction
570    }  // end clearFlag()
571
572    /**
573    * Reopens an existing task.
574    * @param params The params for task with id of params.id.
575    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
576    */
577    def reopen(params) {
578        Task.withTransaction { status ->
579            def result = [:]
580
581            def fail = { Map m ->
582                status.setRollbackOnly()
583                if(result.taskInstance && m.field)
584                    result.taskInstance.errors.rejectValue(m.field, m.code)
585                result.error = [ code: m.code, args: ["Task", params.id] ]
586                return result
587            }
588
589            result.taskInstance = Task.get(params.id)
590
591            if(!result.taskInstance)
592                return fail(code:"default.not.found")
593
594            // Optimistic locking check.
595            if(params.version) {
596                if(result.taskInstance.version > params.version.toLong())
597                    return fail(field:"version", code:"default.optimistic.locking.failure")
598            }
599
600            // Check for authorisation on recurring tasks.
601            if(result.taskInstance.taskRecurringSchedule) {
602                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
603                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
604            }
605
606            def isInProgress = false
607            result.taskInstance.entries.each() {
608                if(it.entryType.id == 3 && (it.durationHour + it.durationMinute > 0) )
609                    isInProgress = true
610            }
611
612            if(isInProgress)
613                result.taskInstance.taskStatus = TaskStatus.read(2) // In Progress
614            else
615                result.taskInstance.taskStatus = TaskStatus.read(1) // Not Started
616
617            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
618                return fail(code:"default.update.failure")
619
620            def taskModification = new TaskModification(person:authService.currentUser,
621                                                    taskModificationType: TaskModificationType.get(5),
622                                                    task: result.taskInstance)
623
624            if(taskModification.hasErrors() || !taskModification.save())
625                return fail(code:"task.modifications.failedToSave")
626
627            // Success.
628            return result
629
630        } //end withTransaction
631    }  // end reopen()
632
633    /**
634    * Move a task to the trash.
635    * @param params The params for task with id of params.id.
636    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
637    */
638    def trash(params) {
639        Task.withTransaction { status ->
640            def result = [:]
641
642            def fail = { Map m ->
643                status.setRollbackOnly()
644                if(result.taskInstance && m.field)
645                    result.taskInstance.errors.rejectValue(m.field, m.code)
646                result.error = [ code: m.code, args: ["Task", params.id] ]
647                return result
648            }
649
650            result.taskInstance = Task.get(params.id)
651
652            if(!result.taskInstance)
653                return fail(code:"default.not.found")
654
655            // Optimistic locking check.
656            if(params.version) {
657                if(result.taskInstance.version > params.version.toLong())
658                    return fail(field:"version", code:"default.optimistic.locking.failure")
659            }
660
661            // Check for authorisation on recurring tasks.
662            if(result.taskInstance.taskRecurringSchedule) {
663                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
664                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
665            }
666
667            result.taskInstance.trash = true
668            result.taskInstance.attentionFlag = false
669            result.taskInstance.taskRecurringSchedule?.enabled = false
670
671            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
672                return fail(code:"default.update.failure")
673
674            def taskModification = new TaskModification(person:authService.currentUser,
675                                                    taskModificationType: TaskModificationType.get(6),
676                                                    task: result.taskInstance)
677
678            if(taskModification.hasErrors() || !taskModification.save())
679                return fail(code:"task.modifications.failedToSave")
680
681            // Success.
682            return result
683
684        } //end withTransaction
685    }  // end trash()
686
687    /**
688    * Restore a task from the trash.
689    * @param params The params for task with id of params.id.
690    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
691    */
692    def restore(params) {
693        Task.withTransaction { status ->
694            def result = [:]
695
696            def fail = { Map m ->
697                status.setRollbackOnly()
698                if(result.taskInstance && m.field)
699                    result.taskInstance.errors.rejectValue(m.field, m.code)
700                result.error = [ code: m.code, args: ["Task", params.id] ]
701                return result
702            }
703
704            result.taskInstance = Task.get(params.id)
705
706            if(!result.taskInstance)
707                return fail(code:"default.not.found")
708
709            // Optimistic locking check.
710            if(params.version) {
711                if(result.taskInstance.version > params.version.toLong())
712                    return fail(field:"version", code:"default.optimistic.locking.failure")
713            }
714
715            // Check for authorisation on recurring tasks.
716            if(result.taskInstance.taskRecurringSchedule) {
717                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
718                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
719            }
720
721            result.taskInstance.trash = false
722
723            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
724                return fail(code:"default.update.failure")
725
726            def taskModification = new TaskModification(person:authService.currentUser,
727                                                    taskModificationType: TaskModificationType.get(7),
728                                                    task: result.taskInstance)
729
730            if(taskModification.hasErrors() || !taskModification.save())
731                return fail(code:"task.modifications.failedToSave")
732
733            // Success.
734            return result
735
736        } //end withTransaction
737    }  // end restore()
738
739    /**
740    * Approve a task.
741    * @param params The params for task with id of params.id.
742    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
743    */
744    def approve(params) {
745        Task.withTransaction { status ->
746            def result = [:]
747
748            def fail = { Map m ->
749                status.setRollbackOnly()
750                if(result.taskInstance && m.field)
751                    result.taskInstance.errors.rejectValue(m.field, m.code)
752                result.error = [ code: m.code, args: ["Task", params.id] ]
753                return result
754            }
755
756            result.taskInstance = Task.get(params.id)
757
758            if(!result.taskInstance)
759                return fail(code:"default.not.found")
760
761            // Optimistic locking check.
762            if(params.version) {
763                if(result.taskInstance.version > params.version.toLong())
764                    return fail(field:"version", code:"default.optimistic.locking.failure")
765            }
766
767            // Check for authorisation on recurring tasks.
768            if(result.taskInstance.taskRecurringSchedule) {
769                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
770                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
771            }
772
773            result.taskInstance.approved = true
774
775            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
776                return fail(code:"default.update.failure")
777
778            def taskModification = new TaskModification(person:authService.currentUser,
779                                                    taskModificationType: TaskModificationType.get(8),
780                                                    task: result.taskInstance)
781
782            if(taskModification.hasErrors() || !taskModification.save())
783                return fail(code:"task.modifications.failedToSave")
784
785            // Success.
786            return result
787
788        } //end withTransaction
789    }  // end approve()
790
791    /**
792    * Remove a previously given approval from a task.
793    * @param params The params for task with id of params.id.
794    * @returns A map containing result.error (if any error) and result.taskInstance (if available).
795    */
796    def renegeApproval(params) {
797        Task.withTransaction { status ->
798            def result = [:]
799
800            def fail = { Map m ->
801                status.setRollbackOnly()
802                if(result.taskInstance && m.field)
803                    result.taskInstance.errors.rejectValue(m.field, m.code)
804                result.error = [ code: m.code, args: ["Task", params.id] ]
805                return result
806            }
807
808            result.taskInstance = Task.get(params.id)
809
810            if(!result.taskInstance)
811                return fail(code:"default.not.found")
812
813            // Optimistic locking check.
814            if(params.version) {
815                if(result.taskInstance.version > params.version.toLong())
816                    return fail(field:"version", code:"default.optimistic.locking.failure")
817            }
818
819            // Check for authorisation on recurring tasks.
820            if(result.taskInstance.taskRecurringSchedule) {
821                if(!authenticateService.ifAnyGranted('ROLE_AppAdmin,ROLE_Manager,ROLE_TaskManager'))
822                    return fail(field:"taskRecurringSchedule", code:"task.operationNotPermittedOnRecurringTaskWithoutAuth")
823            }
824
825            result.taskInstance.approved = false
826
827            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
828                return fail(code:"default.update.failure")
829
830            def taskModification = new TaskModification(person:authService.currentUser,
831                                                    taskModificationType: TaskModificationType.get(9),
832                                                    task: result.taskInstance)
833
834            if(taskModification.hasErrors() || !taskModification.save())
835                return fail(code:"task.modifications.failedToSave")
836
837            // Success.
838            return result
839
840        } //end withTransaction
841    }  // end renegeApproval()
842
843    /**
844    * Creates a new unscheduled breakin task with the given params.
845    * @param params The params to use when creating the new task.
846    * @returns A map containing result.error (if any error) and result.taskInstance.
847    */
848    def saveUnscheduled(params) {
849        Task.withTransaction { status ->
850            def result = [:]
851
852            def fail = { Map m ->
853                status.setRollbackOnly()
854                if(result.taskInstance && m.field)
855                    result.taskInstance.errors.rejectValue(m.field, m.code)
856                result.error = [ code: m.code, args: ["Task", params.id] ]
857                return result
858            }
859
860            // If not supplied.
861            if(!params.taskStatus)
862                params.taskStatus = TaskStatus.get(1) // Not Started.
863
864            result.taskInstance = new Task(params)
865
866            // Always for an unscheduled breakin..
867            result.taskInstance.taskType = TaskType.get(2) // Unscheduled Breakin.
868            result.taskInstance.taskBudgetStatus = TaskBudgetStatus.get(1) // Unplanned.
869
870            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
871                fail(code:"default.create.failure")
872
873            if(!result.error) {
874                def taskModification = new TaskModification(person: authService.currentUser,
875                                                                taskModificationType: TaskModificationType.get(1), // Created.
876                                                                task: result.taskInstance)
877
878                if(taskModification.hasErrors() || !taskModification.save())
879                    fail(field:"taskModifications", code:"task.modifications.failedToSave")
880            }
881
882            // Success.
883            return result
884
885        } //end withTransaction
886    } // end saveUnscheduled()
887
888    /**
889    * Creates a new immediate callout task with the given params.
890    * @param params The params to use when creating the new task.
891    * @returns A map containing result.error (if any error) and result.taskInstance.
892    */
893    def saveImmediateCallout(params) {
894        Task.withTransaction { status ->
895            def result = [:]
896
897            def fail = { Map m ->
898                status.setRollbackOnly()
899                if(result.taskInstance && m.field)
900                    result.taskInstance.errors.rejectValue(m.field, m.code)
901                result.error = [ code: m.code, args: ["Task", params.id] ]
902                return result
903            }
904
905            // If not supplied.
906            if(!params.taskStatus)
907                params.taskStatus = TaskStatus.get(1) // Not Started.
908
909            result.taskInstance = new Task(params)
910
911            // Always for an immediate callout.
912            result.taskInstance.taskType = TaskType.get(1) // Immediate Callout.
913            result.taskInstance.taskBudgetStatus = TaskBudgetStatus.get(1) // Unplanned.
914            result.taskInstance.taskPriority = TaskPriority.get(1) // Immediate.
915            result.taskInstance.taskGroup = TaskGroup.get(1) // Engineering Activites.
916            result.taskInstance.approved = true
917            result.taskInstance.leadPerson = authService.currentUser
918            result.taskInstance.targetCompletionDate = result.taskInstance.targetStartDate
919
920            if(result.taskInstance.hasErrors() || !result.taskInstance.save())
921                fail(code:"default.create.failure")
922
923            if(!result.error) {
924                def taskModification = new TaskModification(person: authService.currentUser,
925                                                                taskModificationType: TaskModificationType.get(1), // Created.
926                                                                task: result.taskInstance)
927
928                if(taskModification.hasErrors() || !taskModification.save())
929                    fail(field:"taskModifications", code:"task.modifications.failedToSave")
930            }
931
932            def productionReference
933            if(params.entryFault.productionReference.id.isLong())
934                productionReference = ProductionReference.get(params.entryFault.productionReference.id.toLong())
935
936            def faultParams = [task: result.taskInstance,
937                                            entryType: EntryType.get(1),
938                                            comment: params.entryFault.comment,
939                                            dateDone: result.taskInstance.targetStartDate,
940                                            productionReference: productionReference,
941                                            durationHour: params.entryFault.durationHour,
942                                            durationMinute: params.entryFault.durationMinute]
943            def faultResult = saveEntry(faultParams)
944            result.entryFaultInstance = faultResult.entryInstance
945
946            def causeParams = [task: result.taskInstance,
947                                            entryType: EntryType.get(2),
948                                            dateDone: result.taskInstance.targetStartDate,
949                                            comment: params.entryCause.comment]
950            def causeResult = saveEntry(causeParams)
951            result.entryCauseInstance = causeResult.entryInstance
952
953            def workDoneParams = [task: result.taskInstance,
954                                                    entryType: EntryType.get(3),
955                                                    comment: params.entryWorkDone.comment,
956                                            dateDone: result.taskInstance.targetStartDate,
957                                                    durationHour: params.entryWorkDone.durationHour,
958                                                    durationMinute: params.entryWorkDone.durationMinute]
959            def workDoneResult = saveEntry(workDoneParams)
960            result.entryWorkDoneInstance = workDoneResult.entryInstance
961
962            if(result.error)
963                return result
964
965            if(causeResult.error)
966                return fail(code: "default.create.failure")
967
968            if(faultResult.error)
969                return fail(code: "default.create.failure")
970
971            if(workDoneResult.error)
972                return fail(code: "default.create.failure")
973
974            // Success.
975            return result
976
977        } //end withTransaction
978    } // end saveImmediateCallout()
979
980} // end TaskService
Note: See TracBrowser for help on using the repository browser.