source: trunk/grails-app/services/AssetReportService.groovy @ 735

Last change on this file since 735 was 735, checked in by gav, 13 years ago

Small correction to getEquipmentRegister report query.

File size: 13.0 KB
RevLine 
[652]1import net.kromhouts.HqlBuilder
2
3/**
4* Service class that encapsulates the business logic for Asset Reports.
5*/
6class AssetReportService {
7
8    boolean transactional = false
9
10    def authService
11    def dateUtilService
12//     def messageSource
13
14    def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()
15
16    def paramsMax = 100000
17
18    /**
19    * Selects and returns the assets and their details.
20    * @param params The request params, may contain params to specify the search.
21    * @param locale The locale to use when generating result.message.
22    */
23    def getAssetRegister(params, locale) {
24        def result = [:]
25
[681]26        result.section = Section.get(params.section.id.toLong())
27        result.site = result.section.site
28
[652]29        // Inner join used to return only attribTypes that are used by AssetExtendedAttributes.
30        // So the result is only asset extendedAttributeTypes.
[686]31//         def attribTypesQ = new HqlBuilder().query {
32//             select 'distinct attribT.name'
33//             from 'AssetExtendedAttribute attrib',
34//                     'join attrib.extendedAttributeType as attribT'
35//             order 'by attribT.name asc'
36//         }
37
38        // All active ExtendedAttributes.
[652]39        def attribTypesQ = new HqlBuilder().query {
40            select 'distinct attribT.name'
[686]41            from 'ExtendedAttributeType attribT'
42            where 'attribT.isActive = true'
[652]43            order 'by attribT.name asc'
44        }
[686]45        result.attribTypes = ExtendedAttributeType.executeQuery(attribTypesQ.query, attribTypesQ.namedParams)
[652]46
47        // A result is returned for every asset and for any extended attributes.
48        def q = new HqlBuilder().query {
49            select 'new map(asset.name as name',
50                        'asset.description as description',
51                        'asset.comment as comment',
52                        'attribT.name as attribType',
53                        'attrib.value as attribValue)'
54            from 'Asset asset',
55                    'left join asset.assetExtendedAttributes as attrib',
56                    'left join attrib.extendedAttributeType as attribT'
[681]57            where 'asset.section = :section'
58                    namedParams.section = result.section
[652]59            order 'by asset.name asc, attribT.name asc'
60        }
61        def assetResults = Asset.executeQuery(q.query, q.namedParams)
62
63        // Build the report table row for each asset.
64        // Rows are keyed by asset.name and the value is a Map of the attributes.
65        def rows = [:]
66        assetResults.each { assetResult ->
67            // Create row if it does not exist yet.
68            if(!rows.containsKey(assetResult.name)) {
69                rows[assetResult.name] = ['name':assetResult.name,
70                                                            'description':assetResult.description,
71                                                            'comment':assetResult.comment]
72
73                // Add all attribType columns.
74                result.attribTypes.each { column ->
[686]75                    rows[assetResult.name][column] = ' '
[652]76                }
77            }
78
79            // Assign value to column.
80            rows[assetResult.name][assetResult.attribType] = assetResult.attribValue
81        }
82
83        // The value of each row is the dataList used by the report table.
84        result.dataList = rows.collect {it.value}
85
86        // Success.
87        return result
88
89    } // getAssetRegister
90
91    /**
92    * Selects and returns an asset (or all) and its details.
93    * @param params The request params, may contain params to specify the search.
94    * @param locale The locale to use when generating result.message.
95    */
96    def getAssetDetail(params, locale) {
97        //def result = [:]
98        def result
99
100        //result.summaryOfCalculationMethod = ''
101
102        // A result is returned for every asset and for any extended attributes.
103        // The report then groups by asset.name
104        def q = new HqlBuilder().query {
105            select 'new map(asset.name as name',
106                        'asset.description as description',
107                        'asset.comment as comment',
108                        'attribT.name as attribType',
109                        'attrib.value as attribValue)'
110            from 'Asset asset',
111                    'left join asset.assetExtendedAttributes as attrib',
112                    'left join attrib.extendedAttributeType as attribT'
[687]113            if(params.section instanceof Section) {
114                namedParams.section = params.section
115                where 'asset.section = :section'
[652]116            }
117            order 'by asset.name asc, attribT.name asc'
118        }
119
120        // result.dataList = Asset.list()
121        result = Asset.executeQuery(q.query, q.namedParams)
122
123        // Success.
124        return result
125
126    } // getAssetDetail
127
[654]128    /**
129    * Selects and returns level 1 sub items (aka machines or equipment) and their details.
130    * @param params The request params, may contain params to specify the search.
131    * @param locale The locale to use when generating result.message.
132    */
133    def getEquipmentRegister(params, locale) {
134        def result = [:]
135
[710]136        def fail = { Map m ->
137            result.error = [ code: m.code, args: [] ]
138            return result
139        }
140
[679]141        result.section = Section.get(params.section.id.toLong())
142        result.site = result.section.site
143
[733]144        result.startDate = params.startDate ?: dateUtilService.oneWeekAgo
145        result.endDate = params.endDate ?: dateUtilService.today
[732]146        // Auto swap date range.
[733]147        if(result.startDate > result.endDate) {
148            def tempStartDate = result.startDate
149            result.startDate = result.endDate
150            result.endDate = tempStartDate
[732]151        }
[706]152
[733]153        result.startDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: result.startDate)
154        result.endDateString = g.formatDate(format: "EEE, dd-MMM-yyyy", date: result.endDate)
155
[654]156        // Inner join used to return only attribTypes that are used by AssetSubItemExtendedAttributes.
157        // So the result is only assetSubItem extendedAttributeTypes.
[686]158//         def attribTypesQ = new HqlBuilder().query {
159//             select 'distinct attribT.name'
160//             from 'AssetSubItemExtendedAttribute attrib',
161//                     'join attrib.extendedAttributeType as attribT'
162//             order 'by attribT.name asc'
163//         }
164
165        // All active ExtendedAttributes.
[654]166        def attribTypesQ = new HqlBuilder().query {
167            select 'distinct attribT.name'
[686]168            from 'ExtendedAttributeType attribT'
169            where 'attribT.isActive = true'
[654]170            order 'by attribT.name asc'
171        }
[686]172        result.attribTypes = ExtendedAttributeType.executeQuery(attribTypesQ.query, attribTypesQ.namedParams)
[654]173
[679]174        // A useful list of assets without subItems to be given to the user.
[654]175        def assetsWithoutEquipmentQ = new HqlBuilder().query {
176            select 'distinct asset'
177            from 'Asset asset',
178                    'left join asset.assetSubItems as assetSubItem'
179            where 'assetSubItem = null'
[679]180                namedParams.section = result.section
181                and 'asset.section = :section'
[654]182        }
[735]183        result.assetsWithoutEquipment = Asset.executeQuery(assetsWithoutEquipmentQ.query, assetsWithoutEquipmentQ.namedParams)
[654]184
[706]185        // Subquery to count regulatory tasks.
186        def regulatoryTaskCountQ = new HqlBuilder().query {
187
188            select 'count (distinct task)'
189            from 'Task as task',
190                    'left join task.associatedAssets as associatedAsset'
[728]191            where 'task.regulatoryRequirement = true'
[706]192                and 'task.targetStartDate < :endDate'
193                and 'task.targetCompletionDate >= :startDate'
194                and '(task.primaryAsset.id = asset.id or associatedAsset.id = asset.id)'
195                and 'task.trash = false'
196        }
197
198        def totalRegulatoryTaskCountQ = regulatoryTaskCountQ.query
199
200        regulatoryTaskCountQ.and 'task.taskStatus.id = 3'
201        def completedRegulatoryTaskCountQ = regulatoryTaskCountQ.query
202
[654]203        // A result is returned for every level 1 assetSubItem and for any extended attributes.
204        def q = new HqlBuilder().query {
[706]205
[654]206            select 'new map(asset.name as assetName',
207                        'assetSubItem.name as name',
208                        'assetSubItem.description as description',
209                        'assetSubItem.comment as comment',
[706]210                        "0 as totalRegulatoryTaskCount",
211                        "0 as completedRegulatoryTaskCount",
[654]212                        'attribT.name as attribType',
213                        'attrib.value as attribValue)'
214            from 'AssetSubItem assetSubItem',
215                    'inner join assetSubItem.assets as asset',
216                    'left join assetSubItem.assetSubItemExtendedAttributes as attrib',
217                    'left join attrib.extendedAttributeType as attribT'
218            where 'asset != null' // ensure that only level 1 assetSubItems are returned.
[679]219                namedParams.section = result.section
[654]220                and 'asset.section = :section'
221            order 'by asset.name asc, assetSubItem.name asc, attribT.name asc'
222        }
223        def equipmentResults = AssetSubItem.executeQuery(q.query, q.namedParams)
224
[679]225        // A result is returned for every asset and for any extended attributes.
226        def assetResultsQ = new HqlBuilder().query {
[706]227
228            // Subquery namedParams.
[733]229            namedParams.startDate = result.startDate
230            namedParams.endDate = result.endDate+1
[706]231
[679]232            select 'new map(asset.name as assetName',
233                        "'   Asset Details' as name", // Place holder 'equipment' name, 3 leading spaces for sorting.
234                        'asset.description as description',
235                        'asset.comment as comment',
[706]236                        "($totalRegulatoryTaskCountQ) as totalRegulatoryTaskCount",
237                        "($completedRegulatoryTaskCountQ) as completedRegulatoryTaskCount",
[679]238                        'attribT.name as attribType',
239                        'attrib.value as attribValue)'
240            from 'Asset asset',
241                    'left join asset.assetExtendedAttributes as attrib',
242                    'left join attrib.extendedAttributeType as attribT'
243            where 'asset.section = :section'
244                    namedParams.section = result.section
245            order 'by asset.name asc, attribT.name asc'
246        }
247        def assetResults = Asset.executeQuery(assetResultsQ.query, assetResultsQ.namedParams)
248
249        // Add asset details to equipmentResults.
250        equipmentResults.addAll(assetResults)
251        equipmentResults.sort { p1, p2 -> p1.assetName.compareToIgnoreCase(p2.assetName) ?: p1.name.compareToIgnoreCase(p2.name) }
252
[654]253        // Build the report table rows.
254        // Rows are keyed by equipmentResult.assetName+equipmentResult.name` while the value is a Map of the attributes.
255        // The report table then groups by assetName.
256        def rows = [:]
257        equipmentResults.each { equipmentResult ->
[706]258
[654]259            def rowKey = equipmentResult.assetName+equipmentResult.name
[706]260
261            // Create new row if it does not exist yet.
[654]262            if(!rows.containsKey(rowKey)) {
263                rows[rowKey] = ['assetName': equipmentResult.assetName,
[706]264                                            'name':equipmentResult.name,
265                                            'description':equipmentResult.description,
266                                            'comment':equipmentResult.comment,
267                                            'Regulatory Task Completion': ' ']
[654]268
269                // Add all attribType columns.
270                result.attribTypes.each { column ->
[686]271                    rows[rowKey][column] = ' '
[654]272                }
273
[706]274                // Caluculate and assign RegulatoryTaskCompletion, only for Assets.
275                if(params.calculateRegulatoryTaskCompletion) {
276
277                    if(equipmentResult.totalRegulatoryTaskCount) {
278                        def percentComplete = (equipmentResult.completedRegulatoryTaskCount / equipmentResult.totalRegulatoryTaskCount)*100
279                        rows[rowKey]['Regulatory Task Completion'] = "${percentComplete.toInteger()}% (${equipmentResult.completedRegulatoryTaskCount}/${equipmentResult.totalRegulatoryTaskCount})"
280                    }
281                    else if(equipmentResult.name == '   Asset Details')
282                        rows[rowKey]['Regulatory Task Completion'] = 'N/A'
283                }
284
285            } // Create new row.
286
[654]287            // Assign value to column.
288            rows[rowKey][equipmentResult.attribType] = equipmentResult.attribValue
[706]289        } // each.
[654]290
291        // The value of each row is the dataList used by the report table.
292        result.dataList = rows.collect {it.value}
293        // Print formatting, since we are done with these as objects.
294        result.attribTypes = result.attribTypes.join(', ')
295        result.assetsWithoutEquipment = result.assetsWithoutEquipment.collect {it.name}.join(', ')
296
297        // Success.
298        return result
299
300    } // getEquipmentRegister
301
[652]302} // end class
Note: See TracBrowser for help on using the repository browser.