-
Notifications
You must be signed in to change notification settings - Fork 4
/
read_bezetting_optimized.py
2831 lines (2272 loc) · 109 KB
/
read_bezetting_optimized.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import math
import datetime as dt
from datetime import datetime #, timedelta
# import datetime
import string
import pandas as pd
import time
from openpyxl import load_workbook
import streamlit as st
# from keys import * # secret file with the prices
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import sys
import platform
import calendar
def clear_cache():
"""Clears the cache
"""
if st.button("Clear All"):
# Clear values from *all* all in-memory and on-disk data caches:
# i.e. clear values from both square and cube
st.cache_data.clear()
st.write("Cache is cleared")
st.stop()
def find_fill_color():
"""Find fill color of a cell in 2023-tabblad
# dirty solution to find the fill color.
# as solutions given here https://stackoverflow.com/questions/58429823/getting-excel-cell-background-themed-color-as-hex-with-openpyxl
# dont work
Args:
cell (string): The cell you want to find the color from
"""
if platform.processor() != "":
sheet_name = st.sidebar.text_input("Sheetname", "KLADBLOK")
cell = st.sidebar.text_input("Cell", "A1")
excel_file_2023 = r"C:\Users\rcxsm\Downloads\bezetting2023_eind.xlsb"
wb_2023 = load_workbook(excel_file_2023, data_only=True)
sh_2023 = wb_2023[sheet_name]
val = sh_2023[cell].fill.start_color.rgb
try:
valx = val[0]
valx = val
except Exception:
valx = sh_2023[cell].fill.start_color.theme
theme = sh_2023[cell].fill.start_color.theme
tint = sh_2023[cell].fill.start_color.tint
val = int(sh_2023[cell].fill.start_color.index, 16)
st.write(f"File = {excel_file_2023}")
st.write(f"Cel = {cell}")
st.write(f"{valx = } {theme=} {tint=}")
st.write(f"{val = }")
# hex_color = "%06x" % (val && 0xFFFFFF)
# st.write(hex_color)
else:
st.error("Available only on local systems")
st.stop()
@st.cache_data
def retrieve_prijzen():
"""Retrieve the average price for an accomodation in a given month
Returns:
df: Table with the prices
"""
# sheet_id prijzen = in keys.py
# sheet_name_prijzen = "prijzen"
# url_prijzen = f"https://docs.google.com/spreadsheets/d/{sheet_id_prijzen}/gviz/tq?tqx=out:csv&sheet={sheet_name_prijzen}"
if platform.processor() != "":
url_prijzen = r"C:\Users\rcxsm\Downloads\vacansoleil\prijzen.csv"
else:
url_prijzen = "https://raw.githubusercontent.com/rcsmit/streamlit_scripts/main/input/prijzen_dummy.csv"
df_prijzen = pd.read_csv(url_prijzen, delimiter=",")
# df_prijzen_stacked = df_prijzen.stack()
df_prijzen_stacked = df_prijzen.melt(
"acco_type", var_name="month_int", value_name="price_per_night"
)
df_prijzen_stacked["month_str"] = df_prijzen_stacked["month_int"].astype(str)
# .set_index('acco_type').stack().rename(columns={'price_per_night':'month'})
return df_prijzen_stacked
def create_check_table_per_accotype(df, y):
"""Generate tables per accotype to see if the sheet is 100% correct (fill colors right*).
The last column has to be zero
* a booking starts with green
* a booking end with cyaan (back_to_back) or red (checkout)
Args:
df (_type_): _description_
y : year
"""
list_of_accotypes_ = df.acco_type.unique()
st.write(f"Checking {y}")
# list_of_accotypes = [list_of_accotypes_[4]] # if you only one acco type
year_ok = True
for acco in list_of_accotypes_:
df_acco = df[df["acco_type"] == acco].reset_index()
df_acco = df_acco.groupby([df_acco["date"]], sort=True)[["geel","back_to_back","new_arrival", "vertrek_no_clean", "vertrek_clean"]].sum().reset_index()
#df_acco = df_acco.groupby(["date"]["geel","back_to_back","new_arrival", "vertrek_no_clean", "vertrek_clean"], sort=True).sum().reset_index()
df_acco = df_acco.assign(bezet_saldo=None)
df_acco.loc[0, "bezet_saldo"] = 0
df_acco["bezet_theorie"] = (
df_acco["geel"] + df_acco["back_to_back"] + df_acco["new_arrival"]
)
for i in range(1, len(df_acco)):
if y == "2023":
# paars is ook bezet ipv vertrek clean
df_acco.loc[i, "bezet_saldo"] = (
df_acco.loc[i - 1, "bezet_saldo"]
+ df_acco.loc[i, "new_arrival"]
- df_acco.loc[i, "vertrek_no_clean"]
- df_acco.loc[i, "vertrek_clean"]
)
else:
df_acco.loc[i, "bezet_saldo"] = (
df_acco.loc[i - 1, "bezet_saldo"]
+ df_acco.loc[i, "new_arrival"]
- df_acco.loc[i, "vertrek_no_clean"]
- df_acco.loc[i, "vertrek_clean"]
)
df_acco["verschil_bezet"] = df_acco["bezet_theorie"] - df_acco["bezet_saldo"]
df_acco_test = df_acco[df_acco["verschil_bezet"] != 0]
if len(df_acco_test) == 0:
st.write(f":white_check_mark: {y} - {acco} OK")
with st.expander("DF"):
st.write (df_acco)
else:
st.error(f":heavy_exclamation_mark: ERROR IN BOOKINGSSCHEMA {y} - {acco} ")
with st.expander("Complete DF"):
st.write(df_acco)
st.write(df_acco_test)
st.error("/ERROR ")
year_ok = False
if year_ok:
st.write(f":white_check_mark: **{y} is okay**")
def generate_businessinfo(df_mutations):
"""print and return the business intelligence
Args:
df_mutations (_type_): df met info over accos
df_mutation : df met de mutaties
y : year
Returns:
_type_: _description_
"""
st.write(df_mutations)
aantal_boekingen = df_mutations["back_to_back"].sum() + df_mutations["new_arrival"].sum()
if (df_mutations["aantal"].mean() * len(df_mutations) - df_mutations["out_of_order"].sum()) != 0:
occupation = round(
(
df_mutations["geel"].sum()
+ df_mutations["back_to_back"].sum()
+ df_mutations["new_arrival"].sum()
)
/ (
(df_mutations["aantal"].mean() * len(df_mutations))
- df_mutations["out_of_order"].sum()
)
* 100,
2,
)
else:
occupation = 0
aantal_overnachtingen = (
df_mutations["geel"].sum() + df_mutations["back_to_back"].sum() + df_mutations["new_arrival"].sum()
)
if (df_mutations["back_to_back"].sum() + df_mutations["new_arrival"].sum()) != 0:
# De verblijfsduur is vertekend als je het per month, per acco bekijkt in rustige maanden, zie bijv. bali, september 2019 (maar 1 aankomst, maar mensen die nog vanuit augustus aanwezig zijn)
verblijfsduur = round(
(
df_mutations["geel"].sum()
+ df_mutations["back_to_back"].sum()
+ df_mutations["new_arrival"].sum()
)
/ (df_mutations["back_to_back"].sum() + df_mutations["new_arrival"].sum()),
2,
)
else:
verblijfsduur = 0
omzet = df_mutations["omzet"].sum()
st.write(f"{aantal_boekingen=}")
st.write(f"{occupation=}")
st.write(f"{aantal_overnachtingen=}")
st.write(f"{verblijfsduur=}")
st.write(f"{omzet=}")
# calculate number of accos for each type
def generate_columns_to_use():
"""Generate a list with columns to use, eg. from A to ZZ
Returns:
_type_: _description_
"""
alphabet = list(string.ascii_uppercase)
alphabet_tot_h = [
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
]
alphabet_to_use = []
for alp in alphabet_tot_h:
for alp2 in alphabet:
alphabet_to_use.append(alp + alp2)
alphabet_to_use = alphabet_to_use[1:]
return alphabet_to_use
def add_row(
list,
acco_type,
acco_number,
guest_name,
checkin_date,
checkout_date,
back_to_back_in,
back_to_back_out,
):
"""Add a row to the bookingslist. Called from make_booking_table()
Args:
list (list): the list where the new row has to be added
acco_type (str): _description_
acco_number (str): _description_
guest_name (str): _description_
checkin_date (str): _description_
checkout_date (str): _description_
Returns:
list: _description_
"""
number_of_days = datetime.strptime(checkout_date, "%Y-%m-%d") - datetime.strptime(checkin_date, "%Y-%m-%d")
try:
delta = (
datetime.strptime(checkout_date, "%Y-%m-%d").date()
- datetime.strptime(checkin_date, "%Y-%m-%d").date()
)
number_of_days = delta.days
except:
st.write(f" {acco_number= }, {guest_name=}, {checkin_date=}, {checkout_date=},")
number_of_days = 0
list.append(
[
acco_type,
acco_number,
guest_name,
checkin_date,
checkout_date,
back_to_back_in,
back_to_back_out,
number_of_days,
]
)
return list
# @st.cache_data()
def make_booking_table(wb_2023):
"""Generate a booking_tabel from the booking chart
columns: [acco_type,acco_number, guest_name, checkin_date, checkout_date, number_of_days]
Args:
year (int): the year of which you want the booking table
"""
columns_to_use = generate_columns_to_use()
list = []
# placeholder_what = st.empty()
acco_type, acco_temp = None, None
# placeholder_progress = st.empty()
for year in [2019,2021,2022,2023]:
year_temp = year
to_do, sheets= select_to_do_and_sheet(wb_2023, year)
for i,t in enumerate(to_do):
progress = int(i/len(to_do)*100)
for r in range(t[1], t[2] + 1):
first_guest = False
guest_name = None
acco_number_cell = "a" + str(r)
sh_titel = sheets[0]
for sh in sheets:
if acco_type != acco_temp:
print(f"Making booking table {year_temp} | {acco_type}" )
acco_temp = acco_type
# placeholder_progress.progress(progress)
acco_type = str(sh_titel["a" + str(t[0])].value)
acco_type = replace_acco_types(acco_type)
acco_number = str(sh_titel[acco_number_cell].value)
if acco_number == "kal 32m2 645":
acco_number = 645
if acco_number == "kal 25m2 654":
acco_number = 654
if acco_number == "25m2 641":
acco_number = 641
if acco_number == "25m2 655":
acco_number = 655
for c in columns_to_use[1:]:
cell_ = c + str(r)
date_ = str(sh[c + "2"].value)
try:
date2 = datetime.strptime(date_, "%Y-%m-%d %M:%H:%S")
date = datetime.strftime(date2, "%Y-%m-%d")
month = date2.month
year = date2.year
except Exception:
date = None
month = None
year = None
val = sh[cell_].fill.start_color.rgb
try:
valx = val[0]
valx = val
except Exception:
valx = sh[cell_].fill.start_color.theme
# if valx != "00000000":
# print (f"{sh} {r} {c} {valx} {sh[c + str(r)].value}")
if valx == 9 or valx == "FF70AD47": # licht groen
first_guest = True
checkin_date = date
# if (guest_name == "" or guest_name == None) and first_guest == True:
# guest_name = "ERROR"
# else:
guest_name = str(sh[c + str(r)].value)
#st.write(f"--{r}--{sh}---{val} --{cell_}- {guest_name}")
back_to_back_in = False
elif valx == "FFFF0000": # rood
checkout_date = date
back_to_back_out = False
list = add_row(
list,
acco_type,
acco_number,
guest_name,
checkin_date,
checkout_date,
back_to_back_in,
back_to_back_out,
)
guest_name = "_"
elif valx == "FF7030A0": # paars
checkout_date = date
back_to_back_out = False
list = add_row(
list,
acco_type,
acco_number,
guest_name,
checkin_date,
checkout_date,
back_to_back_in,
back_to_back_out,
)
elif valx == 5: # bruin
pass
elif valx == 0 or valx == 6: # zwart of grijs
pass
elif valx == "FF00B0F0" or valx=="FFFFC000": # lichtblauw / cyaan - dark yellow for non paid resa
checkout_date = date
back_to_back_out = True
list = add_row(
list,
acco_type,
acco_number,
guest_name,
checkin_date,
checkout_date,
back_to_back_in,
back_to_back_out,
)
checkin_date = date
guest_name = str(sh[c + str(r)].value)
back_to_back_in = True
elif valx == "FFFFFF00": # geel / bezet
pass
# guest_name =""
df = pd.DataFrame(
list,
columns=[
"acco_type",
"acco_number",
"guest_name",
"checkin_date",
"checkout_date",
"back_to_back_in",
"back_to_back_out",
"number_of_days",
],
)
df = extract_info(df)
#df = add_extra_linnen(df)
df = make_date_columns(df)
# placeholder_what.empty()
# placeholder_progress.empty()
return df
def extract_info(df):
"""Extracts nationality, guest name, linnen, babypack and bookingnumber and puts in a new column
Args:
df (_type_): _description_
Returns:
_type_: _description_
"""
# df["number_of_days"] = df["number_of_days"].astype(string)
# extract the language code from the text column using a regular expression
df["guest_name"] = df["guest_name"].str.replace(r'^de\s', 'de_', regex=True)
df["guest_name"] = df["guest_name"].str.replace(r'^van de\s', 'van de_', regex=True)
df["guest_name"] = df["guest_name"].str.replace("sp+", "s_peeltuin+", regex=True) #geeft een fout bij "nispen sp+"
df["guest_name"] = df["guest_name"].str.replace(r"\bsp\+\b", "s_peeltuin+", regex=True) #geeft een fout bij "nispen sp+"
df["language"] = df["guest_name"].str.extract(
r"\b(du|de|en|fr|dm|dk|gb|de|uk|po|it|ph|lx|lux|ch|sp|ierl|be)\b", expand=False
)
df['language'] = df['language'].replace({'gb':'en','du': 'de', 'dm': 'dk'})
# fill missing values with 'NL'
df["language"] = df["language"].fillna("nl")
df["guest_name_booking"] = df["guest_name"].str.split().str[0]
# Extract the text and store it in a new column
# df['guest_name_booking'] = df['guest_name'].apply(lambda x: re.match(r'^(.*?)(?=\b(?:\d+|du|en|fr|dk|gb|de|po|it|sp|ierl|be|)\b)', x).group(1))
df["guest_name_booking"] = df["guest_name"].str.extract(r"^([^0-9]+)")
# Remove specific endings from the extracted text
endings = ["du", "en", "fr", "dk", "dm","uk", "gb", "de", "po", "it", "sp", "ierl", "be"]
# Replace values in the column
df["guest_name_booking"] = df["guest_name_booking"].str.replace(
rf'({"|".join(endings)})$', "", regex=True
)
df["guest_name_booking"] = df["guest_name_booking"].str.replace("s_peeltuin+", "sp", regex=True) #geeft een fout bij "nispen sp+"
# LINNEN
df["guest_name"] = df["guest_name"].str.replace(r"\*1", "x1", regex=True)
df["guest_name"] = df["guest_name"].str.replace(r"\*2", "x2", regex=True)
df["dbl_linnen"] = df["guest_name"].str.extract(r"\b(\d+)x2\b", expand=False).fillna(0).astype(int)
df["sng_linnen"] = df["guest_name"].str.extract(r"\b(\d+)x1\b", expand=False).fillna(0).astype(int)
df = df.fillna(0)
df["babypack_old"] = df["guest_name"].str.contains("baby").astype(int)
df["kst"] = df["guest_name"].str.contains("kst").astype(int)
df["bb"] = df["guest_name"].str.contains(" bb").astype(int)
df["babypack"] = np.where(
(df["babypack_old"] == 1) | (df["kst"] == 1) | (df["bb"] == 1), 1, 0
)
df["booking_number"] = df["guest_name"].str.extract(r"(\d+)").fillna(0).astype(int)
# Function to format the numbers
def format_number(number):
formatted_number = format(number, ",")
return formatted_number.replace(",", "")
# Apply the formatting function to the 'Number' column
df["booking_number"] = df["booking_number"].apply(format_number)
df["guest_name"] = df["guest_name"].str.replace(r'^de_\s', 'de', regex=True)
df["guest_name"] = df["guest_name"].str.replace(r'^van de_\s', 'van de', regex=True)
return df
def add_extra_linnen(booking_table):
# Assuming you have two dataframes: bookingtable and extra_linnen
# with a common column 'reservation nr' and a column 'single linnen'
# Example dataframes
data_extra_linnen = {'reservation nr': [2, 3, 4],
'single linnen': [2, 3, 1]}
bookingtable = pd.DataFrame(data_bookingtable)
extra_linnen = pd.DataFrame(data_extra_linnen)
# Merge dataframes on 'reservation nr' and update 'single linnen' column
# Merge dataframes on 'reservation nr' and update the columns
merged_df = bookingtable.merge(extra_linnen, on='booking_number', how='left')
columns_to_update = ['dbl_linnen', 'sng_linnen', 'kst', 'bb']
for col in columns_to_update:
merged_df[col + '_x'] += merged_df[col + '_y']
merged_df.drop(columns=[col + '_y'], inplace=True)
merged_df.rename(columns={col + '_x': col}, inplace=True)
# Print the updated dataframe
print(merged_df)
# Print the updated dataframe
print(merged_df)
return booking_table
def graph_distribution_nationalities(df, y):
"""Show a graph with the distribution of nationalities in time
Args:
df (df): booking table
y : year, used in the graph titles
"""
df =df.copy()
# Convert the 'checkin_date' and 'checkout_date' columns to datetime format
df['checkin_date'] = pd.to_datetime(df['checkin_date'])
df['checkout_date'] = pd.to_datetime(df['checkout_date'])
# Generate a date range from the minimum checkin_date to the maximum checkout_date
date_range = pd.date_range(df['checkin_date'].min(), df['checkout_date'].max())
# Calculate the proportion of each language on each day
language_proportions = pd.DataFrame()
for date in date_range:
guests_on_date = df[(df['checkin_date'] <= date) & (df['checkout_date'] > date)]
guests_on_date = guests_on_date.copy()
guests_on_date["date_language"] = date
# language_counts = guests_on_date['language'].value_counts(normalize=True)
language_proportions = pd.concat([language_proportions,guests_on_date], ignore_index=True)
language_proportions["count"] =1
# Create the pivot table
df_pivot = pd.pivot_table(language_proportions, index='date_language', columns="language", values="count", aggfunc='sum')
# normalize the pivot table to ensure each row sums to 100%
pivot_table_normalized = df_pivot.div(df_pivot.sum(axis=1), axis=0) * 100
# Round the values to one decimal place
pivot_table_normalized = pivot_table_normalized.round(1).fillna(0)
# Reorder the columns to have NL at the bottom, followed by DE, and then the rest of the languages
pivot_table_normalized = pivot_table_normalized[['nl', 'de', "be"] + [col for col in pivot_table_normalized.columns if col not in ['nl', 'de', "be"]]]
# Create a line graph using Plotly
fig = go.Figure()
for column in pivot_table_normalized.columns:
fig.add_trace(go.Scatter(
x=pivot_table_normalized.index,
y=pivot_table_normalized[column],
name=column
))
fig.update_layout(
title=f'Proportions of Languages over Time in {y}',
xaxis_title='Date',
yaxis_title='Proportion (%)',
)
st.plotly_chart(fig)
# Create a stacked bar graph using Plotly
fig = go.Figure()
for column in pivot_table_normalized.columns:
fig.add_trace(go.Bar(
x=pivot_table_normalized.index,
y=pivot_table_normalized[column],
name=column,
offsetgroup=column,
))
fig.update_layout(
title=f'Stacked Proportions of Languages over Time in {y}',
xaxis_title='Date',
yaxis_title='Proportion (%)',
barmode='stack',
)
st.plotly_chart(fig)
df_pivot_acco = pd.pivot_table(language_proportions, index='acco_type', columns="language", values="count", aggfunc='sum').fillna(0)
st.write("df_pivot_acco")
st.write(df_pivot_acco)
pivot_table_acco_normalized_row = df_pivot_acco.div(df_pivot_acco.sum(axis=1), axis=0) * 100
pivot_table_acco_normalized_row = pivot_table_acco_normalized_row.round(1)
st.write("pivot_table_acco_normalized_row")
st.write(pivot_table_acco_normalized_row)
pivot_table_acco_normalized_col = df_pivot_acco.div(df_pivot_acco.sum(axis=0), axis=1) * 100
pivot_table_acco_normalized_col = pivot_table_acco_normalized_col.round(1)
st.write("pivot_table_acco_normalized_col")
st.write(pivot_table_acco_normalized_col)
def show_info_from_bookingtable(df, year):
"""Print the languages, linnen and babypacks
Args:
df (_type_): _description_
"""
st.subheader(f"Show info from bookingtable {year}")
st.write(f"Total single {df['sng_linnen'].astype(int).sum()}")
st.write(f"Total double {df['dbl_linnen'].astype(int).sum()}")
st.write(f"Total babypack {df['babypack'].sum()}")
# get the frequency table for the 'values' column
st.subheader(f"Distribution of languages in {year}")
freq_table = df["language"].value_counts()
st.write(freq_table)
st.write(f"Total number of bookings :{len(df)}")
graph_distribution_nationalities(df, year)
def select_to_do_and_sheet(wb_2023, year):
"""Select which rows to do for a given year
Called from make_booking_table and make_mutation_df
Returns:
_type_: _description_
"""
sh_2022 = [wb_2023["ALLES2022"]]
sh_2021 = [wb_2023["ALLES2021"]]
sh_2019 = [wb_2023["ALLES2019"]]
sh_2023 = [
wb_2023["mrt april"],
wb_2023["mei"],
wb_2023["juni"],
wb_2023["juli"],
wb_2023["aug"],
wb_2023["sept"],
wb_2023["okt"],
wb_2023["nov"],
]
# rij met de naam, startrij, eindrij
to_do_2023 = [
[1, 4, 9], # bal
[11, 14, 23], # wai
[25, 28, 31], # kal1
[32, 33, 36], # kal2
[37, 37, 45], # kal1
[46, 46, 48], # kal2
[50, 53, 61], # ser xl
[62, 63, 70], # ser L
[71, 74, 87],
] # navajo
to_do_2022 = [
[1, 4, 9], # bal
[11, 14, 23], # wai
[25, 28, 40], # kal1
[41, 42, 48], # kal2
[50, 53, 61], # ser xl
[62, 63, 70], # ser L
[71, 75, 88],
] # sahara
to_do_2021 = [
[1, 4, 9], # bal
[11, 14, 23], # wai
[25, 28, 40], # kal1
[41, 42, 48], # kal2
[49, 52, 60], # ser xl
[62, 65, 86],
] # sahara
to_do_2019 = [
[3, 4, 9], # bal 6
[11, 12, 21], # wai 10
[23, 24, 36], # kal1 13
[38, 39, 47], # sahara 9
[49, 50, 58], # ser xl 9
] #
if year == 2019:
to_do = to_do_2019
sheets = sh_2019
#sh_0 = sh_2019[0]
elif year == 2021:
to_do = to_do_2021
sheets = sh_2021
#sh_0 = sh_2019[0]
elif year == 2022:
to_do = to_do_2022
sheets = sh_2022
#sh_0 = sh_2022[0]
elif year == 2023:
to_do = to_do_2023
sheets = sh_2023
#sh_0 = sh_2023[0] # de sheet waar de acconamen in 2023 uit worden gehaald
else:
st.error(f"ERROR IN YEAR year = {year}")
return to_do, sheets #, sh_0
def show_info_number_of_days(df,y):
#df["number_of_days"] = df["number_of_days"].dt.days.astype("int16")
st.subheader(f"Distribution of length of stay in {y}")
st.write(f"Number of stays : {len(df)}")
st.write(f"Number of days total : {df['number_of_days'].sum()}")
st.write(f"Number of days min : {df['number_of_days'].min()}")
st.write(f"Number of days max : {df['number_of_days'].max()}")
st.write(f"Number of days average : {df['number_of_days'].mean()}")
freq_tabel = df["number_of_days"].value_counts()
st.write("Freq. number_of_days")
fig = px.histogram(df, x="number_of_days")
# plotly.offline.plot(fig)
st.plotly_chart(fig, use_container_width=True)
def replace_acco_types(accotype_2023):
# Define the string to be modified
# Define a dictionary of the values to be replaced and their replacements
replace_dict = {
"Waikiki": "WAIKIKI",
"BALI": "BALI",
"Kalahari 32m2": "KALAHARI1",
"Kalahari 25m2": "KALAHARI2",
"kalahari 25m2": "KALAHARI2",
"kal 2 654": "KALAHARI2",
"kal 1 645": "KALAHARI1",
"kalahari 2 ": "KALAHARI2",
"Kalahari 1": "KALAHARI1",
"kal 32m2 645": "KALAHARI1",
"kalahari 25m2": "KALAHARI2",
"Kalahari 32m2_": "KALAHARI1",
"kal 25m2 654": "KALAHARI2",
"Serengeti xl": "SERENGETI XL",
"serengeti 5p": "SERENGETI L",
"navajo": "SAHARA",
"kal 32m2 645": "KALAHARI1",
"Kalahari 32m2": "KALAHARI1",
"Kalahari 25m2": "KALAHARI2",
"kal 32m2 645": "KALAHARI1",
"kal 25m2 654": "KALAHARI2",
"25m2 641": "KALAHARI2",
}
# accotype_original = accotype_2023
# for key, value in replace_dict.items():
# accotype_original = accotype_original.replace(key, value)
# Create a regular expression pattern to match any of the keys in the dictionary
pattern = re.compile("|".join(replace_dict.keys()))
# Use the sub() method to replace all matches with their corresponding values
accotype_original = pattern.sub(lambda m: replace_dict[m.group(0)], accotype_2023)
return accotype_original
# @st.cache_data
def make_mutation_df(wb_2023):
"""Generate the dataframe
Columns: ['acco_type', 'aantal', 'date',"month","year", "new_arrival","vertrek_no_clean", "vertrek_clean", "back_to_back", "geel"])
Args:
columns_to_use (list with strings): which columns to scrape, eg. from "A to ... ZZ "
Returns:
df: dataframe
"""
columns_to_use = generate_columns_to_use()
list_complete = []
# placeholder_what = st.empty()
# placeholder_progress = st.empty()
for year in [2019,2021,2022,2023]:
to_do, sheets = select_to_do_and_sheet(wb_2023, year)
for ix, sh in enumerate(sheets):
print(f"Reading {year} - {sh} [{ix+1}/{len(sheets)}]")
for i,a in enumerate(columns_to_use):
# progress = int(i/len(columns_to_use)*100)
# placeholder_progress.progress(progress)
# [rij met de naam, start, eind]'
for t in to_do:
#if year == 2023:
acco_type = str(sh["a" + str(t[0])].value)
if acco_type == "kal 32m2 645" or acco_type =="637":
acco_type = "KALAHARI1"
if acco_type == "25m2 641" or acco_type == "kal 25m2 654" or acco_type =="641":
acco_type = "KALAHARI2"
#else:
# acco_type = str(sh["a" + str(t[0])].value)
# if t[0] ==32 :
# print (f".{acco_type}.")
acco_type = replace_acco_types(acco_type)
ii = []
for x in range(t[1], t[2] + 1):
ii.append(a + str(x))
bezet = 0
aantal = t[2] - t[1] + 1
vertrek_no_clean = 0
vertrek_clean = 0
vertrek_totaal = 0
back_to_back = 0
geel = 0
out_of_order = 0
new_arrival = 0
try:
date = str(sh[a + "2"].value)
date2 = datetime.strptime(date, "%Y-%m-%d %M:%H:%S")
date3 = datetime.strftime(date2, "%Y-%m-%d")
month = int(date2.month)
year = date2.year
except Exception:
date3 = "STOP"
month = 0
if year == 2023:
# leave out the last day in every sheet (bv. 1 mei voor de april sheet)
stop_conditions = {
(5, 0): "STOP",
(6, 1): "STOP",
(7, 2): "STOP",
(8, 3): "STOP",
(9, 4): "STOP",
(10, 5): "STOP",
}
date3 = stop_conditions.get((month, ix), date3)
if date3 != "STOP":
for i in ii:
val = sh[i].fill.start_color.rgb
try:
valx = val[0]
valx = val
except Exception:
valx = sh[i].fill.start_color.theme
if valx == "FFFF0000": # rood
vertrek_clean += 1
elif valx == "FF7030A0": # paars
vertrek_no_clean += 1
elif valx == 5: # bruin
vertrek_totaal += 1
elif valx == 0 or valx == 6: # zwart of grijs
out_of_order += 1
elif valx == "FF00B0F0" or valx=="FFFFC000": # lichtblauw / cyaan - dark yellow for non paid resa
back_to_back += 1
elif valx == "FFFFFF00": # geel / bezet
geel += 1
elif valx == 9 or valx == "FF70AD47": # licht groen
new_arrival += 1
row = [
acco_type,
aantal,
date3,
month,
year,
new_arrival,
vertrek_no_clean,
vertrek_clean,
back_to_back,
geel,
out_of_order,
]
list_complete.append(row)
df_mutation = pd.DataFrame(
list_complete,
columns=[
"acco_type",
"aantal",
"date",
"month",
"year",
"new_arrival",
"vertrek_no_clean",
"vertrek_clean",
"back_to_back",
"geel",
"out_of_order",
],
)
df_mutation["in_house"] = (
df_mutation["geel"] + df_mutation["new_arrival"] + df_mutation["back_to_back"]
)
df_mutation["month_str"] = df_mutation["month"].astype(str)
# df_mutation = df_mutation[
# (df_mutation["month"] >= start_month) & (df_mutation["month"] <= end_month)
# ]
#df_mutation = df_mutation[df_mutation["acco_type"].isin(selection_list_accos)]
#st.write(f"{year=}, {start_month=}, {end_month=} {selection_list_accos=}")
df_mutation = make_date_columns(df_mutation)
# add turnover info
df_prijzen_stacked = retrieve_prijzen()
df_mutations_met_omzet = pd.merge(
df_mutation,
df_prijzen_stacked,
how="inner",
on=["acco_type", "month_str"],
)
df_mutations_met_omzet["omzet"] = (
df_mutations_met_omzet["in_house"]
* df_mutations_met_omzet["price_per_night"]
)
# placeholder_what.empty()
# placeholder_progress.empty()
return df_mutations_met_omzet
def make_date_columns(df):
datefields = ["date", "checkin_date", "Arrival Date"]
for d in datefields:
try:
df["date"] = pd.to_datetime(df[d], format="%Y-%m-%d")
except Exception:
pass
df["year"] = df["date"].dt.strftime("%Y")
df["year_int"] = df["date"].dt.strftime("%Y").astype(int)
df["month"] = df["date"].dt.strftime("%m").astype(str).str.zfill(2)
df["day"] = df["date"].dt.strftime("%d").astype(str).str.zfill(2)
df["month_day"] = df["month"] + "-" + df["day"]
df["day_month"] = df["day"] + "-" + df["month"]
df["date_str"] = df["date"].astype(str)
df["date_"] = pd.to_datetime(df["month_day"], format="%m-%d")
# convert the date column to a datetime data type
return df
def make_occupuation_graph(df___):
"""_summary_
GIVES AN ERROR ValueError: Index contains duplicate entries, cannot reshape
Args:
df_ (_type_): _description_
"""
st.subheader("Occupation all accomodationtypes, all years")
df_grouped_by_date_year = df___.groupby(["year","date", "day_month"])[["aantal", "in_house"]].sum().sort_values(by="date").reset_index()
df_grouped_by_date_year["occupation"] = round(df_grouped_by_date_year["in_house"]/ df_grouped_by_date_year["aantal"]*100,1)
df_grouped_by_date_year["day_month_dt"] = pd.to_datetime(df_grouped_by_date_year["day_month"], format="%d-%m")
pivot_table = df_grouped_by_date_year.pivot_table(index="day_month_dt", columns="year", values="occupation")
figz = go.Figure()
for column in pivot_table.columns:
figz.add_trace(go.Scatter(x=pivot_table.index, y=pivot_table[column], name=str(column)))
figz.update_layout(xaxis_tickformat="%d-%b") # Display only the day and month on x-axis