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

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

New defaultSort for Tasks, sort by status then priority then target start date.
Small improvement to custom:sortableColumnWithImg to allow imgTitle to be specified.

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