fleetmap-reports 1.0.305 → 1.0.309

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.idea/aws.xml ADDED
@@ -0,0 +1,17 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="accountSettings">
4
+ <option name="activeProfile" value="profile:default" />
5
+ <option name="activeRegion" value="us-east-1" />
6
+ <option name="recentlyUsedProfiles">
7
+ <list>
8
+ <option value="profile:default" />
9
+ </list>
10
+ </option>
11
+ <option name="recentlyUsedRegions">
12
+ <list>
13
+ <option value="us-east-1" />
14
+ </list>
15
+ </option>
16
+ </component>
17
+ </project>
@@ -0,0 +1,7 @@
1
+ <component name="ProjectCodeStyleConfiguration">
2
+ <code_scheme name="Project" version="173">
3
+ <ScalaCodeStyleSettings>
4
+ <option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
5
+ </ScalaCodeStyleSettings>
6
+ </code_scheme>
7
+ </component>
@@ -1,8 +1,9 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
- <module type="WEB_MODULE" version="4">
2
+ <module type="JAVA_MODULE" version="4">
3
3
  <component name="NewModuleRootManager" inherit-compiler-output="true">
4
4
  <exclude-output />
5
5
  <content url="file://$MODULE_DIR$" />
6
+ <orderEntry type="inheritedJdk" />
6
7
  <orderEntry type="sourceFolder" forTests="false" />
7
8
  </component>
8
9
  </module>
@@ -1,6 +1,6 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
2
  <project version="4">
3
3
  <component name="JavaScriptLibraryMappings">
4
- <includedPredefinedLibrary name="Node.js Core" />
4
+ <file url="file://$PROJECT_DIR$" libraries="{Node.js Core}" />
5
5
  </component>
6
6
  </project>
package/.idea/modules.xml CHANGED
@@ -2,7 +2,7 @@
2
2
  <project version="4">
3
3
  <component name="ProjectModuleManager">
4
4
  <modules>
5
- <module fileurl="file://$PROJECT_DIR$/fleetmap-reports.iml" filepath="$PROJECT_DIR$/fleetmap-reports.iml" />
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/fleetmap-reports.iml" filepath="$PROJECT_DIR$/.idea/fleetmap-reports.iml" />
6
6
  </modules>
7
7
  </component>
8
8
  </project>
package/.idea/vcs.xml CHANGED
@@ -1,6 +1,6 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
2
  <project version="4">
3
3
  <component name="VcsDirectoryMappings">
4
- <mapping directory="$PROJECT_DIR$" vcs="Git" />
4
+ <mapping directory="" vcs="Git" />
5
5
  </component>
6
6
  </project>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetmap-reports",
3
- "version": "1.0.305",
3
+ "version": "1.0.309",
4
4
  "description": "",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -8,39 +8,31 @@ const {headerFromUser, addTable} = require("./util/pdfDocument")
8
8
  const {getStyle} = require("./reportStyle")
9
9
  const {getUserPartner} = require("fleetmap-partners")
10
10
  const traccar = require("./util/traccar")
11
- const {createKmsReport} = require("./kms-report");
12
- const {isInsideTimetable} = require("./util/trips");
13
- const { Document, Packer, Paragraph, TextRun } = require("docx")
14
- import { saveAs } from "file-saver"
15
- let traccarInstance
16
- let userData
11
+ const {isInsideTimetable, isPartialInsideTimetable} = require("./util/trips");
12
+ const trips = require("./util/trips");
17
13
 
18
14
  const fileName = 'ActivityReport'
19
15
 
20
- async function createActivityReport(from, to, reportUserData, traccar) {
16
+ async function createActivityReport(from, to, userData, traccarInstance) {
21
17
  console.log('Create ActivityReport')
22
- traccarInstance = traccar
23
- userData = reportUserData
24
18
  const reportData = []
25
19
 
26
20
  if(userData.byDriver){
27
- const allData = await createActivityReportByDriver(from, to)
21
+ const allData = await createActivityReportByDriver(from, to, userData, traccarInstance)
28
22
  reportData.push(allData)
29
23
  }
30
24
  else if(userData.byGroup){
31
- const allGroupsData = await createActivityReportByGroup(from, to)
32
- allGroupsData.forEach(data => reportData.push(data))
33
- const withoutGroupDevices = await createActivityReportByDevice(from, to)
34
- reportData.push(withoutGroupDevices)
25
+ const allData = await createActivityReportByGroup(from, to, userData, traccarInstance)
26
+ reportData.push(...allData)
35
27
  } else {
36
- const allData = await createActivityReportByDevice(from, to)
28
+ const allData = await createActivityReportByDevice(from, to, userData, traccarInstance)
37
29
  reportData.push(allData)
38
30
  }
39
31
 
40
32
  return reportData
41
33
  }
42
34
 
43
- async function createActivityReportByGroup(from, to){
35
+ async function createActivityReportByGroup(from, to, userData, traccarInstance){
44
36
  console.log("ByGroup")
45
37
  const reportData = []
46
38
  for (const g of userData.groups) {
@@ -56,26 +48,30 @@ async function createActivityReportByGroup(from, to){
56
48
  }
57
49
 
58
50
  const response = await traccarInstance.reports.reportsSummaryGet(from, to, null, [g.id])
59
- const data = response.data
51
+ const summaries = response.data
60
52
 
61
53
  const responseTrips = await traccarInstance.reports.reportsTripsGet(from, to, null, [g.id])
62
54
  const trips = responseTrips.data
63
55
 
64
56
  devices.sort((a, b) => (a.name > b.name) ? 1 : -1)
65
57
 
66
- if (data.length > 0) {
58
+ if (summaries.length > 0) {
67
59
 
68
- console.log('Summary:' + data.length)
69
- groupData.devices = processDevices(devices, data, trips)
60
+ console.log('Summary:' + summaries.length)
61
+ groupData.devices = processDevices(from, to, devices, {summaries: summaries, trips: trips})
70
62
 
71
63
  reportData.push(groupData)
72
64
  }
73
65
  }
74
66
  }
67
+
68
+ const withoutGroupDevices = await createActivityReportByDevice(from, to)
69
+ reportData.push(withoutGroupDevices)
70
+
75
71
  return reportData
76
72
  }
77
73
 
78
- async function createActivityReportByDevice(from, to){
74
+ async function createActivityReportByDevice(from, to, userData, traccarInstance){
79
75
  const groupIds = userData.groups.map(g => g.id)
80
76
  const devicesToProcess = userData.byGroup ? userData.devices.filter(d => !groupIds.includes(d.groupId)) : userData.devices
81
77
 
@@ -89,84 +85,51 @@ async function createActivityReportByDevice(from, to){
89
85
  //Get report data from traccar
90
86
  devicesToProcess.sort((a, b) => (a.name > b.name) ? 1 : -1)
91
87
 
92
- // use the km report to calculate kms
93
- const kmsReport = await createKmsReport(from, to, userData, traccarInstance)
88
+ let summaries = []
89
+ let routeData = []
90
+ const tripsData = await traccar.getTrips(traccarInstance, from, to, devicesToProcess)
94
91
 
95
- let data = []
96
92
  if(userData.groupByDay) {
93
+ routeData = userData.allWeek ? [] : await traccar.getRoute(traccarInstance, from, to, devicesToProcess)
94
+ console.log('trips:' + tripsData.length)
95
+
96
+ if (tripsData.length > 0) {
97
+ trips.checkTripsKms(traccarInstance, from, to, devicesToProcess, {trips: tripsData, route: routeData})
98
+ }
99
+
97
100
  const dates = getDates(from, to)
98
101
  for(const date of dates){
99
- if(userData.allWeek || !userData.weekDays){
102
+ if(userData.allWeek || !userData.weekDays || !userData.dayHours){
100
103
  const fromByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0)
101
104
  const toByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
102
105
 
103
106
  const summary = await traccar.getSummary(traccarInstance, fromByDay, toByDay, devicesToProcess)
104
107
  summary.forEach(s => s.date = date)
105
- data = data.concat(summary)
106
- } else {
107
- if((date.getDay() === 0 && userData.weekDays.sunday) ||
108
- (date.getDay() === 1 && userData.weekDays.monday) ||
109
- (date.getDay() === 2 && userData.weekDays.tuesday) ||
110
- (date.getDay() === 3 && userData.weekDays.wednesday) ||
111
- (date.getDay() === 4 && userData.weekDays.thursday) ||
112
- (date.getDay() === 5 && userData.weekDays.friday) ||
113
- (date.getDay() === 6 && userData.weekDays.saturday)) {
114
-
115
- const fromByDay = new Date(new Date(date).toISOString().split('T')[0] + ' ' + userData.dayHours.startTime)
116
- const toByDay = new Date(new Date(date).toISOString().split('T')[0] + ' ' + userData.dayHours.endTime)
117
-
118
- if(fromByDay.getTime() < toByDay.getTime()) {
119
- const summary = await traccar.getSummary(traccarInstance, new Date(fromByDay.toUTCString()), new Date(toByDay.toUTCString()), devicesToProcess)
120
- summary.forEach(s => s.date = date)
121
- data = data.concat(summary)
122
- } else {
123
- const dayStart = new Date(new Date(date).toISOString().split('T')[0] + ' 00:00:00')
124
- const dayEnd = new Date(new Date(date).toISOString().split('T')[0] + ' 23:59:59')
125
-
126
- const summaryStart = await traccar.getSummary(traccarInstance, new Date(dayStart.toUTCString()), new Date(toByDay.toUTCString()), devicesToProcess)
127
- const summaryEnd = await traccar.getSummary(traccarInstance, new Date(fromByDay.toUTCString()), new Date(dayEnd.toUTCString()), devicesToProcess)
128
-
129
- const summary = []
130
- summaryStart.forEach(s => {
131
- const sEnd = summaryEnd.find(a => s.deviceId === a.deviceId)
132
- summary.push({
133
- date: date,
134
- deviceId: s.deviceId,
135
- averageSpeed: (s.averageSpeed + sEnd.averageSpeed) / 2,
136
- distance: s.distance + sEnd.distance,
137
- engineHours: s.engineHours + sEnd.engineHours,
138
- maxSpeed: s.maxSpeed > sEnd.maxSpeed ? s.maxSpeed : sEnd.maxSpeed,
139
- endOdometer: 0,
140
- startOdometer: 0
141
- })
142
- })
143
- data = data.concat(summary)
144
- }
145
- }else {
146
- data = data.concat({date: date})
147
- }
108
+ summaries = summaries.concat(summary)
148
109
  }
149
110
  }
150
111
  } else {
151
- data = await traccar.getSummary(traccarInstance, from, to, devicesToProcess)
112
+ summaries = await traccar.getSummary(traccarInstance, from, to, devicesToProcess)
152
113
  }
153
114
 
154
- console.log('Summary:' + data.length)
115
+ console.log('Summary:' + summaries.length)
155
116
 
156
117
  //Process report data
157
- if (data.length > 0) {
158
- allData.devices = processDevices(devicesToProcess, data, kmsReport)
118
+ if (summaries.length || tripsData.length) {
119
+ allData.devices = processDevices(from, to, devicesToProcess, {summaries: summaries, trips: tripsData, route: routeData})
159
120
  }
160
121
 
161
122
  return allData
162
123
  }
163
124
 
164
- async function createActivityReportByDriver(from, to){
125
+ async function createActivityReportByDriver(from, to, userData, traccarInstance){
165
126
  const devices = await drivers.devicesByDriver(traccarInstance, from, to, userData.drivers, userData.devices)
166
127
 
167
128
  let tripsData = []
129
+ let routeData = []
168
130
  if(devices.length > 0) {
169
131
  tripsData = await traccar.getTrips(traccarInstance, from, to, devices)
132
+ routeData = await traccar.getRoute(traccarInstance, from, to, devices)
170
133
  }
171
134
 
172
135
  const allData = {
@@ -175,28 +138,74 @@ async function createActivityReportByDriver(from, to){
175
138
  to: to
176
139
  }
177
140
 
178
- allData.drivers = processDrivers(from, to, userData.drivers, tripsData)
141
+ allData.drivers = processDrivers(from, to, userData.drivers, {trips: tripsData, route: routeData})
179
142
 
180
143
  return allData
181
144
  }
182
145
 
183
- function processDevices(devices, data, kmsReport) {
146
+
147
+ function processDevices(from, to, devices, data) {
184
148
  const devicesResult = []
185
149
 
186
150
  devices.forEach(d => {
187
- const summary = data.filter(s => s.deviceId === d.id)
188
- if (summary) {
189
- summary.forEach(s => {
190
- const deviceKms = kmsReport[0].devices.filter(r => r.device.id === d.id)
191
- s.convertedSpentFuel = automaticReports.calculateSpentFuel(s.spentFuel, d)
192
- s.distance = deviceKms.length ? (userData.groupByDay ? deviceKms[0].days.find(d => d.date.getTime() === s.date.getTime()).kms : deviceKms[0].summary.distance) : 0
193
- })
194
- const deviceData = {
195
- device: d,
196
- summary: summary,
151
+ const summary = []
152
+ if(userData.groupByDay) {
153
+ const route = data.route.filter(t => t.deviceId === d.id)
154
+ const deviceTrips = data.trips.filter(t => t.deviceId === d.id
155
+ && (userData.allWeek || !userData.weekDays || isInsideTimetable(t, userData) || isPartialInsideTimetable(t, userData, route)))
156
+
157
+ const dates = getDates(from, to)
158
+ for(const date of dates){
159
+ const fromByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0)
160
+ const toByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
161
+
162
+ const tripsByDay = deviceTrips.filter(t => (new Date(t.startTime) > fromByDay && new Date(t.endTime) < toByDay))
163
+ const distance = tripsByDay.reduce((a, b) => a + b.distance, 0)
164
+
165
+ if(!userData.allWeek && userData.weekDays && userData.dayHours) {
166
+ summary.push({
167
+ date: date,
168
+ deviceId: d.id,
169
+ averageSpeed: distance > 0 ? ((tripsByDay.reduce((a, b) => a + (b.averageSpeed * b.distance), 0)) / distance) : 0,
170
+ distance: distance,
171
+ engineHours: tripsByDay.reduce((a, b) => a + b.duration, 0),
172
+ maxSpeed: tripsByDay.reduce((a, b) => {
173
+ return a > b.maxSpeed ? a : b.maxSpeed
174
+ }, 0),
175
+ endOdometer: 0,
176
+ startOdometer: 0
177
+ })
178
+ } else {
179
+ const summaryCurrentDay = data.summaries.filter(s => {
180
+ console.log(s.date.getTime(), date.getTime(), s.date.getTime() === date.getTime())
181
+ return s.deviceId === d.id && s.date.getTime() === date.getTime()})
182
+
183
+ if (summaryCurrentDay.length) {
184
+ summaryCurrentDay.forEach(s => {
185
+ s.distance = distance
186
+ s.convertedSpentFuel = automaticReports.calculateSpentFuel(s.spentFuel, d)
187
+ })
188
+
189
+ summary.push(...summaryCurrentDay)
190
+ }
191
+ }
192
+ }
193
+ } else {
194
+ summary.push(...data.summaries.filter(s => s.deviceId === d.id))
195
+
196
+ if (summary.length) {
197
+ summary.forEach(s => {
198
+ s.distance = data.trips.filter(t => t.deviceId === d.id).reduce((a, b) => a + b.distance, 0)
199
+ s.convertedSpentFuel = automaticReports.calculateSpentFuel(s.spentFuel, d)
200
+ })
197
201
  }
198
- devicesResult.push(deviceData)
199
202
  }
203
+
204
+ const deviceData = {
205
+ device: d,
206
+ summary: summary,
207
+ }
208
+ devicesResult.push(deviceData)
200
209
  })
201
210
 
202
211
  return devicesResult
@@ -206,7 +215,8 @@ function processDrivers(from, to, drivers, data) {
206
215
  console.log(data)
207
216
  const driversResult = []
208
217
  drivers.forEach(d => {
209
- const trips = data.filter(t => t.driverUniqueId === d.uniqueId)
218
+ const route = data.route.filter(p => p.attributes.driverUniqueId === d.uniqueId)
219
+ const trips = data.trips.filter(t => t.driverUniqueId === d.uniqueId)
210
220
  if (trips.length > 0) {
211
221
  const driverData = {
212
222
  driver: d,
@@ -219,7 +229,7 @@ function processDrivers(from, to, drivers, data) {
219
229
  const toByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
220
230
 
221
231
  const tripsByDay = trips.filter(t => (new Date(t.startTime) > fromByDay && new Date(t.endTime) < toByDay)
222
- && (userData.allWeek || !userData.weekDays || isInsideTimetable(t, userData)))
232
+ && (userData.allWeek || !userData.weekDays || isInsideTimetable(t, userData) || isPartialInsideTimetable(t, userData, route)))
223
233
 
224
234
  driverData.summary.push({
225
235
  date: date,
@@ -267,34 +277,6 @@ async function exportActivityReportToPDF(userData, reportData) {
267
277
  }
268
278
  }
269
279
 
270
- function exportActivityReportToWord(userData, reportData) {
271
- const doc = new Document({
272
- sections: [{
273
- properties: {},
274
- children: [
275
- new Paragraph({
276
- children: [
277
- new TextRun("Hello World"),
278
- new TextRun({
279
- text: "Foo Bar",
280
- bold: true,
281
- }),
282
- new TextRun({
283
- text: "\tGithub is the best",
284
- bold: true,
285
- }),
286
- ],
287
- }),
288
- ],
289
- }],
290
- })
291
- Packer.toBlob(doc).then(blob => {
292
- console.log(blob);
293
- saveAs(blob, "example.docx");
294
- console.log("Document created successfully");
295
- })
296
- }
297
-
298
280
  function exportActivityReportToPDF_Driver(doc, translations, reportData) {
299
281
  const headers = [translations.report.driver,
300
282
  translations.report.distance,
@@ -9,10 +9,7 @@ const {convertToLocaleString} = require("./util/utils");
9
9
 
10
10
  const fileName = 'EventReport'
11
11
 
12
- let traccar
13
-
14
- async function createEventsReport(from, to, userData, traccarInstance) {
15
- traccar = traccarInstance
12
+ async function createEventsReport(from, to, userData, traccar) {
16
13
  console.log('Create EventsReport')
17
14
  const reportData = []
18
15
 
@@ -45,7 +42,7 @@ async function createEventsReport(from, to, userData, traccarInstance) {
45
42
 
46
43
  withoutGroupDevices.sort((a, b) => (a.name > b.name) ? 1 : -1)
47
44
 
48
- const data = await getReportData(from, to, withoutGroupDevices, userData.eventTypes)
45
+ const data = await getReportData(from, to, withoutGroupDevices, userData.eventTypes, traccar)
49
46
 
50
47
  if(data.length > 0) {
51
48
  reportData.push({
@@ -57,7 +54,7 @@ async function createEventsReport(from, to, userData, traccarInstance) {
57
54
  return reportData
58
55
  }
59
56
 
60
- async function getReportData(from, to, devices, types) {
57
+ async function getReportData(from, to, devices, types, traccar) {
61
58
  let data = []
62
59
  const arrayOfArrays = automaticReports.sliceArray(devices)
63
60
  const traccarTypes = new Set(types.map(t => t.startsWith('alarm') ? 'alarm' : t))
@@ -1,10 +1,7 @@
1
1
  const automaticReports = require("./automaticReports");
2
2
  const refuelingReport = require("./refueling-report");
3
3
 
4
- let traccar
5
-
6
- async function createFuelConsumptionReport(from, to, userData, traccarInstance) {
7
- traccar = traccarInstance
4
+ async function createFuelConsumptionReport(from, to, userData, traccar) {
8
5
  console.log('Create FuelConsumption Report')
9
6
 
10
7
  const reportData = []
@@ -60,12 +57,10 @@ async function createFuelConsumptionReport(from, to, userData, traccarInstance)
60
57
  const dayTrips = groupedTrips.get(key)
61
58
  const dayRefueling = groupedRefuelings.get(key)
62
59
  const distance = dayTrips.reduce((a, b) => a + b.distance, 0)
63
- let spentFuel = 0
64
- if(d.attributes.xpert) {
65
- spentFuel = automaticReports.calculateXpertSpentFuel(key, positions)
66
- } else {
67
- spentFuel = automaticReports.calculateSpentFuel(dayTrips.reduce((a, b) => a + b.spentFuel, 0), d)
68
- }
60
+ let spentFuel = d.attributes.xpert ?
61
+ automaticReports.calculateXpertSpentFuel(key, positions)
62
+ :
63
+ automaticReports.calculateSpentFuel(dayTrips.reduce((a, b) => a + b.spentFuel, 0), d)
69
64
 
70
65
  const day = {
71
66
  date: key,
package/src/index.js CHANGED
@@ -40,9 +40,6 @@ function Reports(config, axios) {
40
40
  this.tripReportToExcel = (userData, reportData) => {
41
41
  return require('./trip-report').exportTripReportToExcel(userData, reportData)
42
42
  }
43
- this.tripReportToWord = (userData, reportData) => {
44
- return require('./trip-report').exportTripReportToWord(userData, reportData)
45
- }
46
43
 
47
44
  this.zoneReport = (from, to, userData) => {
48
45
  return require('./zone-report').createZoneReport(from, to, userData, this.traccar)
@@ -112,9 +109,7 @@ function Reports(config, axios) {
112
109
  return require('./kms-report').exportKmsReportToPDF(userData, reportData)
113
110
  }
114
111
 
115
- this.kmsReportToWord = (userData, reportData) => {
116
- return require('./kms-report').exportKmsReportToWord(userData, reportData)
117
- }
112
+ this.reportToWord = require('./word').reportToWord
118
113
 
119
114
  this.kmsReportToExcel = (userData, reportData) => {
120
115
  return require('./kms-report').exportKmsReportToExcel(userData, reportData)
package/src/kms-report.js CHANGED
@@ -133,8 +133,7 @@ function processDrivers(from, to, drivers, data) {
133
133
  const fromByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0)
134
134
  const toByDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
135
135
 
136
- const tripsByDay = trips.filter(t => (new Date(t.startTime) > fromByDay && new Date(t.endTime) < toByDay)
137
- && (userData.allWeek || !userData.weekDays || isInsideTimetable(t, userData)))
136
+ const tripsByDay = trips.filter(t => (new Date(t.startTime) > fromByDay && new Date(t.endTime) < toByDay))
138
137
 
139
138
  driverData.days.push({
140
139
  date: date,
@@ -10,38 +10,33 @@ const drivers = require("./util/driver")
10
10
  const {distance, point} = require('turf')
11
11
  const here = require('./here')
12
12
  const {getUserPartner} = require("fleetmap-partners");
13
- const traccar = require("./util/traccar");
14
-
15
- let traccarInstance
16
- let userData
13
+ const traccarHelper = require("./util/traccar");
17
14
 
18
15
  const fileName = 'SpeedingReport'
19
16
  const eventTypes = ['deviceOverspeed']
20
17
 
21
- async function createSpeedingReport(from, to, reportUserData, traccar) {
22
- traccarInstance = traccar
23
- userData = reportUserData
18
+ async function createSpeedingReport(from, to, userData, traccarInstance) {
24
19
  const reportData = []
25
20
 
26
21
  if (userData.byDriver) {
27
22
  console.log("ByDriver")
28
- const allData = await createSpeedingReportByDriver(from, to)
23
+ const allData = await createSpeedingReportByDriver(from, to, userData, traccarInstance)
29
24
  reportData.push(allData)
30
25
  }
31
26
  else if (userData.byGroup) {
32
27
  console.log("ByGroup")
33
- const allData = await createSpeedingReportByGroup(from, to)
28
+ const allData = await createSpeedingReportByGroup(from, to, userData, traccarInstance)
34
29
  reportData.push(...allData)
35
30
  } else {
36
31
  console.log("createSpeedingReportByDevice")
37
- const allData = await createSpeedingReportByDevice(from, to, userData.devices)
32
+ const allData = await createSpeedingReportByDevice(from, to, userData.devices, userData, traccarInstance)
38
33
  reportData.push(allData)
39
34
  }
40
35
 
41
36
  return reportData
42
37
  }
43
38
 
44
- async function createSpeedingReportByGroup(from, to){
39
+ async function createSpeedingReportByGroup(from, to, userData, traccarInstance){
45
40
  const reportData = []
46
41
  for (const g of userData.groups) {
47
42
  const devices = userData.devices.filter(d => d.groupId === g.id)
@@ -53,8 +48,8 @@ async function createSpeedingReportByGroup(from, to){
53
48
  xpert: devices.filter(d => d.attributes.xpert).length > 0
54
49
  }
55
50
 
56
- const events = await traccar.getEvents(traccarInstance, from, to, devices, eventTypes)
57
- const routes = await traccar.getRoute(traccarInstance, from, to, devices)
51
+ const events = await traccarHelper.getEvents(traccarInstance, from, to, devices, eventTypes)
52
+ const routes = await traccarHelper.getRoute(traccarInstance, from, to, devices)
58
53
 
59
54
  devices.sort((a, b) => (a.name > b.name) ? 1 : -1)
60
55
 
@@ -74,15 +69,15 @@ async function createSpeedingReportByGroup(from, to){
74
69
  return reportData
75
70
  }
76
71
 
77
- async function createSpeedingReportByDevice(from, to, devices) {
72
+ async function createSpeedingReportByDevice(from, to, devices, userData, traccarInstance) {
78
73
  devices.sort((a, b) => (a.name > b.name) ? 1 : -1)
79
74
 
80
- const routes = await traccar.getRoute(traccarInstance, from, to, devices)
75
+ const routes = await traccarHelper.getRoute(traccarInstance, from, to, devices)
81
76
  const events = []
82
77
  if(!userData.useVehicleSpeedLimit && userData.customSpeed){
83
78
  events.push(...await getCustomSpeedLimitEvents(devices, routes))
84
79
  } else {
85
- events.push(...await traccar.getEvents(traccarInstance, from, to, devices, eventTypes))
80
+ events.push(...await traccarHelper.getEvents(traccarInstance, from, to, devices, eventTypes))
86
81
  }
87
82
 
88
83
  if(userData.roadSpeedLimits){
@@ -109,12 +104,12 @@ async function createSpeedingReportByDriver(from, to) {
109
104
  return { drivers: [] }
110
105
  }
111
106
 
112
- const routes = await traccar.getRoute(traccarInstance, from, to, devices)
107
+ const routes = await traccarHelper.getRoute(traccarInstance, from, to, devices)
113
108
  const events = []
114
109
  if(!userData.useVehicleSpeedLimit && userData.customSpeed){
115
110
  events.push(...await getCustomSpeedLimitEvents(devices, routes))
116
111
  } else {
117
- events.push(...await traccar.getEvents(traccarInstance, from, to, devices, eventTypes))
112
+ events.push(...await traccarHelper.getEvents(traccarInstance, from, to, devices, eventTypes))
118
113
  }
119
114
 
120
115
  if(userData.roadSpeedLimits){
@@ -10,7 +10,6 @@ const {getStyle} = require("./reportStyle")
10
10
  const traccar = require("./util/traccar")
11
11
  const trips = require("./util/trips");
12
12
  const {isInsideTimetable, addNearestPOIs, isPartialInsideTimetable} = require("./util/trips")
13
- const word = require('./word')
14
13
 
15
14
 
16
15
  let traccarInstance
@@ -449,4 +448,3 @@ function getStop(tripEndDate, stops){
449
448
  exports.createTripReport = createTripReport
450
449
  exports.exportTripReportToPDF = exportTripReportToPDF
451
450
  exports.exportTripReportToExcel = exportTripReportToExcel
452
- exports.exportTripReportToWord = word.exportTripReportToWord
package/src/util/utils.js CHANGED
@@ -1,5 +1,12 @@
1
1
  const axios = require('axios')
2
2
  const turf = require('turf')
3
+ const {getUserPartner} = require("fleetmap-partners")
4
+ const messages = require("../../lang")
5
+
6
+ exports.getTranslations = (userData) => {
7
+ const lang = userData.user.attributes.lang || (navigator && navigator.language)
8
+ return messages[lang] ? messages[lang] : messages['en-GB']
9
+ }
3
10
 
4
11
  function convertMS(duration, withSeconds) {
5
12
 
@@ -31,7 +38,7 @@ function coordsDistance(lon1, lat1, lon2, lat2) {
31
38
 
32
39
  function getDates(startDate, endDate) {
33
40
  const dates = []
34
- let currentDate = new Date(startDate.toISOString().split('T')[0] + ' 12:00 PM')
41
+ let currentDate = new Date(startDate.toISOString().split('T')[0] + ' 12:00:00.000 PM')
35
42
  const addDays = function (days) {
36
43
  const date = new Date(this.valueOf())
37
44
  date.setDate(date.getDate() + days)
@@ -44,19 +51,34 @@ function getDates(startDate, endDate) {
44
51
  return dates
45
52
  }
46
53
 
54
+ function getImage(url) {
55
+ return axios.get(url, {responseType: 'arraybuffer'}).then(d => d.data)
56
+ }
57
+
58
+ async function getImageBase64(url) {
59
+ const response = await getImage(url);
60
+ return Buffer.from(response, 'binary').toString('base64')
61
+ }
62
+
63
+ function getLogoUrl(hostname) {
64
+ const path = `/img/logos/${hostname}.png`
65
+ return window ? path : `https://${hostname}${path}`
66
+ }
67
+
47
68
  async function getImgFromUrl(hostname) {
69
+ const url = getLogoUrl(hostname)
48
70
  try {
49
71
  const img = new Image()
50
- img.src = '/img/logos/' + hostname + '.png'
72
+ img.src = url
51
73
  return img
52
74
  } catch (e) {
53
- const response = await axios.get('https://' + hostname + '/img/logos/' + hostname + '.png', { responseType: 'arraybuffer' })
54
- return Buffer.from(response.data, 'binary').toString('base64')
75
+ return await getImageBase64(url);
55
76
  }
56
77
  }
57
78
 
58
79
  function isClientSide() { return (typeof window !== "undefined") }
59
80
 
81
+
60
82
  function convertToLocaleString(value, lang, timezone){
61
83
  if(isClientSide()){
62
84
  return new Date(value).toLocaleString()
@@ -97,4 +119,8 @@ exports.getDates = getDates
97
119
  exports.convertToLocaleString = convertToLocaleString
98
120
  exports.convertToLocaleDateString = convertToLocaleDateString
99
121
  exports.convertToLocaleTimeString = convertToLocaleTimeString
100
-
122
+ exports.isClientSide = isClientSide
123
+ exports.getLogo = (user) => {
124
+ const host = window ? window.location.hostname : getUserPartner(user).host
125
+ return getImage(getLogoUrl(host))
126
+ }
package/src/word/index.js CHANGED
@@ -1,27 +1,81 @@
1
- const {Document, Paragraph, Packer, TableRow, TableCell, Table} = require("docx")
1
+ const {Document, Paragraph, Packer, TableRow, TableCell, Table, WidthType, ImageRun, Header, TextRun, HeadingLevel,
2
+ AlignmentType
3
+ } = require("docx")
2
4
  const { saveAs } = require('file-saver')
3
- const kmsReport = require('../kms-report')
5
+ const utils = require('../util/utils')
6
+ const {getPartnerData} = require("fleetmap-partners");
7
+ const colWidth = 3505
4
8
 
5
- exports.exportKmsReportToWord = (userData, reportData) => {
6
- const excel = kmsReport.exportKmsReportToExcel(userData, reportData)
9
+ function formatCellValue(value) {
10
+ return value.toLocaleDateString ? value.toLocaleDateString() : value + ''
11
+ }
12
+
13
+ exports.reportToWord = async (userData, dateRange, excel, title) => {
14
+ console.log('excel', excel)
15
+ const partnerData = getPartnerData(userData.user)
16
+
17
+ if (!excel.data.length && utils.isClientSide()) {
18
+ alert('Não há dados')
19
+ return
20
+ }
21
+ const logo = await utils.getLogo(userData.user)
22
+ console.log('logo', logo)
7
23
  const table = new Table({
8
- rows: excel.data.map(r => new TableRow({
9
- children: r.map(c =>
10
- new TableCell({
11
- children: [new Paragraph(c)]
12
- }))
13
- }))
24
+ columnWidths: excel.headers.map(() => colWidth),
25
+ rows: [
26
+ new TableRow({
27
+ children: excel.headers.map(r => new TableCell({
28
+ children: [new Paragraph(r.label)],
29
+ width: {
30
+ size: colWidth,
31
+ type: WidthType.DXA,
32
+ }
33
+ }))}),
34
+ ...excel.data.filter(r=>Object.keys(r).length).map(r => new TableRow({
35
+ children: Object.keys(r).map(k =>
36
+ new TableCell({
37
+ children: [new Paragraph(formatCellValue(r[k]))],
38
+ width: {
39
+ size: colWidth,
40
+ type: WidthType.DXA,
41
+ }
42
+ }))})),
43
+ ]
14
44
  })
15
-
16
45
  const doc = new Document({
17
46
  sections: [{
47
+ headers: {
48
+ default: new Header({
49
+ children: [
50
+ new Paragraph({
51
+ children: [
52
+ new ImageRun({
53
+ data: logo,
54
+ transformation: {
55
+ width: (partnerData.reports && partnerData.reports.logoWidth*2) || 200,
56
+ height: (partnerData.reports && partnerData.reports.logoHeight*2) || 50
57
+ }
58
+ })
59
+ ]
60
+ })
61
+ ]
62
+ })
63
+ },
18
64
  properties: {},
19
65
  children: [
66
+ new Paragraph({
67
+ children: [new TextRun(title)],
68
+ heading: HeadingLevel.HEADING_1,
69
+ alignment: AlignmentType.CENTER,
70
+ }),
71
+ new Paragraph({}),
72
+ new Paragraph(new Date(dateRange[0]).toLocaleString() + ' - ' + new Date(dateRange[1]).toLocaleString()),
73
+ new Paragraph({}),
20
74
  table
21
75
  ],
22
76
  }],
23
77
  })
24
78
  Packer.toBlob(doc).then(blob => {
25
- saveAs(blob, "trip.docx");
79
+ saveAs(blob, "report.docx");
26
80
  })
27
81
  }