secmi / utils /btn_behaviors.py
tgey's picture
APP test
2145052
import os
import numpy as np
import pandas as pd
import streamlit as st
import datetime as dt
from data.cli_dropbox import dropbox_upload_file
from data.datastructures import generate_intervenant_fit, generate_intervenant_monthly_payroll, generate_society_fit, generate_society_payroll
from data.excels import get_fit_totals, update_historical_week, update_monthly_payroll, update_society_fit, update_society_payroll, write_excel_fit
from utils.indemnites import calculate_arrets
from utils.times import date_to_week_day, date_to_week_number
from utils.device import get_current_ip, get_device_id
from const import root_path
import asyncio
def merge_dicts(list_of_dicts):
merged_dict = {}
for dictionary in list_of_dicts:
for key, value in dictionary.items():
if key not in merged_dict:
merged_dict[key] = []
merged_dict[key].append(value)
return merged_dict
@st.cache_resource
async def read_transform_write_excel(datapath: str = f'{root_path}/data/output', form: dict = None):
fit_data = {
"year": form["year"],
"month": form["month"],
"week": form["week"],
"intervenant": form["intervenant"],
}
fit_dict = generate_intervenant_fit(form)
fit_df = pd.DataFrame(fit_dict, index=[0])
if 'fit' in st.session_state.keys() \
and form["intervenant"] in st.session_state['fit'].keys() \
and form["year"] in st.session_state['fit'][form["intervenant"]].keys() \
and form["month"] in st.session_state['fit'][form["intervenant"]][form["year"]].keys() \
and form["week"] in st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]].keys():
df = st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]][form["week"]]['data']
# Concatenate DataFrame and dictionary DataFrame
fit_df = pd.concat([df, fit_df], ignore_index=True)
totals = get_fit_totals(fit_df)
fit_data['data'] = fit_df
fit_data['totals'] = totals
path = f'{form["intervenant"]}_{form["year"]}_{form["month"]}_{form["week"]}_FIT.xlsx'
write_excel_fit(datapath, path, fit_data)
dropbox_upload_file(datapath, path, f'/SEC_IND_GTP2023_OUTPUT/FIT/{form["intervenant"]}/{form["year"]}/{form["month"]}/{form["week"]}', path)
if 'fit' not in st.session_state.keys():
st.session_state['fit'] = {}
if form["intervenant"] not in st.session_state['fit'].keys():
st.session_state['fit'][form["intervenant"]] = {}
if form["year"] not in st.session_state['fit'][form["intervenant"]].keys():
st.session_state['fit'][form["intervenant"]][form["year"]] = {}
if form["month"] not in st.session_state['fit'][form["intervenant"]][form["year"]].keys():
st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]] = {}
if form["week"] not in st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]].keys():
st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]][form["week"]] = {}
st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]][form["week"]] = {
'data': fit_data['data'],
'totals': totals
}
st.toast('Fiche de temps envoyée', icon="📨")
return st.session_state['fit'][form["intervenant"]][form["year"]][form["month"]][form["week"]]
def validate():
data_dict = {
"intervenant": st.session_state.intervenant,
"nom": st.session_state.df['intervenants'][st.session_state.df['intervenants']['intervenant'] == st.session_state.intervenant]['Nom'].values[0],
"prenom": st.session_state.df['intervenants'][st.session_state.df['intervenants']['intervenant'] == st.session_state.intervenant]['Prénom'].values[0],
"employeur": st.session_state.df['intervenants'][st.session_state.df['intervenants']['intervenant'] == st.session_state.intervenant]['Employeur'].values[0],
"client": st.session_state.client,
"affaire": st.session_state.affaire,
"prestataire": st.session_state.prestataire,
"vehicule": st.session_state.vehicules,
"location": st.session_state.location,
"activities": st.session_state.activities_text_area,
"date": st.session_state.date_input,
"year": st.session_state.date_input.year,
"month": st.session_state.date_input.month,
"week": date_to_week_number(st.session_state.date_input),
"public_holyday": st.session_state.public_holyday,
"start_time": st.session_state.start_time_input,
"end_time": st.session_state.end_time_input,
"pause_time": st.session_state.pause_time_input,
"supplement_1": st.session_state.supplement1,
"supplement_2": st.session_state.supplement2,
"supplement_3": st.session_state.supplement3,
# "contract_hours": st.session_state.df['all'].contract_hours[st.session_state.indexes_all['contract_hours']],
# "maladie": st.session_state.total_hours if st.session_state.affaire.find('Absence Maladie Individuelle') != -1 or \
# st.session_state.affaire.find('Absence Maladie Professionnelle') != -1 \
# else 0,
"maladie": calculate_arrets() if st.session_state.affaire.find('Absence Maladie Individuelle') != -1 or \
st.session_state.affaire.find('Absence Maladie Professionnelle') != -1 \
else 0,
"arret_travail": calculate_arrets() if st.session_state.affaire.find('Absence Accident du Travail') != -1 else 0,
"conges_payes": calculate_arrets() if st.session_state.affaire.find('Absence Congés payés') != -1 else 0,
"conges_sans_solde": calculate_arrets() if st.session_state.affaire.find('Absence Congés sans solde') != -1 else 0,
"rtt": calculate_arrets() if st.session_state.affaire.find('Absence RTT') != -1 else 0,
"formation": calculate_arrets() if st.session_state.affaire.find('Absence Formation') != -1 else 0,
"evenement_familial": calculate_arrets() if st.session_state.affaire.find('Absence Evénement Familial') != -1 else 0,
"worked_hours": st.session_state.total_hours if st.session_state.total_hours else 0,
"night_hours": st.session_state.night_hours if st.session_state.night_hours else 0,
"contract_hours": st.session_state.contract_hours if st.session_state.contract_hours else 0,
"supp_contract_hours": st.session_state.supp_contract_hours if st.session_state.supp_contract_hours else 0,
"day_hours": st.session_state.total_hours - st.session_state.night_hours if st.session_state.total_hours and st.session_state.night_hours else 0,
"drive_hours": st.session_state.drive_hours if st.session_state.drive_hours else 0,
"saturday_hours": st.session_state.total_hours if date_to_week_day(st.session_state.date_input) == 'samedi' else 0,
"sunday_hours": st.session_state.total_hours if date_to_week_day(st.session_state.date_input) == 'dimanche' else 0,
"holyday_hours": st.session_state.total_hours if st.session_state.public_holyday else 0,
"overtime_25": st.session_state.overtime25 if st.session_state.overtime25 else 0,
"overtime_50": st.session_state.overtime50 if st.session_state.overtime50 else 0,
"overtime_100": st.session_state.overtime100 if st.session_state.overtime100 else 0,
"meal_nonus": st.session_state.meal_bonus if st.session_state.meal_bonus else 0,
"mileage_allowances_bonus": st.session_state.mileage_allowances_bonus if st.session_state.mileage_allowances_bonus else 0,
"personal_tools_bonus": st.session_state.personal_tools_bonus if st.session_state.personal_tools_bonus else 0,
"intervention_bonus": st.session_state.intervention_bonus if st.session_state.intervention_bonus else 0,
"on_call_bonus": st.session_state.on_call_bonus if st.session_state.on_call_bonus else 0,
"team_leader_bonus": st.session_state.team_leader_bonus if st.session_state.team_leader_bonus else 0,
# "other_bonus": st.session_state.electrical_bonus + st.session_state.painting_bonus + st.session_state.welding_bonus if st.session_state.electrical_bonus + st.session_state.painting_bonus + st.session_state.welding_bonus else 0,
"device_model": get_device_id(),
"device_ip": get_current_ip(),
"modified": dt.datetime.now(),
}
if 'completed_forms' not in st.session_state:
st.session_state['completed_forms'] = []
st.session_state.completed_forms.append(data_dict)
st.toast('Fiche de temps validée et enregistrée', icon="✅")
def reset(df):
st.session_state.df = df
st.session_state.indexes_all = {k: 0 for k in df['all'].columns}
st.session_state.indexes_affaire = {k: 0 for k in df['affaire'].columns}
st.session_state.indexes_intervenants = {k: 0 for k in df['intervenants'].columns}
st.session_state.indexes_vehicules = {k: 0 for k in df['vehicules'].columns}
st.session_state.intervenant = df['intervenants'].intervenant[0]
st.session_state.client = df['affaire'].client[0]
st.session_state.affaire = df['affaire'].affaire[0]
st.session_state.prestataire = df['affaire'].prestataire[0]
st.session_state.vehicules = df['vehicules'].vehicules[0]
st.session_state.activities_text_area = ""
st.session_state.date_input = dt.datetime.now()
st.session_state.public_holyday = False
st.session_state.start_time_input = dt.time(8, 00)
st.session_state.end_time_input = dt.time(17, 00)
st.session_state.pause_time_input = dt.time(0, 00)
st.session_state.supplement1 = df['supplements'].supplements[0]
st.session_state.supplement2 = df['supplements'].supplements[0]
st.session_state.supplement3 = df['supplements'].supplements[0]
st.toast('Nouvelle fiche de temps ', icon="🔃")
async def run_async_tasks():
await read_transform_write_excel(form=st.session_state.completed_forms[-1])
st.toast('Mise à jour de votre historique, veuillez patienter', icon="💾")
historic_df = await update_historical_week(dropbox_datapath='/SEC_IND_GTP2023_OUTPUT', form=st.session_state.completed_forms[-1])
st.toast('Historique mis à jour', icon="✅")
st.toast('Mise à jour du Tableau de société, veuillez patienter', icon="💾")
society_form = generate_society_fit(form=st.session_state.completed_forms[-1])
society_df = await update_society_fit(dropbox_datapath='/SEC_IND_GTP2023_OUTPUT', form=society_form)
st.toast('Tableau de société mis à jour', icon="✅")
st.toast('Mise à jour des Prestations croisées, veuillez patienter', icon="💾")
society_form = generate_society_payroll(form=st.session_state.completed_forms[-1])
society_df = await update_society_payroll(dropbox_datapath='/SEC_IND_GTP2023_OUTPUT', form=society_form)
st.toast('Prestations croisées mis à jour', icon="✅")
st.toast('Mise à jour du Tableau de paye, veuillez patienter', icon="💾")
payroll = generate_intervenant_monthly_payroll(form=historic_df)
await update_monthly_payroll(dropbox_datapath='/SEC_IND_GTP2023_OUTPUT', payroll_dict=payroll, year=st.session_state.completed_forms[-1]['year'] , month=st.session_state.completed_forms[-1]['month'], week=st.session_state.completed_forms[-1]['week'])
st.toast('Tableau de paye mis à jour', icon="✅")
st.toast('Fiche de temps dupliquée', icon="📄")
def validate_duplicate():
if st.session_state.intervenant != '-' and st.session_state.client != '-' and st.session_state.affaire != '-':
validate()
# print(st.session_state.completed_forms[-1])
if st.session_state.date_input < dt.datetime.now().date():
st.session_state.date_input += dt.timedelta(days=1)
asyncio.run(run_async_tasks())
else:
st.toast('Veuillez remplir les champs intervenant, client et affaire', icon="⚠️")
def validate_end():
if st.session_state.intervenant != '-' and st.session_state.client != '-' and st.session_state.affaire != '-':
validate()
asyncio.run(run_async_tasks())
st.session_state.completed_forms = []
st.toast('Vous pouvez fermer l\'application ', icon="👍")
else:
st.toast('Veuillez remplir les champs intervenant, client et affaire', icon="⚠️")