Fix weekly consumption calc
Description
After ordering/booking a coffee using Postman, I found some inconsistencies with the calculation of the konsum
field of the transaction data.
The calculation does not consider all edge cases. With the given examples below the calculation is as follows:
With the two days period of "2024-10-02" and "2024-10-01", the time difference of the total history is:
- Math.abs(1727827200000 - 1727740800000) = **86400000 ms** (equivalent to 1 day)
- convert time difference to weeks -> 86400000 / (1000 * 60 * 60 * 24 * 7)
- 1000 * 60 * 60 * 24 * 7 = 604800000 ms
- 86400000 / 604800000 ≈ 0.142857 weeks
Result: 0.142857 weeks
Given the field "konsum" is 4 (like in the second code snippet below) the calculation continues as follows:
- data.konsum / 0.142857 -> 4 / 0.142857 ≈ 28
- and lastly rounding up: Math.ceil(28) = 28
Result: 28 items per week
Suggested solution
const MS_IN_WEEK = 1000 * 60 * 60 * 24 * 7;
const firstDate = new Date(data.history[0].date).getTime();
const lastDate = new Date(data.history[data.history.length - 1].date).getTime();
const timeDiff = Math.abs(firstDate - lastDate);
const weeks = Math.max(timeDiff / MS_IN_WEEK, 1); // using Math.max to set amount of weeks to minimum of 1
data.konsum = Math.ceil(data.konsum / weeks)
NOTE: Due to lack of time I did not spin up a own database to test this code live. It just wrote a short calculation in javascript using the provided values.
Results snippets recorded while testing:
Result after first booking:
{
"chart": {
// omitted
},
"konsum": 21,
"history": [
{
"date": "2024-10-02T00:00:00.000Z",
"amount": "2",
// omitted
},
{
"date": "2024-10-01T00:00:00.000Z",
"amount": "1",
// omitted
}
]
// omitted
}
Result after 2nd booking
{
"chart": {
// omitted
},
"konsum": 28,
"history": [
{
"date": "2024-10-02T00:00:00.000Z",
"amount": "3",
// omitted
},
{
"date": "2024-10-01T00:00:00.000Z",
"amount": "1",
// omitted
}
]
// omitted
}
Misc
Additionally, I encountered some rounding issues in the payload of the order response. It don't know what consequences this might have in the future though - just a note.