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

Last change on this file since 962 was 962, checked in by gav, 12 years ago

Formatting only, no code change.

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