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

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

Small refator of DateUtilService.
New plusMonth() replaces getNextMonth and getPreviousMonth().
Clarify getDayFromDate() to getDayOfMonthFromDate().

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