| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- from datetime import datetime
- from pprint import pprint
- from config.settings import DECIMAL_PLACES
- from cruds.measures import get_finca_measures
- from database.mongo import mongo_measures
- from routes.calculations.pipelines import count_precip_measures_pipeline, get_percent
- from schemas.fincas import FincaBase as FincaBaseSchema
- from schemas.tables import MonthlyPrecipitations as MonthlyPrecipitationsSchema
- def montly_precipitations(
- finca: FincaBaseSchema, start_datetime: datetime, end_datetime: datetime
- ) -> MonthlyPrecipitationsSchema:
- finca_data = mongo_measures[finca.station_code]
- accumulated_precip_agg = finca_data.aggregate(
- [
- {
- "$match": {
- "date": {
- "$gte": start_datetime,
- "$lte": end_datetime,
- },
- "precip": {"$ne": None},
- },
- },
- {
- "$group": {
- "_id": {
- "month": {"$month": "$date"},
- "year": {"$year": "$date"},
- },
- "sumPrecip": {"$sum": "$precip"},
- }
- },
- ]
- )
- accumulated_precip = list(accumulated_precip_agg)
- data_count = finca_data.count(
- count_precip_measures_pipeline(start_datetime, end_datetime)
- )
- total_count = (end_datetime - start_datetime).total_seconds() // (60 * 10)
- data_percentage = get_percent(data_count, total_count)
- months = {}
- for month in accumulated_precip:
- value = month.get("sumPrecip")
- if value is not None:
- value = round(value, DECIMAL_PLACES)
- months[str(month.get("_id", {}).get("month"))] = value
- summary = MonthlyPrecipitationsSchema(
- station=FincaBaseSchema(
- station_code=finca.station_code,
- title=finca.title,
- ),
- initial_date=start_datetime,
- final_date=end_datetime,
- months=months,
- data_percentage=data_percentage,
- )
- return summary
|