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

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

Domain change, first draft of TaskProcedureRevisions.

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