source: trunk/grails-app/controllers/InventoryItemDetailedController.groovy @ 554

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

Get Inventory Search filterpane associatedPropertyValues in controller instead of in gsp.

File size: 19.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_InventoryManager'])
7class InventoryItemDetailedController extends BaseController {
8
9    def filterService
10    def exportService
11    def inventoryCsvService
12    def inventoryItemService
13    def inventoryItemSearchService
14    def inventoryMovementService
15
16    // the delete, save and update actions only accept POST requests
17    static allowedMethods = [delete:'POST', save:'POST', update:'POST', useInventoryItem:'POST']
18
19    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
20    def index = { redirect(action:search, params:params) }
21
22    /**
23    * Set session.inventoryItemSearchParamsMax
24    */
25    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
26    def setSearchParamsMax = {
27        def max = 1000
28        if(params.newMax.isInteger()) {
29            def i = params.newMax.toInteger()
30            if(i > 0 && i <= max)
31                session.inventoryItemSearchParamsMax = params.newMax
32            if(i > max)
33                session.inventoryItemSearchParamsMax = max
34        }
35        forward(action: 'search', params: params)
36    }
37
38    /**
39    * Display the import view.
40    */
41    def importInventory = {
42    }
43
44    /**
45    * Handle the import save.
46    */
47    def importInventorySave = {
48        def result = inventoryCsvService.importInventory(request)
49
50        if(!result.error) {
51            flash.message = g.message(code: "inventory.import.success")
52            redirect(action:search)
53            return
54        }
55
56        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
57        redirect(action: importInventory)
58    }
59
60    /**
61    * Export a csv template.
62    * NOTE: IE has a 'validating' bug in dev mode that causes the export to take a long time!
63    * This does not appear to be a problem once deployed to Tomcat.
64    */
65    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
66    def exportInventoryTemplate = {
67        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
68        response.setHeader("Content-disposition", "attachment; filename=InventoryTemplate.csv")
69        def s = inventoryCsvService.buildInventoryTemplate()
70        render s
71    }
72
73    /**
74    * Export a csv test file.
75    */
76    def exportInventoryExample = {
77        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
78        response.setHeader("Content-disposition", "attachment; filename=InventoryExample.csv")
79        def s = inventoryCsvService.buildInventoryExample()
80        render s
81    }
82
83    /**
84    * Export the entire inventory as a csv file.
85    */
86    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
87    def exportInventory = {
88
89        def inventoryItemList = InventoryItem.list()
90
91        response.contentType = ConfigurationHolder.config.grails.mime.types["csv"]
92        response.setHeader("Content-disposition", "attachment; filename=Inventory.csv")
93        def s = inventoryCsvService.buildInventory(inventoryItemList)
94        render s
95    }
96
97    /**
98    * Display the import view for purchases.
99    */
100    def importInventoryItemPurchases = {
101    }
102
103    /**
104    * Handle the inventory purchases import save.
105    */
106    def importInventoryItemPurchasesSave = {
107        def result = inventoryCsvService.importInventoryItemPurchases(request)
108
109        if(!result.error) {
110            flash.message = g.message(code: "inventory.import.success")
111            redirect(action:search)
112            return
113        }
114
115        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
116        redirect(action: importInventoryItemPurchases)
117    }
118
119    /**
120    * Search for Inventory items.
121    */
122    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
123    def search = {
124
125        if(session.inventoryItemSearchParamsMax)
126            params.max = session.inventoryItemSearchParamsMax
127
128        // Protect filterPane.
129        params.max = Math.min( params.max ? params.max.toInteger() : 10,  1000)
130
131        def inventoryItemInstanceList = []
132        def inventoryItemInstanceTotal
133        def filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
134        def isFilterApplied = FilterUtils.isFilterApplied(params)
135
136        // Restore search unless a new search is being requested.
137        if(!params.quickSearch && !filterParams) {
138            if(session.inventoryItemQuickSearch) {
139                params.quickSearch = session.inventoryItemQuickSearch
140                if(session.inventoryItemQuickSearchDaysBack)
141                    params.daysBack = session.inventoryItemQuickSearchDaysBack.toString()
142            }
143            else if(session.inventoryItemSearchFilterParams) {
144                session.inventoryItemSearchFilterParams.each() { params[it.key] = it.value }
145                params.filter = session.inventoryItemSearchFilter
146                isFilterApplied = FilterUtils.isFilterApplied(params)
147            }
148        }
149
150        // Remember sort if supplied, otherwise try to restore.
151        if(params.sort && params.order) {
152             session.inventoryItemSearchSort = params.sort
153             session.inventoryItemSearchOrder = params.order
154        }
155        else if(session.inventoryItemSearchSort && session.inventoryItemSearchOrder) {
156            params.sort = session.inventoryItemSearchSort
157            params.order = session.inventoryItemSearchOrder
158        }
159
160        if(isFilterApplied) {
161            // filterPane:
162            inventoryItemInstanceList = filterService.filter( params, InventoryItem )
163            inventoryItemInstanceTotal = filterService.count( params, InventoryItem )
164            filterParams = com.zeddware.grails.plugins.filterpane.FilterUtils.extractFilterParams(params)
165            // Remember search.
166            session.inventoryItemSearchFilterParams = new LinkedHashMap(filterParams)
167            session.inventoryItemSearchFilter = new LinkedHashMap(params.filter)
168            session.removeAttribute("inventoryItemQuickSearch")
169            session.removeAttribute("inventoryItemQuickSearchDaysBack")
170        }
171        else {
172            // Quick Search:
173            if(!params.quickSearch) params.quickSearch = "all"
174            def result = inventoryItemSearchService.getQuickSearch(params, RCU.getLocale(request))
175            inventoryItemInstanceList = result.inventoryItemList
176            inventoryItemInstanceTotal = result.inventoryItemList.totalCount
177            params.message = result.message
178            filterParams.quickSearch = result.quickSearch
179            // Remember search.
180            session.removeAttribute("inventoryItemSearchFilterParams")
181            session.removeAttribute("inventoryItemSearchFilter")
182            session.inventoryItemQuickSearch = result.quickSearch
183            if(result.daysBack)
184                session.inventoryItemQuickSearchDaysBack = result.daysBack
185        }
186
187        // export plugin:
188        if(params?.format && params.format != "html") {
189
190            def dateFmt = { date ->
191                formatDate(format: "EEE, dd-MMM-yyyy", date: date)
192            }
193
194            String title
195            if(params.quickSearch)
196                title = params.message
197            else
198                title = "Filtered Inventory List."
199
200            response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
201            response.setHeader("Content-disposition", "attachment; filename=Inventory.${params.extension}")
202            List fields = ["name",
203                                "description",
204                                "inventoryGroup",
205                                "unitsInStock",
206                                "reorderPoint",
207                                "unitOfMeasure",
208                                "inventoryLocation",
209                                "inventoryLocation.inventoryStore"]
210            Map labels = ["name": "Name",
211                                "description": "Description",
212                                "inventoryGroup": "Group",
213                                "unitsInStock":"In Stock",
214                                "reorderPoint":"Reorder Point",
215                                "unitOfMeasure": "UOM",
216                                "inventoryLocation": "Location",
217                                "inventoryLocation.inventoryStore": "Store"]
218
219            Map formatters = [:]
220            Map parameters = [title: title, separator: ","]
221
222            exportService.export(params.format,
223                                                response.outputStream,
224                                                inventoryItemInstanceList.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) },
225                                                fields,
226                                                labels,
227                                                formatters,
228                                                parameters)
229        }
230
231        // Add some basic params to filterParams.
232        filterParams.max = params.max
233        filterParams.offset = params.offset?.toInteger() ?: 0
234        filterParams.sort = params.sort ?: "name"
235        filterParams.order = params.order ?: "asc"
236
237        // Get some associatedProperty values for filterpane.
238        def associatedPropertyValues = [:]
239        def associatedPropertyMax = 10000
240        associatedPropertyValues.inventoryLocationList = InventoryLocation.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
241        associatedPropertyValues.assetList = Asset.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
242        associatedPropertyValues.manufacturerList = Manufacturer.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
243        associatedPropertyValues.supplierList = Supplier.findAllByIsActive(true, [max:associatedPropertyMax, sort:'name'])
244
245        return[ inventoryItemInstanceList: inventoryItemInstanceList,
246                        inventoryItemInstanceTotal: inventoryItemInstanceTotal,
247                        filterParams: filterParams,
248                        params: params,
249                        associatedPropertyValues: associatedPropertyValues ]
250    } // end search()
251
252    /**
253    * Simply assigns a passed in task id to a session variable and redirects to search.
254    */
255    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
256    def findInventoryItemForMovement = {
257        if(!params.task?.id) {
258            flash.message = "No task id supplied, please select a task then the inventory tab."
259            redirect(controller: "taskDetailed", action: "search")
260            return
261        }
262
263        session.inventoryMovementTaskId = params.task.id
264        flash.message = "Please find and then select the inventory item."
265        redirect(action: search)
266    }
267
268    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
269    def show = {
270
271        // In the case of an actionSubmit button, rewrite action name from 'index'.
272        if(params._action_Show)
273            params.action='show'
274
275        def result = inventoryItemService.show(params)
276
277        if(!result.error) {
278
279            def model = [ inventoryItemInstance: result.inventoryItemInstance,
280                                    inventoryMovementList: result.inventoryMovementList,
281                                    inventoryMovementListTotal: result.inventoryMovementListTotal,
282                                    inventoryMovementListMax: result.inventoryMovementListMax,
283                                    inventoryItemPurchases: result.inventoryItemPurchases,
284                                    inventoryItemPurchasesTotal: result.inventoryItemPurchasesTotal,
285                                    showTab: result.showTab]
286
287            if(session.inventoryMovementTaskId) {
288                model.inventoryMovementInstance = new InventoryMovement()
289                model.inventoryMovementInstance.task = Task.get(session.inventoryMovementTaskId)
290                model.inventoryMovementInstance.quantity = 1
291            }
292
293            // Success.
294            return model
295        }
296
297        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
298        redirect(action:search)
299    }
300
301    def delete = {
302        def result = inventoryItemService.delete(params)
303
304        if(!result.error) {
305            flash.message = g.message(code: "default.delete.success", args: ["InventoryItem", params.id])
306            redirect(action:search)
307            return
308        }
309
310        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
311
312        if(result.error.code == "default.not.found") {
313            redirect(action:search)
314            return
315        }
316
317        redirect(action:show, id: params.id)
318    }
319
320    def edit = {
321
322        // In the case of an actionSubmit button, rewrite action name from 'index'.
323        if(params._action_Edit)
324            params.action='edit'
325
326        def result = inventoryItemService.edit(params)
327
328        if(!result.error) {
329            def possibleAlternateItems = inventoryItemService.getPossibleAlternateItems(result.inventoryItemInstance)
330            def suppliers = Supplier.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
331            def manufacturers = Manufacturer.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
332
333            return [ inventoryItemInstance : result.inventoryItemInstance,
334                            possibleAlternateItems: possibleAlternateItems,
335                            suppliers: suppliers,
336                            manufacturers: manufacturers]
337        }
338
339        flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
340        redirect(action:search)
341    }
342
343    def update = {
344        def result = inventoryItemService.update(params)
345
346        if(!result.error) {
347            flash.message = g.message(code: "default.update.success", args: ["InventoryItem", params.id])
348            redirect(action:show, id: params.id)
349            return
350        }
351
352        if(result.error.code == "default.not.found") {
353            flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
354            redirect(action:search)
355            return
356        }
357
358        def possibleAlternateItems = inventoryItemService.getPossibleAlternateItems(result.inventoryItemInstance)
359        def suppliers = Supplier.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
360        def manufacturers = Manufacturer.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
361        render(view:'edit', model:[inventoryItemInstance: result.inventoryItemInstance.attach(),
362                                                possibleAlternateItems: possibleAlternateItems,
363                                                suppliers: suppliers,
364                                                manufacturers: manufacturers])
365    }
366
367    def create = {
368        def result = inventoryItemService.create(params)
369        def suppliers = Supplier.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
370        def manufacturers = Manufacturer.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
371
372        if(!result.error)
373            return [inventoryItemInstance: result.inventoryItemInstance,
374                            suppliers: suppliers,
375                            manufacturers: manufacturers]
376
377        //flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
378        redirect(action: search)
379    }
380
381    def save = {
382        def result = inventoryItemService.save(params)
383
384        if(!result.error) {
385            flash.message = g.message(code: "default.create.success", args: ["InventoryItem", result.inventoryItemInstance.id])
386            redirect(action:show, id: result.inventoryItemInstance.id)
387            return
388        }
389
390        def suppliers = Supplier.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
391        def manufacturers = Manufacturer.findAllByIsActive(true).sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }
392
393        //flash.errorMessage = g.message(code: result.error.code, args: result.error.args)
394        render(view:'create', model:[inventoryItemInstance: result.inventoryItemInstance,
395                                                    suppliers: suppliers,
396                                                    manufacturers: manufacturers])
397    }
398
399    /**
400    * Handles the use inventory item form submit in the show view.
401    */
402    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
403    def useInventoryItem = {
404
405        params.inventoryMovementType = InventoryMovementType.get(1) // Set type to "Used".
406        def result = inventoryMovementService.move(params)
407
408        if(!result.error) {
409            flash.message = "Inventory Movement for ${result.inventoryMovementInstance.inventoryItem.name.encodeAsHTML()} created."
410            session.inventoryMovementTaskId = null
411            redirect(controller: "taskDetailed",
412                            action: "show",
413                            id: result.taskId,
414                            params: [showTab: "showInventoryTab"])
415            // Success.
416            return
417        }
418
419        // Prepare data for the show view.
420        def p = [:]
421        p.id = result.inventoryMovementInstance.inventoryItem?.id
422        def r = inventoryItemService.show(p)
423
424        // Render show view if data was successfully prepared.
425        if(!r.error) {
426            def model = [ inventoryItemInstance: r.inventoryItemInstance,
427                                    inventoryMovementList: r.inventoryMovementList,
428                                    inventoryMovementListTotal: r.inventoryMovementListTotal,
429                                    inventoryMovementListMax: r.inventoryMovementListMax,
430                                    inventoryItemPurchases: r.inventoryItemPurchases,
431                                    inventoryItemPurchasesTotal: r.inventoryItemPurchasesTotal,
432                                    showTab: r.showTab]
433
434            model.inventoryMovementInstance = result.inventoryMovementInstance // This will pass in the errors.
435
436            render(view: 'show', model: model)
437            return
438        }
439
440        // Could not prepare data for show view so doing the next best thing.
441        flash.errorMessage = g.message(code: r.error.code, args: r.error.args)
442        redirect(action:search)
443
444    } // useInventoryItem
445
446    /**
447    * Clear the use inventory item form in the show view.
448    * Accomplished by clearing the session variable and ajax.
449    */
450    @Secured(['ROLE_AppAdmin', 'ROLE_Manager', 'ROLE_InventoryManager', 'ROLE_InventoryUser'])
451    def clearUseInventoryItem = {
452            session.inventoryMovementTaskId = null
453            render ''
454    }
455
456} // end of class
Note: See TracBrowser for help on using the repository browser.