source: trunk/grails-app/controllers/TaskDetailedController.groovy @ 838

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

Update service, controller and view logic to hand Task and Entry highestSeverity.
Also remove associatedAssets from task search panes.

File size: 39.4 KB
Line 
1import org.codehaus.groovy.grails.plugins.springsecurity.Secured
2import org.codehaus.groovy.grails.commons.ConfigurationHolder
3import com.zeddware.grails.plugins.filterpane.FilterUtils
4import org.springframework.web.servlet.support.RequestContextUtils as RCU
5
6@Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
7class TaskDetailedController extends BaseController {
8
9    def authService
10    def taskService
11    def taskSearchService
12    def taskReportService
13    def filterService
14    def exportService
15    def dateUtilService
16
17    // these actions only accept POST requests
18    static allowedMethods = [save:'POST',update:'POST',restore:'POST', trash:'POST',
19                                                approve:'POST', renegeApproval:'POST', complete:'POST',
20                                                reopen:'POST', setAttentionFlag:'POST', clearAttentionFlag:'POST']
21
22    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
23    def index = { redirect(action: 'search', params: params) }
24
25    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
26    def setSearchParamsMax = {
27        def max = 1000
28        if(params.newMax?.isInteger()) {
29            def i = params.newMax.toInteger()
30            if(i > 0 && i <= max)
31                session.taskSearchParamsMax = params.newMax
32            if(i > max)
33                session.taskSearchParamsMax = max
34        }
35        forward(action: 'search', params: params)
36    }
37
38    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
39    def setSearchCalendarParamsMax = {
40        def max = 1000
41        if(params.newMax?.isInteger()) {
42            def i = params.newMax.toInteger()
43            if(i > 0 && i <= max)
44                session.taskSearchCalendarParamsMax = params.newMax
45            if(i > max)
46                session.taskSearchCalendarParamsMax = max
47        }
48        forward(action: 'searchCalendar', params: params)
49    }
50
51    /**
52    * Search for tasks.
53    */
54    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
55    def search = {
56
57        if(session.taskSearchParamsMax)
58            params.max = session.taskSearchParamsMax
59
60        // Protect filterPane.
61        params.max = Math.min( params.max ? params.max.toInteger() : 100,  1000 )
62
63        // View main data.
64        def taskInstanceList = []
65        def taskInstanceTotal
66        def filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
67        def isFilterApplied = FilterUtils.isFilterApplied(params)
68
69        // Restore search unless a new search is being requested.
70        if(!params.quickSearch && !filterParams) {
71            if(session.taskSearchFilterParams) {
72                session.taskSearchFilterParams.each() { params[it.key] = it.value }
73                params.filter = session.taskSearchFilter
74                isFilterApplied = FilterUtils.isFilterApplied(params)
75            }
76        }
77        if(!params.quickSearch) {
78            if(session.taskSearchQuickSearch) {
79                params.quickSearch = session.taskSearchQuickSearch
80                params.person = Person.get(session.taskQuickSearchPersonId.toLong())
81                params.startDate = session.taskQuickSearchStartDate
82                params.endDate = session.taskQuickSearchEndDate
83                params.includeCompleted = session.taskQuickSearchIncludeCompleted
84            }
85        }
86
87        // Remember sort if supplied, otherwise try to restore.
88        if(params.sort && params.order) {
89            // Reset to defaultSort if requested.
90            if(params.sort == 'defaultSort') {
91                params.sort = null
92                params.order = null
93                session.removeAttribute("taskSearchSort")
94                session.removeAttribute("taskSearchOrder")
95            }
96            else {
97                session.taskSearchSort = params.sort
98                session.taskSearchOrder = params.order
99            }
100        }
101        else if(session.taskSearchSort && session.taskSearchOrder) {
102            params.sort = session.taskSearchSort
103            params.order = session.taskSearchOrder
104        }
105
106        if(isFilterApplied) {
107            // filterPane:
108            params.sort = params.sort ?: "id"
109            params.order = params.order ?: "desc"
110            if(params.sort == "attentionFlag") // See ticket #64 in Trac.
111                params.sort = "id"
112            // Prevent tasks in the trash being returned unless explicitly requested.
113            if(!params.filter.op.trash) {
114                params.filter.op.trash = "Equal"
115                params.filter.trash = "false"
116            }
117            // Call filterService.
118            taskInstanceList = filterService.filter( params, Task )
119            taskInstanceTotal = filterService.count( params, Task )
120            filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
121            // Remember search.
122            session.taskSearchFilterParams = new LinkedHashMap(filterParams)
123            session.taskSearchFilter = new LinkedHashMap(params.filter)
124        }
125        else {
126            // Quick Search:
127            def result = taskSearchService.getQuickSearch(params, RCU.getLocale(request))
128            taskInstanceList = result.taskInstanceList
129            taskInstanceTotal = result.taskInstanceList.totalCount
130            params.message = result.message
131            params.quickSearch = result.quickSearch
132            params.person = result.person
133            params.startDate = result.startDate
134            params.endDate = result.endDate
135            params.includeCompleted = result.includeCompleted
136            // Remember search.
137            session.removeAttribute("taskSearchFilterParams")
138            session.removeAttribute("taskSearchFilter")
139            session.taskSearchQuickSearch = result.quickSearch
140            session.taskQuickSearchPersonId = result.person.id
141            session.taskQuickSearchStartDate = result.startDate
142            session.taskQuickSearchEndDate = result.endDate
143            session.taskQuickSearchIncludeCompleted = result.includeCompleted
144        }
145
146        // export plugin:
147        if(params?.format && params.format != "html") {
148
149            def dateFmt = { date ->
150                formatDate(format: "EEE, dd-MMM-yyyy", date: date)
151            }
152
153            String title
154            if(params.quickSearch)
155                title = params.message
156            else
157                title = "Filtered tasks."
158
159            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
160            response.setHeader("Content-disposition", "attachment; filename=Tasks.${params.extension}")
161            List fields = ["id", "targetStartDate", "description", "leadPerson", "taskPriority", "taskType", "taskStatus"]
162            Map labels = ["id": "ID", "targetStartDate": "Target Start Date", "description": "Description",
163                                    "leadPerson": "Lead Person", "taskPriority": "Task Priority",
164                                    "taskType": "Task Type", "taskStatus": "Task Status"]
165            Map formatters = [ targetStartDate: dateFmt]
166            Map parameters = [title: title, separator: ","]
167
168            exportService.export(params.format, response.outputStream, taskInstanceList, fields, labels, formatters, parameters)
169        }
170
171        // Add some basic params to filterParams.
172        filterParams.max = params.max
173        filterParams.offset = params.offset?.toInteger() ?: 0
174        filterParams.sort = params.sort ?: "id"
175        filterParams.order = params.order ?: "desc"
176
177        // Get some associatedProperty values for filterpane.
178        def associatedPropertyValues = [:]
179        def associatedPropertyMax = 10000
180        associatedPropertyValues.taskPriorityList = TaskPriority.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
181        def lastNameQuery = 'select distinct p.lastName from Person p where p.isActive = ? order by p.lastName'
182        associatedPropertyValues.lastNameList = Person.executeQuery(lastNameQuery, [true], [max:associatedPropertyMax])
183        def firstNameQuery = 'select distinct p.firstName from Person p where p.isActive = ? order by p.firstName'
184        associatedPropertyValues.firstNameList = Person.executeQuery(firstNameQuery, [true], [max:associatedPropertyMax])
185        associatedPropertyValues.taskGroupList = TaskGroup.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
186        associatedPropertyValues.assetList = Asset.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
187        def highestSeverityCodeQuery = 'select distinct cs.code from ConditionSeverity cs where cs.isActive = ? order by cs.code'
188        associatedPropertyValues.highestSeverityList = ConditionSeverity.executeQuery(highestSeverityCodeQuery, [true], [max:associatedPropertyMax])
189        associatedPropertyValues.taskStatusList = TaskStatus.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
190        associatedPropertyValues.taskTypeList = TaskType.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
191        def startOfYearRange = dateUtilService.getYearFromDate(dateUtilService.plusYear(new Date(), -10))
192        def endOfYearRange = dateUtilService.getYearFromDate(dateUtilService.plusYear(new Date(), 10))
193        associatedPropertyValues.yearRange = startOfYearRange..endOfYearRange
194
195        return[ taskInstanceList: taskInstanceList,
196                        taskInstanceTotal: taskInstanceTotal,
197                        filterParams: filterParams,
198                        params: params,
199                        associatedPropertyValues: associatedPropertyValues,
200                        quickSearchSelection: taskSearchService.quickSearchSelection]
201
202    } // search
203
204    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
205    def searchCalendar = {
206
207        // No pagination for calendar.
208        params.offset = 0
209
210        // Restore params.max
211        if(session.taskSearchCalendarParamsMax)
212            params.max = session.taskSearchCalendarParamsMax
213
214        // Protect filterPane.
215        params.max = Math.min( params.max ? params.max.toInteger() : 100,  1000 )
216
217        def displayList = []
218        def taskInstanceList = []
219        def taskInstanceTotal
220        def filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
221        def isFilterApplied = FilterUtils.isFilterApplied(params)
222
223        // Restore search unless a new search is being requested.
224        if(!params.quickSearch && !filterParams) {
225            if(session.taskSearchCalendarFilterParams) {
226                session.taskSearchCalendarFilterParams.each() { params[it.key] = it.value }
227                params.filter = session.taskSearchCalendarFilter
228                isFilterApplied = FilterUtils.isFilterApplied(params)
229            }
230        }
231        if(!params.quickSearch) {
232            if(session.taskSearchCalendarQuickSearch) {
233                params.quickSearch = session.taskSearchCalendarQuickSearch
234                params.person = Person.get(session.taskCalendarQuickSearchPersonId.toLong())
235                params.startDate = session.taskCalendarQuickSearchStartDate
236                params.endDate = session.taskCalendarQuickSearchEndDate
237                params.includeCompleted = session.taskCalendarQuickSearchIncludeCompleted
238            }
239        }
240
241        // The date the calendar will use to determine the month to show.
242        // Use session, if not specified in params, otherwise use today.
243        def showDate = new Date()
244        if(params.showMonth) {
245            if(params.showYear)
246                showDate = dateUtilService.makeDate(params.showYear, params.showMonth)
247            else
248                showDate = dateUtilService.makeDate(dateUtilService.getYearFromDate(showDate), params.showMonth)
249            // Remember the showDate.
250            session.taskSearchCalendarShowDate = showDate
251        }
252        else if(session.taskSearchCalendarShowDate)
253            showDate = session.taskSearchCalendarShowDate
254
255        // Get the dates for the calendar month controls.
256        def calendarMonthControls = getCalendarMonthControls(showDate)
257
258        if(isFilterApplied) {
259            // filterPane:
260            params.sort = params.sort ?: "id"
261            params.order = params.order ?: "desc"
262            if(params.sort == "attentionFlag") // See ticket #64 in Trac.
263                params.sort = "id"
264            // Prevent tasks in the trash being returned unless explicitly requested.
265            if(!params.filter.op.trash) {
266                params.filter.op.trash = "Equal"
267                params.filter.trash = "false"
268            }
269            // Call filterService.
270            taskInstanceList = filterService.filter( params, Task )
271            taskInstanceTotal = filterService.count( params, Task )
272            filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
273            // Remember search.
274            session.taskSearchCalendarFilterParams = new LinkedHashMap(filterParams)
275            session.taskSearchCalendarFilter = new LinkedHashMap(params.filter)
276        }
277        else {
278            // Quick Search:
279            def result = taskSearchService.getQuickSearch(params, RCU.getLocale(request))
280            taskInstanceList = result.taskInstanceList
281            taskInstanceTotal = result.taskInstanceList.totalCount
282            params.message = result.message
283            params.quickSearch = result.quickSearch
284            params.person = result.person
285            params.startDate = result.startDate
286            params.endDate = result.endDate
287            params.includeCompleted = result.includeCompleted
288            // Remember search.
289            session.removeAttribute("taskSearchCalendarFilterParams")
290            session.removeAttribute("taskSearchCalendarFilter")
291            session.taskSearchCalendarQuickSearch = result.quickSearch
292            session.taskCalendarQuickSearchPersonId = result.person.id
293            session.taskCalendarQuickSearchStartDate = result.startDate
294            session.taskCalendarQuickSearchEndDate = result.endDate
295            session.taskCalendarQuickSearchIncludeCompleted = result.includeCompleted
296        }
297
298//         displayList = taskReportService.getWorkLoadSummary(
299//                                     [taskInstanceList: taskInstanceList], RCU.getLocale(request)
300//                                 ).displayList
301
302        // export plugin:
303        if(params?.format && params.format != "html") {
304
305            def dateFmt = { date ->
306                formatDate(format: "EEE, dd-MMM-yyyy", date: date)
307            }
308
309            String title
310            if(params.quickSearch)
311                title = params.message
312            else
313                title = "Filtered tasks."
314
315            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
316            response.setHeader("Content-disposition", "attachment; filename=Tasks.${params.extension}")
317            List fields = ["id", "targetStartDate", "description", "leadPerson", "taskPriority", "taskType", "taskStatus"]
318            Map labels = ["id": "ID", "targetStartDate": "Target Start Date", "description": "Description",
319                                    "leadPerson": "Lead Person", "taskPriority": "Task Priority",
320                                    "taskType": "Task Type", "taskStatus": "Task Status"]
321            Map formatters = [ targetStartDate: dateFmt]
322            Map parameters = [title: title, separator: ","]
323
324            exportService.export(params.format, response.outputStream, taskInstanceList, fields, labels, formatters, parameters)
325        }
326
327        if(taskInstanceTotal > params.max)
328            params.errorMessage = g.message(code:"task.search.calendar.text.too.many.results", args:[params.max])
329
330        // Add some basic params to filterParams.
331        filterParams.max = params.max
332        filterParams.offset = params.offset?.toInteger() ?: 0
333        filterParams.sort = params.sort ?: "id"
334        filterParams.order = params.order ?: "desc"
335
336        // Get some associatedProperty values for filterpane.
337        def associatedPropertyValues = [:]
338        def associatedPropertyMax = 10000
339        associatedPropertyValues.taskPriorityList = TaskPriority.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
340        def lastNameQuery = 'select distinct p.lastName from Person p where p.isActive = ? order by p.lastName'
341        associatedPropertyValues.lastNameList = Person.executeQuery(lastNameQuery, [true], [max:associatedPropertyMax])
342        def firstNameQuery = 'select distinct p.firstName from Person p where p.isActive = ? order by p.firstName'
343        associatedPropertyValues.firstNameList = Person.executeQuery(firstNameQuery, [true], [max:associatedPropertyMax])
344        associatedPropertyValues.taskGroupList = TaskGroup.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
345        associatedPropertyValues.assetList = Asset.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
346        def highestSeverityCodeQuery = 'select distinct cs.code from ConditionSeverity cs where cs.isActive = ? order by cs.code'
347        associatedPropertyValues.highestSeverityList = ConditionSeverity.executeQuery(highestSeverityCodeQuery, [true], [max:associatedPropertyMax])
348        associatedPropertyValues.taskStatusList = TaskStatus.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
349        associatedPropertyValues.taskTypeList = TaskType.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
350        def startOfYearRange = dateUtilService.getYearFromDate(dateUtilService.plusYear(new Date(), -10))
351        def endOfYearRange = dateUtilService.getYearFromDate(dateUtilService.plusYear(new Date(), 10))
352        associatedPropertyValues.yearRange = startOfYearRange..endOfYearRange
353
354        return[taskInstanceList: taskInstanceList,
355                        taskInstanceTotal: taskInstanceTotal,
356                        filterParams: filterParams,
357                        params: params,
358                        associatedPropertyValues: associatedPropertyValues,
359                        showDate: showDate,
360                        today: calendarMonthControls.today,
361                        previousMonth: calendarMonthControls.previousMonth,
362                        nextMonth: calendarMonthControls.nextMonth,
363                        previousYear: calendarMonthControls.previousYear,
364                        nextYear: calendarMonthControls.nextYear,
365                        quickSearchSelection: taskSearchService.quickSearchSelection]
366
367    } // searchCalendar
368
369    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
370    def show = {
371
372        // In the case of an actionSubmit button, rewrite action name from 'index'.
373        if(params._action_Show)
374            params.action='show'
375
376        // Used by navigation.
377        if(params.id == 'nav') {
378            params.id = session.currentTaskId ?: null
379            redirect(action: show, id: params.id)
380            return
381        }
382
383        def showTab = [:]
384        switch (params.showTab) {
385            case "showProcedureTab":
386                showTab.procedure =  new String("true")
387                break
388            case "showRecurrenceTab":
389                showTab.recurrence =  new String("true")
390                break
391            case "showInventoryTab":
392                showTab.inventory = new String("true")
393                break
394            case "showSubTasksTab":
395                showTab.subTasks = new String("true")
396                break
397            default:
398                showTab.task = new String("true")
399        }
400
401        def taskInstance = Task.get( params.id )
402
403        if(!taskInstance) {
404            flash.message = "Task not found with id ${params.id}"
405            redirect(action: 'search')
406        }
407        else {
408            // Remember the current task id for use with navigation.
409            session.currentTaskId = params.id
410
411            params.max = 10
412            params.order = "desc"
413            params.sort = "id"
414
415            def entryFaultList = Entry.withCriteria {
416                                                                eq("entryType", EntryType.get(1))
417                                                                eq("task", taskInstance)
418                                                        }
419
420            def entryCauseList = Entry.withCriteria {
421                                                                eq("entryType", EntryType.get(2))
422                                                                eq("task", taskInstance)
423                                                        }
424
425            def entryWorkDoneList = Entry.withCriteria {
426                                                                eq("entryType", EntryType.get(3))
427                                                                eq("task", taskInstance)
428                                                        }
429
430            def entryPMList = Entry.withCriteria {
431                                                                eq("entryType", EntryType.get(6))
432                                                                eq("task", taskInstance)
433                                                        }
434
435            def subTaskInstanceList = Task.findAllByParentTaskAndTrash(taskInstance, false, params)
436            def subTaskInstanceTotal = Task.countByParentTaskAndTrash(taskInstance, false)
437
438            def inventoryMovementList = InventoryMovement.findAllByTask(taskInstance, [max:100, sort:"id", order:"desc", offset:0])
439
440            def taskModificationList = TaskModification.findAllByTask(taskInstance, [max:100, sort:"id", order:"asc", offset:0])
441
442            def assignedGroupList = taskInstance.assignedGroups.sort { p1, p2 -> p1.personGroup.name.compareToIgnoreCase(p2.personGroup.name) }
443            def assignedPersonList = taskInstance.assignedPersons.sort { p1, p2 -> p1.person.firstName.compareToIgnoreCase(p2.person.firstName) }
444
445            def taskProcedureRevision = TaskProcedureRevision.get(taskInstance.taskProcedureRevision?.id)
446            def taskProcedureExits = new Boolean("true")
447            if(!taskProcedureRevision) {
448                taskProcedureExits = false
449            }
450
451            def taskRecurringScheduleInstance = TaskRecurringSchedule.get(taskInstance.taskRecurringSchedule?.id)
452            def taskRecurringScheduleExits= new Boolean("true")
453            if(!taskRecurringScheduleInstance) {
454                taskRecurringScheduleExits = false
455            }
456
457            return [ taskInstance: taskInstance,
458                            entryFaultList: entryFaultList,
459                            entryCauseList: entryCauseList,
460                            entryWorkDoneList: entryWorkDoneList,
461                            entryPMList: entryPMList,
462                            taskProcedureRevision: taskProcedureRevision,
463                            taskProcedureExits: taskProcedureExits,
464                            showTab: showTab,
465                            subTaskInstanceList: subTaskInstanceList,
466                            subTaskInstanceTotal: subTaskInstanceTotal,
467                            subTaskInstanceMax: params.max,
468                            taskRecurringScheduleInstance: taskRecurringScheduleInstance,
469                            taskRecurringScheduleExits: taskRecurringScheduleExits,
470                            inventoryMovementList: inventoryMovementList,
471                            taskModificationList: taskModificationList,
472                            assignedGroupList: assignedGroupList,
473                            assignedPersonList: assignedPersonList]
474        }
475    }
476
477    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
478    def restore = {
479
480        def result = taskService.restore(params)
481
482        if(!result.error) {
483                flash.message = "Task ${params.id} has been restored."
484                redirect(action: show, id: params.id)
485                return
486        }
487
488        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
489
490        if(result.taskInstance)
491            redirect(action: show, id: params.id)
492        else
493            redirect(action: 'search')
494
495    }
496
497    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
498    def trash = {
499
500        def result = taskService.trash(params)
501
502        if(!result.error) {
503                flash.message = "Task ${params.id} has been moved to trash."
504                redirect(action: 'search')
505                return
506        }
507
508        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
509
510        if(result.taskInstance)
511            redirect(action: show, id: params.id)
512        else
513            redirect(action: 'search')
514
515    }
516
517    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
518    def approve = {
519
520        def result = taskService.approve(params)
521
522        if(!result.error) {
523                flash.message = "Task ${params.id} has been approved."
524                redirect(action: show, id: params.id)
525                return
526        }
527
528        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
529
530        if(result.taskInstance)
531            redirect(action: show, id: params.id)
532        else
533            redirect(action: 'search')
534
535    }
536
537    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
538    def renegeApproval = {
539
540        def result = taskService.renegeApproval(params)
541
542        if(!result.error) {
543                flash.message = "Task ${params.id} has had approval removed."
544                redirect(action: show, id: params.id)
545                return
546        }
547
548        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
549
550        if(result.taskInstance)
551            redirect(action: show, id: params.id)
552        else
553            redirect(action: 'search')
554
555    }
556
557    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
558    def complete = {
559
560        def result = taskService.complete(params)
561
562        if(!result.error) {
563                flash.message = "Task ${params.id} has been completed."
564                redirect(action: show, id: params.id)
565                return
566        }
567
568        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
569
570        if(result.taskInstance)
571            redirect(action: show, id: params.id)
572        else
573            redirect(action: 'search')
574
575    }
576
577    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
578    def setAttentionFlag = {
579
580        def result = taskService.setAttentionFlag(params)
581
582        if(!result.error) {
583                flash.message = "Task ${params.id} has been flagged for attention."
584                redirect(action: show, id: params.id)
585                return
586        }
587
588        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
589
590        if(result.taskInstance)
591            redirect(action: show, id: params.id)
592        else
593            redirect(action: 'search')
594
595    }
596
597    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
598    def clearAttentionFlag = {
599
600        def result = taskService.clearAttentionFlag(params)
601
602        if(!result.error) {
603                flash.message = "Task ${params.id} attention flag cleared."
604                redirect(action: show, id: params.id)
605                return
606        }
607
608        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
609
610        if(result.taskInstance)
611            redirect(action: show, id: params.id)
612        else
613            redirect(action: 'search')
614
615    }
616
617    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
618    def reopen = {
619
620        def result = taskService.reopen(params)
621
622        if(!result.error) {
623                flash.message = "Task ${params.id} has been reopened."
624                redirect(action: show, id: params.id)
625                return
626        }
627
628        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
629
630        if(result.taskInstance)
631            redirect(action: show, id: params.id)
632        else
633            redirect(action: 'search')
634
635    }
636
637    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
638    def edit = {
639
640        // In the case of an actionSubmit button, rewrite action name from 'index'.
641        if(params._action_Edit)
642            params.action='edit'
643
644        // Used by navigation.
645        if(params.id == 'nav') {
646            params.id = session.currentTaskId ?: null
647            redirect(action: edit, id: params.id)
648            return
649        }
650
651        def taskInstance = Task.get( params.id )
652
653        if(!taskInstance) {
654            flash.message = "Task not found with id ${params.id}"
655            redirect(action: 'search')
656        }
657        else {
658            // Remember the current task id for use with navigation.
659            session.currentTaskId = params.id
660
661            if(taskInstance.trash) {
662                flash.message = "You may not edit tasks that are in the trash."
663                redirect(action: 'show', id: taskInstance.id)
664                return
665            }
666//             def possibleParentList = taskService.possibleParentList(taskInstance)
667//             return [ taskInstance : taskInstance, possibleParentList: possibleParentList ]
668            return [ taskInstance : taskInstance ]
669        }
670    }
671
672    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
673    def update = {
674
675        def result = taskService.update(params)
676
677        if(!result.error) {
678                flash.message = "Task ${params.id} updated"
679                redirect(action: show, id: params.id)
680                return
681        }
682
683        if(result.error.code == "task.modifications.failedToSave")
684            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
685
686        render(view:'edit',model:[taskInstance:result.taskInstance.attach()])
687
688    }
689
690    /**
691    * The create action is used to create scheduled types of tasks.
692    */
693    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager'])
694    def create = {
695        def taskInstance = new Task()
696
697        // Set the targetStartDate if specified, used by searchCalendar view.
698        if(params.year && params.month && params.day) {
699            def date = dateUtilService.makeDate(params.year, params.month, params.day)
700            taskInstance.targetStartDate = date
701            taskInstance.targetCompletionDate = date
702        }
703
704        // Default leadPerson to current user, unless supplied in params.
705        taskInstance.leadPerson = authService.currentUser
706
707        // Apply params, overiding anything above.
708        taskInstance.properties = params
709
710        def scheduledTaskTypes = taskService.scheduledTaskTypes
711        def scheduledTaskPriorities = taskService.scheduledTaskPriorities
712        taskInstance.taskPriority = scheduledTaskPriorities.default
713        return ['taskInstance': taskInstance,
714                    'scheduledTaskTypes': scheduledTaskTypes,
715                    'scheduledTaskPriorities': scheduledTaskPriorities.list]
716    }
717
718    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
719    def save = {
720        def result = taskService.save(params)
721
722        if(!result.error) {
723            flash.message = "Task ${result.taskInstance.id} created."
724            redirect(action: 'show', id: result.taskInstance.id)
725            return
726        }
727
728        if(result.error.code == "task.modifications.failedToSave")
729            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
730
731
732        def scheduledTaskTypes = taskService.scheduledTaskTypes
733        def scheduledTaskPriorities = taskService.scheduledTaskPriorities
734        render(view:'create', model:[taskInstance:result.taskInstance,
735                                                    'scheduledTaskTypes': scheduledTaskTypes,
736                                                    'scheduledTaskPriorities': scheduledTaskPriorities.list])
737    }
738
739    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
740    def listSubTasks = {
741        def parentTaskInstance = Task.get(params.id)
742
743        if(!parentTaskInstance) {
744            flash.message = "Task not found with id ${params.id}"
745            redirect(action: 'search')
746        }
747        else {
748        params.max = Math.min( params.max ? params.max.toInteger() : 200,  200)
749        def subTaskInstanceList = Task.findAllByParentTaskAndTrash(parentTaskInstance, false, params)
750        def subTaskInstanceTotal = Task.countByParentTaskAndTrash(parentTaskInstance, false)
751
752        [ taskInstanceList: subTaskInstanceList,
753            taskInstanceTotal:  subTaskInstanceTotal,
754            parentTaskInstance: parentTaskInstance]
755        }
756    }
757
758    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
759    def createSubTask = {
760        def parentTaskInstance = Task.get(params.id)
761
762        if(parentTaskInstance) {
763
764            def result = taskService.createSubTask(parentTaskInstance)
765            if(!result.error) {
766                flash.message = "Sub Task ${result.taskInstance.id} created, please edit and update to your requirements."
767                redirect(action: 'edit', id: result.taskInstance.id)
768            }
769            else {
770                if(result.taskInstance.errors.hasFieldErrors("parentTask")) {
771                    flash.errorMessage = g.message(code:"task.operationNotPermittedOnTaskInTrash")
772                    redirect(action: 'show', id:  parentTaskInstance.id)
773                }
774                else {
775                    render(view: 'create', model:[taskInstance: result.taskInstance])
776                }
777            }
778        }
779
780        else {
781            flash.message = "Task not found with id ${params.id}"
782            redirect(action: 'search')
783        }
784    }
785
786    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
787    def createUnscheduled = {
788        def taskInstance = new Task()
789
790        // Default leadPerson to current user, unless supplied in params.
791        taskInstance.leadPerson = authService.currentUser
792        taskInstance.properties = params
793
794        // Always for Unscheduled task.
795        taskInstance.taskType = TaskType.get(2) // Unscheduled Breakin.
796        def unscheduledTaskPriorities = taskService.unscheduledTaskPriorities
797        taskInstance.taskPriority = unscheduledTaskPriorities.default
798
799        return ['taskInstance': taskInstance, 'unscheduledTaskPriorities': unscheduledTaskPriorities.list]
800    }
801
802    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
803    def saveUnscheduled = {
804        def result = taskService.saveUnscheduled(params)
805
806        if(!result.error) {
807            flash.message = "Task ${result.taskInstance.id} created."
808            redirect(action: 'show', id: result.taskInstance.id)
809            return
810        }
811
812        if(result.error.code == "task.modifications.failedToSave")
813            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
814
815        def unscheduledTaskPriorities = taskService.unscheduledTaskPriorities
816
817        render(view:'createUnscheduled',
818                    model: ['taskInstance': result.taskInstance, 'unscheduledTaskPriorities': unscheduledTaskPriorities.list])
819    }
820
821    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
822    def createImmediateCallout = {
823        def taskInstance = new Task()
824
825        def entryFaultInstance = new Entry(entryType: EntryType.get(1))  // Fault.
826        def entryCauseInstance = new Entry(entryType: EntryType.get(2))  // Cause.
827        def entryWorkDoneInstance = new Entry(entryType: EntryType.get(3))  // Work Done.
828
829        return ['taskInstance': taskInstance,
830                        'entryFaultInstance': entryFaultInstance,
831                        'entryCauseInstance': entryCauseInstance,
832                        'entryWorkDoneInstance': entryWorkDoneInstance]
833    }
834
835    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
836    def saveImmediateCallout = {
837        def result = taskService.saveImmediateCallout(params)
838
839        if(!result.error) {
840            flash.message = "Task ${result.taskInstance.id} created."
841            redirect(action: 'show', id: result.taskInstance.id)
842            return
843        }
844
845        if(result.error.code == "task.modifications.failedToSave")
846            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
847
848        render(view:'createImmediateCallout',
849                    model: ['taskInstance': result.taskInstance,
850                                'entryFaultInstance': result.entryFaultInstance,
851                                'entryCauseInstance': result.entryCauseInstance,
852                                'entryWorkDoneInstance': result.entryWorkDoneInstance])
853
854    }
855
856    /**
857    * Render a users total work done hours.
858    */
859    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
860    def workDone = {
861        def result = taskSearchService.getWorkDone(params, RCU.getLocale(request))
862
863        params.message = result.message
864
865        return[entries: result.entries,
866                    totalEntries : result.totalEntries,
867                    startOfDay: result.startOfDay,
868                    person: result.person,
869                    totalHours: result.totalHours,
870                    totalMinutes: result.totalMinutes]
871    } // workDone
872
873    /**
874    * Render work load hours.
875    */
876    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_TaskManager', 'ROLE_TaskUser'])
877    def workLoad= {
878        def result = taskSearchService.getWorkLoad(params, RCU.getLocale(request))
879
880        params.message = result.message
881        params.errorMessage = result.errorMessage
882
883        return[tasks: result.tasks,
884                    startDate: result.startDate,
885                    endDate: result.endDate,
886                    taskGroups: result.taskGroups,
887                    taskStatusList: result.taskStatusList,
888                    workLoadGroups: result.workLoadGroups,
889                    totalHours: result.totalHours,
890                    totalMinutes: result.totalMinutes]
891    } // workLoad
892
893    /**
894    * Get some integers for use by the month control links.
895    */
896    private getCalendarMonthControls(Date showDate) {
897        def result = [:]
898        result.today = [:]
899        result.today.date = new Date()
900        result.today.month = dateUtilService.getMonthFromDate(result.today.date)
901        result.today.year = dateUtilService.getYearFromDate(result.today.date)
902        result.nextMonth = [:]
903        result.nextMonth.date = dateUtilService.plusMonth(showDate)
904        result.nextMonth.month = dateUtilService.getMonthFromDate(result.nextMonth.date)
905        result.nextMonth.year = dateUtilService.getYearFromDate(result.nextMonth.date)
906        result.previousMonth =  [:]
907        result.previousMonth.date = dateUtilService.plusMonth(showDate, -1)
908        result.previousMonth.month = dateUtilService.getMonthFromDate(result.previousMonth.date)
909        result.previousMonth.year = dateUtilService.getYearFromDate(result.previousMonth.date)
910        result.nextYear = [:]
911        result.nextYear.date = dateUtilService.plusYear(showDate)
912        result.nextYear.month = dateUtilService.getMonthFromDate(result.nextYear.date)
913        result.nextYear.year = dateUtilService.getYearFromDate(result.nextYear.date)
914        result.previousYear = [:]
915        result.previousYear.date = dateUtilService.plusYear(showDate, -1)
916        result.previousYear.month = dateUtilService.getMonthFromDate(result.previousYear.date)
917        result.previousYear.year = dateUtilService.getYearFromDate(result.previousYear.date)
918        return result
919    }
920
921} // end of class.
Note: See TracBrowser for help on using the repository browser.