54 lines
3.4 KiB
Python
54 lines
3.4 KiB
Python
from collections import defaultdict
|
|
from datetime import date, datetime
|
|
from decimal import Decimal
|
|
|
|
from flask import current_app, jsonify, request, url_for
|
|
from flask_login import current_user, login_required, login_user
|
|
from sqlalchemy import extract
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
from . import api
|
|
from .common import accessible_vehicles, boolv, fail, payload, response, role_required, station_dict, user_dict, vehicle_dict
|
|
from .. import THEMES
|
|
from ..api_tokens import create_access_token
|
|
from ..extensions import db
|
|
from ..models import AppSetting, CompanySettings, FuelCard, FuelCardPolicy, FuelCardStationRule, FuelEntry, FuelStationCompany, FuelStationPoint, OrlenPrice, User, Vehicle
|
|
from ..services import POLISH_REGIONS, aggregate_ure_companies, calculate_costs, fetch_orlen_price, fetch_orlen_range, fetch_ure_stations, invoice_period
|
|
from ..station_catalog import sync_station_catalog
|
|
|
|
FUEL_TYPES = ("PB95", "PB98", "DIESEL", "LPG")
|
|
|
|
@api.get('/orlen/prices')
|
|
@login_required
|
|
def orlen_prices():
|
|
year=request.args.get('year',type=int) or date.today().year; fuels=[x.upper() for x in request.args.getlist('fuel') if x.upper() in FUEL_TYPES] or ['PB95']; regions=[x.lower() for x in request.args.getlist('region') if x.lower() in POLISH_REGIONS]
|
|
rows=OrlenPrice.query.filter(OrlenPrice.fuel_type.in_(fuels),extract('year',OrlenPrice.effective_date)==year).order_by(OrlenPrice.effective_date).all()
|
|
return response([{'fuel_type':r.fuel_type,'date':r.effective_date.isoformat(),'price_per_liter':float(r.price_per_liter),'region':r.region,'source':r.source} for r in rows if r.fuel_type!='LPG' or not regions or r.region in regions])
|
|
|
|
@api.post('/orlen/sync')
|
|
@role_required('boss','admin')
|
|
def orlen_sync():
|
|
d=payload(); fuels=d.get('fuels',[]); fuels=[fuels] if isinstance(fuels,str) else fuels; fuels=[f.upper() for f in fuels if f.upper() in FUEL_TYPES]; year=int(d.get('year',date.today().year))
|
|
regions=d.get('regions',[]); regions=[regions] if isinstance(regions,str) else regions; regions=[str(r).strip().lower() for r in regions if str(r).strip().lower() in POLISH_REGIONS]
|
|
if not fuels:return fail('Wybierz co najmniej jedno paliwo')
|
|
settings=CompanySettings.query.first(); result={}; total=0
|
|
try:
|
|
for fuel in fuels:
|
|
added=updated=0
|
|
for row in fetch_orlen_range(fuel,date(year,1,1),min(date(year,12,31),date.today()),'all' if fuel=='LPG' else settings.region):
|
|
if fuel=='LPG' and regions and row.get('region') not in regions: continue
|
|
x=OrlenPrice.query.filter_by(fuel_type=row['fuel_type'],effective_date=row['effective_date'],region=row['region']).first()
|
|
if x:
|
|
for k,v in row.items():setattr(x,k,v)
|
|
x.fetched_at=datetime.utcnow();updated+=1
|
|
else:db.session.add(OrlenPrice(**row));added+=1
|
|
result[fuel]={'added':added,'updated':updated};total+=added+updated
|
|
db.session.commit();return response(result,f'Przetworzono {total} rekordów')
|
|
except Exception as exc:db.session.rollback();return fail(str(exc),502)
|
|
|
|
@api.get('/orlen/preview')
|
|
@login_required
|
|
def orlen_preview():
|
|
try:return response(fetch_orlen_price(request.args['fuel_type'],datetime.fromisoformat(request.args['date']).date(),request.args.get('region') or CompanySettings.query.first().region))
|
|
except Exception as exc:return fail(str(exc),502)
|