from datetime import date, datetime from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware import pandas as pd import uvicorn app = FastAPI() origins = [ "http://localhost:5173", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.post("/drinks") async def write_to_excel(data: dict): try: # Define name for the Excel file current_date = date.today() current_time = datetime.now() filename = f'inventur_{current_date}-{current_time.hour}{current_time.minute}' # Extracting data from JSON name = data["name"] comment = data["comment"] inventory_finish = data["inventoryFinishedAt"] drinks = data["inventory"] # Frontend sends amount 0 as undefined when only bottles *or* # containers got set. Fixing this here. for drink in drinks: for key in ['amountBottles', 'amountContainers']: if key not in drink: drink[key] = 0 # Sorting drinks by type drinks.sort(key=lambda x: x["type"]) # Creating pandas dataframe from drinks list df = pd.DataFrame(drinks) # Putting drinks on the sheet writer = pd.ExcelWriter(f"{filename}.xlsx", engine="xlsxwriter") df.to_excel(writer, sheet_name="Inventur", index=False, startcol=3) # Adding name and comment to the worksheet worksheet = writer.sheets["Inventur"] worksheet.write(0, 0, "Inventur vom") worksheet.write(0, 1, inventory_finish) worksheet.write(1, 0, "Durchgefuehrt von") worksheet.write(1, 1, name) worksheet.write(2, 0, "Kommentar") worksheet.write(2, 1, comment) writer.save() return {"message": "Data written to excel successfully"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) if __name__ == '__main__': uvicorn.run(app, host="0.0.0.0", port=8161)