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

Last change on this file since 585 was 585, checked in by gav, 14 years ago

First draft of displaying work load on task calendar, see ticket #66.

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