fleetmap-reports 2.0.315 → 2.0.317

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetmap-reports",
3
- "version": "2.0.315",
3
+ "version": "2.0.317",
4
4
  "description": "",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -1,7 +1,11 @@
1
1
  const traccarHelper = require('../util/traccar')
2
2
  const { isInsideTimetable } = require('../util/trips')
3
- const { convertFromUTCDate } = require('../util/utils')
3
+ const { convertFromUTCDate, getTranslations, convertMS, convertToLocaleTimeString, isClientSide } = require('../util/utils')
4
4
  const automaticReports = require('../automaticReports')
5
+ const jsPDF = require('jspdf')
6
+ const { getStyle } = require('../reportStyle')
7
+ const { getUserPartner } = require('fleetmap-partners')
8
+ const { addTable, headerFromUser } = require('../util/pdfDocument')
5
9
 
6
10
  async function createDailyUseReport (from, to, userData, traccar) {
7
11
  const reportData = []
@@ -77,4 +81,72 @@ function processDeviceData (allInOne, d, userData) {
77
81
  }
78
82
  }
79
83
 
84
+ async function exportDailyUseReportToPDF (userData, reportData) {
85
+ const translations = getTranslations(userData)
86
+ const timezone = userData.user.attributes.timezone
87
+ const lang = userData.user.attributes.lang || (isClientSide() && navigator.language)
88
+
89
+ const headers = [
90
+ translations.report.vehicle,
91
+ 'Immatriculation',
92
+ 'Groupe',
93
+ 'Matin départ',
94
+ 'Matin arrêt',
95
+ 'Matin temps',
96
+ 'Déjeuner',
97
+ 'Après-midi départ',
98
+ 'Après-midi arrêt',
99
+ 'Après-midi temps',
100
+ 'Total temps',
101
+ 'Total conduit',
102
+ 'Total arrêts',
103
+ 'Total kms'
104
+ ]
105
+
106
+ const data = []
107
+ reportData.forEach(d => {
108
+ const row = [
109
+ d.device,
110
+ d.licensePlate,
111
+ d.group,
112
+ convertToLocaleTimeString(d.morningStart, lang, timezone, userData.user),
113
+ convertToLocaleTimeString(d.morningEnd, lang, timezone, userData.user),
114
+ convertMS(d.morningTime),
115
+ convertMS(d.lunch),
116
+ convertToLocaleTimeString(d.afternoonStart, lang, timezone, userData.user),
117
+ convertToLocaleTimeString(d.afternoonEnd, lang, timezone, userData.user),
118
+ convertMS(d.afternoonTime),
119
+ convertMS(d.totalTime),
120
+ convertMS(d.totalDrivingTime),
121
+ d.totalStops,
122
+ (d.totalDistance / 100).toFixed(1)
123
+ ]
124
+ data.push(row)
125
+ })
126
+
127
+ const doc = new jsPDF.jsPDF('l')
128
+ await headerFromUser(doc, 'Rapport de Performance', userData.user)
129
+ const style = getStyle(getUserPartner(userData.user))
130
+
131
+ const footValues = []
132
+
133
+ doc.setFontSize(11)
134
+ doc.text(new Date(userData.from).toLocaleString() + ' - ' + new Date(userData.to).toLocaleString(), 20, 33)
135
+
136
+ style.headerFontSize = 8
137
+ style.bodyFontSize = 7
138
+ const columnStyles = {}
139
+ for (let i = 3; i < 14; i++) {
140
+ columnStyles[i] = { halign: 'right' }
141
+ }
142
+ addTable(doc, headers, data, footValues, style, 40, columnStyles)
143
+ return doc
144
+ }
145
+
146
+ function exportDailyUseReportToExcel (userData, reportData) {
147
+
148
+ }
149
+
80
150
  exports.createDailyUseReport = createDailyUseReport
151
+ exports.exportDailyUseReportToPDF = exportDailyUseReportToPDF
152
+ exports.exportDailyUseReportToExcel = exportDailyUseReportToExcel
@@ -0,0 +1,46 @@
1
+ async function createPassengerReport (from, to, userData, traccar) {
2
+ //const allDevices = await traccar.axios.get('/devices').then(d => d.data)
3
+ const devices = userData.devices
4
+ const drivers = await traccar.axios.get('/drivers').then(d => d.data)
5
+ const groups = await traccar.axios.get('/groups').then(d => d.data)
6
+ await Promise.all(groups.map(async g => {
7
+ const driversByGroup = await traccar.axios.get(`/drivers?groupId=${g.id}`).then(d => d.data)
8
+ driversByGroup.forEach(d => {
9
+ const _driver = drivers.find(a => a.id === d.id)
10
+ if (_driver) {
11
+ _driver.groupName = g.name
12
+ }
13
+ })
14
+ }))
15
+ const eventsUrl = `/reports/events?${devices.map(d => 'deviceId=' + d.id).join('&')
16
+ }&from=${from.toISOString()
17
+ }&to=${to.toISOString()
18
+ }`
19
+ const positionsUrl = `/reports/route?${devices.map(d => 'deviceId=' + d.id).join('&')
20
+ }&from=${from.toISOString()
21
+ }&to=${to.toISOString()
22
+ }`
23
+ const events = await traccar.axios.get(eventsUrl).then(d => d.data)
24
+ const positions = await traccar.axios.get(positionsUrl).then(d => d.data)
25
+ events.forEach(e => {
26
+ delete e.attributes
27
+ const driver = getDriver(e, positions, drivers)
28
+ const position = positions.find(p => p.id === e.positionId)
29
+ e.deviceName = devices.find(d => d.id === e.deviceId).name
30
+ e.groupName = driver.groupName || ''
31
+ e.fixtime = position && new Date(position.fixTime)
32
+ e.notes = driver && driver.attributes.notes
33
+ e.driverName = (driver && driver.name) || (position && position.attributes.driverUniqueId)
34
+ })
35
+ return events
36
+ }
37
+
38
+ function getDriver (event, positions, drivers) {
39
+ const p = positions.find(p => p.id === event.positionId)
40
+ if (!p) { return '' }
41
+ const d = drivers.find(d => d.uniqueId === p.attributes.driverUniqueId)
42
+ if (!d) { return '' }
43
+ return d
44
+ }
45
+
46
+ exports.createPassengerReport = createPassengerReport
@@ -10,60 +10,13 @@ const { headerFromUser, addTable } = require('./util/pdfDocument')
10
10
  const { getStyle } = require('./reportStyle')
11
11
  const { getUserPartner } = require('fleetmap-partners')
12
12
 
13
- function minimumDuration (status, userData) {
14
- if (status) {
15
- return (userData.minimumMinutesOn * 60 * 1000)
16
- }
17
-
18
- return (userData.minimumMinutesOff * 60 * 1000)
19
- }
20
-
21
- function addSensorPeriod (statusPeriodBySensor, s, currentStatus, d, duration, currentPosition, previousPosition) {
22
- statusPeriodBySensor[s.sensor].push({
23
- startTime: currentStatus[s.sensor].startTime,
24
- endTime: previousPosition.fixTime,
25
- endAddress: previousPosition.address,
26
- value: currentStatus[s.sensor].value,
27
- valueDescription: currentStatus[s.sensor].value ? d.attributes[s.sensor + 'on'] : d.attributes[s.sensor + 'off'],
28
- name: s.name,
29
- duration
30
- })
31
- currentStatus[s.sensor] = { value: currentPosition.attributes[s.id], startTime: currentPosition.fixTime }
32
- }
33
-
34
13
  function processDevices (from, to, devices, data, userData) {
35
14
  const result = []
36
15
 
37
16
  for (const d of devices) {
38
17
  const positions = data.route.filter(t => t.deviceId === d.id)
39
18
 
40
- const statusPeriodBySensor = {}
41
- const currentStatus = {}
42
- positions.forEach((p, index) => {
43
- userData.sensors.forEach(s => {
44
- if (!statusPeriodBySensor[s.sensor]) {
45
- statusPeriodBySensor[s.sensor] = []
46
- }
47
- if (currentStatus[s.sensor] !== undefined) {
48
- if (currentStatus[s.sensor].value !== p.attributes[s.id]) {
49
- const duration = new Date(positions[index - 1].fixTime).getTime() - new Date(currentStatus[s.sensor].startTime).getTime()
50
- if ((duration >= minimumDuration(currentStatus[s.sensor].value, userData)) || statusPeriodBySensor[s.sensor].length === 0) {
51
- addSensorPeriod(statusPeriodBySensor, s, currentStatus, d, duration, p, positions[index - 1])
52
- } else {
53
- const element = statusPeriodBySensor[s.sensor].pop()
54
- currentStatus[s.sensor] = { value: p.attributes[s.id], startTime: element.startTime }
55
- }
56
- } else {
57
- const distanceBetweenPositions = new Date(p.fixTime).getTime() - new Date(positions[index - 1].fixTime).getTime()
58
- if (distanceBetweenPositions > 30 * 60 * 1000 && currentStatus[s.sensor].value === true) {
59
- currentStatus[s.sensor] = { value: p.attributes[s.id], startTime: p.fixTime }
60
- }
61
- }
62
- } else {
63
- currentStatus[s.sensor] = { value: p.attributes[s.id], startTime: p.fixTime }
64
- }
65
- })
66
- })
19
+ const statusPeriodBySensor = computeSensorPeriods(positions, userData.sensors, d, userData)
67
20
 
68
21
  const rows = Object.values(statusPeriodBySensor).flat()
69
22
  rows.sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime())
@@ -92,6 +45,129 @@ function processDevices (from, to, devices, data, userData) {
92
45
  return result
93
46
  }
94
47
 
48
+ function computeSensorPeriods (positions, sensors, d, userData) {
49
+ if (!positions || positions.length === 0) return {}
50
+
51
+ const result = {}
52
+ const minOn = (userData.minimumMinutesOn || 0) * 60 * 1000
53
+ const minOff = (userData.minimumMinutesOff || 0) * 60 * 1000
54
+ const maxDistanceBetweenPositions = 20 * 60 * 1000
55
+
56
+ const minThreshold = (value) => (value ? minOn : minOff)
57
+
58
+ function pushPeriod (sensorKey, s, value, startTime, endTime, endPos) {
59
+ const duration = endTime - startTime
60
+ const period = {
61
+ value,
62
+ startTime,
63
+ endTime,
64
+ duration,
65
+ name: s.name,
66
+ endAddress: endPos.address,
67
+ valueDescription: value
68
+ ? d.attributes[s.sensor + 'on']
69
+ : d.attributes[s.sensor + 'off']
70
+ }
71
+ console.debug(period)
72
+ result[sensorKey].push(period)
73
+ }
74
+
75
+ for (const s of sensors) result[s.sensor] = []
76
+
77
+ // Track current period per sensor
78
+ const current = {}
79
+ const firstPos = positions[0]
80
+ for (const s of sensors) {
81
+ current[s.sensor] = {
82
+ value: firstPos.attributes[s.id],
83
+ startTime: new Date(firstPos.fixTime)
84
+ }
85
+ }
86
+
87
+ for (let i = 1; i < positions.length; i++) {
88
+ const prevPos = positions[i - 1]
89
+ const currPos = positions[i]
90
+ const changeTime = new Date(currPos.fixTime)
91
+
92
+ for (const s of sensors) {
93
+ const key = s.sensor
94
+ const prevValue = current[key].value
95
+ const newValue = currPos.attributes[s.id]
96
+
97
+ if (prevValue === newValue) continue
98
+
99
+ const oldStartTime = current[key].startTime
100
+ const prevEndTime = changeTime
101
+ const duration = prevEndTime - oldStartTime
102
+ const threshold = minThreshold(prevValue)
103
+ let newPeriodStartTime = changeTime
104
+
105
+ // Check distance between positions
106
+ if (prevValue === false && newValue === true && maxDistanceBetweenPositions > 0) {
107
+ const nextPos = positions[i + 1]
108
+ if (nextPos && nextPos.attributes && nextPos.attributes[s.id] === true) {
109
+ const nextTime = new Date(nextPos.fixTime)
110
+ if (nextTime - oldStartTime > maxDistanceBetweenPositions) {
111
+ newPeriodStartTime = nextTime
112
+ }
113
+ }
114
+ }
115
+
116
+ if (duration >= threshold) {
117
+ pushPeriod(key, s, prevValue, oldStartTime, prevEndTime, prevPos)
118
+ } else {
119
+ // merging logic for previous ignored period
120
+ const list = result[key]
121
+ if (list.length > 0) {
122
+ const last = list[list.length - 1]
123
+ if (last.value === newValue) {
124
+ list.pop()
125
+ newPeriodStartTime = new Date(last.startTime)
126
+ }
127
+ }
128
+ }
129
+
130
+ current[key] = {
131
+ value: newValue,
132
+ startTime: newPeriodStartTime
133
+ }
134
+ }
135
+ }
136
+
137
+ // Close final periods
138
+ const lastPos = positions[positions.length - 1]
139
+ const lastTime = new Date(lastPos.fixTime)
140
+
141
+ for (const s of sensors) {
142
+ const key = s.sensor
143
+ const st = current[key]
144
+ const startTime = st.startTime
145
+ const endTime = lastTime
146
+ const value = st.value
147
+ const duration = endTime - startTime
148
+ const threshold = minThreshold(value)
149
+
150
+ if (duration >= threshold) {
151
+ pushPeriod(key, s, value, startTime, endTime, lastPos)
152
+ } else {
153
+ // try to merge tiny final period into previous pushed period if same value
154
+ const list = result[key]
155
+ if (list.length > 0 && list[list.length - 1].value === value) {
156
+ const last = list[list.length - 1]
157
+ last.endTime = endTime
158
+ last.duration = last.endTime - last.startTime
159
+ last.endAddress = lastPos.address
160
+ last.valueDescription = value
161
+ ? d.attributes[s.sensor + 'on']
162
+ : d.attributes[s.sensor + 'off']
163
+ }
164
+ // otherwise drop final tiny period
165
+ }
166
+ }
167
+
168
+ return result
169
+ }
170
+
95
171
  async function create (from, to, userData, traccar) {
96
172
  const devices = devicesToProcess(userData)
97
173
  const sliced = automaticReports.sliceArray(devices, 5)
@@ -0,0 +1,19 @@
1
+ const { getReports } = require('./index')
2
+ const assert = require('assert')
3
+ const { createDailyUseReport } = require('../partnerReports/dailyuse-report')
4
+
5
+ describe('dailyuse', function () {
6
+ // eslint-disable-next-line no-undef
7
+ it('dailyuse report', async () => {
8
+ const report = await getReports()
9
+ const userData = await report.getUserData()
10
+
11
+ const data = await createDailyUseReport(
12
+ new Date(Date.UTC(2023, 10, 1, 0, 0, 0, 0)),
13
+ new Date(Date.UTC(2023, 10, 6, 23, 59, 59, 0)),
14
+ userData,
15
+ report.traccar)
16
+ console.log(data)
17
+ assert.equal(data[0].consumption, 19.799999999999997)
18
+ }, 8000000)
19
+ })
@@ -0,0 +1,23 @@
1
+ const { getReports } = require('./index')
2
+ const assert = require('assert')
3
+ const { convertMS } = require('../util/utils')
4
+ const { createGPSJumpReport } = require('../partnerReports/gpsjump-report')
5
+
6
+ // eslint-disable-next-line no-undef
7
+ describe('gpsjump', function () {
8
+ // eslint-disable-next-line no-undef
9
+ it('gpsjump report', async () => {
10
+ const report = await getReports()
11
+ const userData = await report.getUserData()
12
+ userData.devices = userData.devices.filter(d => d.id === 22326)
13
+ const data = await createGPSJumpReport(
14
+ new Date(Date.UTC(2023, 6, 1, 0, 0, 0, 0)),
15
+ new Date(Date.UTC(2023, 6, 17, 23, 59, 59, 0)),
16
+ userData,
17
+ report.traccar)
18
+ console.log(data)
19
+ assert.equal(data[0].consumption, 19.799999999999997)
20
+ assert.equal(data[0].distance, 326.7657)
21
+ assert.equal(convertMS(data[1].time * 1000, false), '08:19')
22
+ }, 8000000)
23
+ })
@@ -65,10 +65,11 @@ describe('Kms_Reports', function () {
65
65
  it('KmsReport by timezone marrocos', async () => {
66
66
  const reports = await getReports(process.env.email, process.env.password)
67
67
  const userData = await reports.getUserData()
68
+ userData.groupByDay = true
68
69
  userData.devices = userData.devices.filter(d => d.id === 93497)
69
70
  const data = await reports.kmsReport(convertFromLocal(new Date(2024, 2, 18, 0, 0, 0), userData.user.attributes.timezone), convertFromLocal(new Date(2024, 2, 18, 23, 59, 59), userData.user.attributes.timezone),
70
71
  userData)
71
72
  const device = data[0].devices.find(d => d.device.id === 93497)
72
- assert.equal(device, 1)
73
+ assert.equal(device.days.length, 1)
73
74
  }, 3000000)
74
75
  })
@@ -159,4 +159,21 @@ describe('zones', function () {
159
159
  console.log(first)
160
160
  assert.equal(first.days[6].distanceOut, 867.0554430738234)
161
161
  }, 4000000)
162
+
163
+ it('works with casais zones in columns 7', async () => {
164
+ const report = await getReports()
165
+ const userData = await report.getUserData()
166
+ userData.zonesByColumn = true
167
+ userData.devices = userData.devices.filter(d => d.id === 81166)
168
+ userData.geofences = userData.geofences.filter(g => g.name === 'baliza 1 - raio verde ' ||
169
+ g.name === 'baliza 2 - raio amarelo')
170
+ userData.onlyWithKmsOut = false
171
+ const result = await report.zoneReport(
172
+ new Date(Date.UTC(2023, 9, 9, 0, 0, 0, 0)),
173
+ new Date(Date.UTC(2023, 9, 31, 23, 59, 59, 0)),
174
+ userData)
175
+ const first = result[0].devices[0]
176
+ console.log(first)
177
+ assert.equal(first.days[17].distanceOut, 720.7985320478997)
178
+ }, 4000000)
162
179
  })
@@ -25,12 +25,6 @@ exports.parallel = (report, method, toSlice, ...args) => {
25
25
  try {
26
26
  console.log('forking worker', workerCount++, report, method, slice.length)
27
27
  const worker = cluster.fork()
28
- worker.send({
29
- report,
30
- method,
31
- args: [slice, ...args]
32
- })
33
- console.log('sent to worker', worker.process.pid)
34
28
  worker.on('message', ({ result }) => {
35
29
  console.log('received result from worker', worker.process.pid)
36
30
  _result.push(result)
@@ -48,6 +42,12 @@ exports.parallel = (report, method, toSlice, ...args) => {
48
42
  reject(new Error(`Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`))
49
43
  }
50
44
  })
45
+ worker.send({
46
+ report,
47
+ method,
48
+ args: [slice, ...args]
49
+ })
50
+ console.log('sent to worker', worker.process.pid)
51
51
  } catch (e) {
52
52
  console.error(report, method, 'worker', workerCount, 'numCPUs', numCPUs)
53
53
  reject(e)
@@ -538,7 +538,7 @@ function analyseAlerts (alerts, deviceRoute, userData, from, to, device) {
538
538
 
539
539
  async function getInAndOutEvents (devices, route, userData) {
540
540
  const events = []
541
- const geofencesFeatures = userData.geofences.map(g => convertToFeature(g))
541
+ const geofencesFeatures = userData.geofences.filter(g => g.area).map(g => convertToFeature(g))
542
542
  devices.forEach(d => {
543
543
  const deviceRoute = route.filter(p => p.deviceId === d.id)
544
544
  const routePoints = deviceRoute.sort(sortPositions).map(p => convertPositionToFeature(p))