2024-02-27 20:21:36 +01:00
|
|
|
from typing import List, Tuple
|
2024-02-27 20:37:51 +01:00
|
|
|
from motor.motor_asyncio import AsyncIOMotorCollection
|
|
|
|
import datetime as dt
|
2024-02-27 20:21:36 +01:00
|
|
|
|
2024-02-27 20:37:51 +01:00
|
|
|
async def aggregate_salaries(collection: AsyncIOMotorCollection, dt_from: str, dt_upto: str, group_type: str) -> Tuple[List[int], List[str]]: # type: ignore
|
2024-02-27 20:42:40 +01:00
|
|
|
group_type_format = "%Y-%m-%dT00:00:00" if group_type == "day" else "%Y-%m-01T00:00:00" if group_type == "month" else "%Y-%m-%dT%H:00:00"
|
2024-02-27 20:21:36 +01:00
|
|
|
pipeline = [
|
2024-02-27 20:37:51 +01:00
|
|
|
{
|
|
|
|
"$match": {
|
|
|
|
"dt": {
|
2024-02-27 20:54:35 +01:00
|
|
|
"$gte": iso(dt_from),
|
|
|
|
"$lte": iso(dt_upto)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"$densify": {
|
|
|
|
"field": "dt",
|
|
|
|
"range": {
|
|
|
|
"step": 1,
|
|
|
|
"unit": group_type,
|
|
|
|
"bounds": [
|
2024-02-27 21:24:45 +01:00
|
|
|
iso(dt_from), iso(dt_upto) + dt.timedelta(days=int(group_type=="day"), hours=int(group_type=="hour")) * (iso(dt_upto).time() == dt.time(hour=0, minute=0, second=0))
|
2024-02-27 20:54:35 +01:00
|
|
|
]
|
2024-02-27 20:37:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"$group": {
|
|
|
|
"_id": {
|
|
|
|
"$dateToString":
|
|
|
|
{
|
2024-02-27 20:42:40 +01:00
|
|
|
"format": group_type_format,
|
2024-02-27 20:37:51 +01:00
|
|
|
"date": "$dt"
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"sum": {
|
|
|
|
"$sum": "$value"
|
|
|
|
},
|
|
|
|
}
|
2024-02-27 20:42:40 +01:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"$sort": {
|
|
|
|
"_id": 1
|
|
|
|
}
|
2024-02-27 20:37:51 +01:00
|
|
|
}
|
2024-02-27 20:21:36 +01:00
|
|
|
]
|
|
|
|
|
2024-02-27 20:37:51 +01:00
|
|
|
dataset = []
|
|
|
|
labels = []
|
|
|
|
|
|
|
|
async for document in collection.aggregate(pipeline):
|
|
|
|
dataset.append(document["sum"])
|
|
|
|
labels.append(document["_id"] )
|
|
|
|
|
|
|
|
return {"dataset": dataset, "labels": labels}
|
|
|
|
|
|
|
|
def iso(date: str) -> dt.datetime:
|
2024-02-27 21:24:45 +01:00
|
|
|
return dt.datetime.fromisoformat(date)
|
|
|
|
|
|
|
|
|