Skip to content

core

Modules:

Name Description
auth

Module with classes and functions used for authentication and password handling.

gui

Module that defines main graphic interface and backend graphic interface.

models

Module with database tables definitions.

Functions:

Name Description
backend_submit_password

Submit password to database from backend but used also from frontend as

build_menu

Read menu from file (Excel or image) and upload menu items to database menu table.

change_order_time_takeaway

Change the time and the takeaway flag of an existing order.

clean_tables

Clean tables that should be reset when a new menu is uploaded.

delete_files

Delete local temporary files.

delete_order

Delete an existing order.

df_list_by_lunch_time

Build a dictionary of dataframes for each lunch-time, with takeaways included in a dedicated dataframe.

download_dataframe

Build an Excel file with tables representing orders for every lunch-time/takeaway-time.

get_host_name

Return hostname.

reload_menu

Main core function that sync Panel widget with database tables.

send_order

Upload orders and user to database tables.

set_guest_user_password

If guest user is active return a password, otherwise return an empty string.

submit_password

Same as backend_submit_password with an additional check on old

Attributes:

Name Type Description
__version__ str

Data-Lunch version.

log Logger

Module logger.

__version__ module-attribute

__version__: str = '3.4.0'

Data-Lunch version.

log module-attribute

log: Logger = getLogger(__name__)

Module logger.

backend_submit_password

backend_submit_password(
    gi: GraphicInterface | BackendInterface,
    config: DictConfig,
    user: str = None,
    is_guest: bool | None = None,
    is_admin: bool | None = None,
    logout_on_success: bool = False,
) -> bool

Submit password to database from backend but used also from frontend as part of submit_password function.

When used for backend is_guest and is_admin are selected from a widget. When called from frontend they are None and the function read them from database using the user input.

Parameters:

Name Type Description Default
gi GraphicInterface | BackendInterface

graphic interface object (used to interact with Panel widgets).

required
config DictConfig

Hydra configuration dictionary.

required
user str

username. Defaults to None.

None
is_guest bool | None

guest flag (true if guest). Defaults to None.

None
is_admin bool | None

admin flag (true if admin). Defaults to None.

None
logout_on_success bool

set to true to force logout once the new password is set. Defaults to False.

False

Returns:

Type Description
bool

true if successful, false otherwise.

Source code in dlunch/core.py
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
def backend_submit_password(
    gi: gui.GraphicInterface | gui.BackendInterface,
    config: DictConfig,
    user: str = None,
    is_guest: bool | None = None,
    is_admin: bool | None = None,
    logout_on_success: bool = False,
) -> bool:
    """Submit password to database from backend but used also from frontend as
    part of `submit_password` function.

    When used for backend `is_guest` and `is_admin` are selected from a widget.
    When called from frontend they are `None` and the function read them from
    database using the user input.

    Args:
        gi (gui.GraphicInterface | gui.BackendInterface): graphic interface object (used to interact with Panel widgets).
        config (DictConfig): Hydra configuration dictionary.
        user (str, optional): username. Defaults to None.
        is_guest (bool | None, optional): guest flag (true if guest). Defaults to None.
        is_admin (bool | None, optional): admin flag (true if admin). Defaults to None.
        logout_on_success (bool, optional): set to true to force logout once the new password is set. Defaults to False.

    Returns:
        bool: true if successful, false otherwise.
    """
    # Check if user is passed, otherwise check if backend widget
    # (password_widget.object.user) is available
    if not user:
        username = gi.password_widget._widgets["user"].value_input
    else:
        username = user
    # Get all passwords, updated at each key press
    new_password_key_press = gi.password_widget._widgets[
        "new_password"
    ].value_input
    repeat_new_password_key_press = gi.password_widget._widgets[
        "repeat_new_password"
    ].value_input
    # Check if new password match repeat password
    if username:
        if new_password_key_press == repeat_new_password_key_press:
            # Check if new password is valid with regex
            if re.fullmatch(
                config.basic_auth.psw_regex,
                new_password_key_press,
            ):
                # If is_guest and is_admin are None (not passed) use the ones
                # already set for the user
                if is_guest is None:
                    is_guest = auth.is_guest(user=user, config=config)
                if is_admin is None:
                    is_admin = auth.is_admin(user=user, config=config)
                # Add a privileged users only if guest option is not active
                if not is_guest:
                    auth.add_privileged_user(
                        user=username,
                        is_admin=is_admin,
                        config=config,
                    )
                # Green light: update the password!
                auth.add_user_hashed_password(
                    user=username,
                    password=new_password_key_press,
                    config=config,
                )

                # Logout if requested
                if logout_on_success:
                    pn.state.notifications.success(
                        "Password updated<br>Logging out",
                        duration=config.panel.notifications.duration,
                    )
                    sleep(4)
                    auth.force_logout()
                else:
                    pn.state.notifications.success(
                        "Password updated",
                        duration=config.panel.notifications.duration,
                    )
                return True

            else:
                pn.state.notifications.error(
                    "Password requirements not satisfied<br>Check again!",
                    duration=config.panel.notifications.duration,
                )

        else:
            pn.state.notifications.error(
                "Password are different!",
                duration=config.panel.notifications.duration,
            )
    else:
        pn.state.notifications.error(
            "Missing user!",
            duration=config.panel.notifications.duration,
        )

    return False

build_menu

build_menu(
    event: Event,
    config: DictConfig,
    app: Template,
    gi: GraphicInterface,
) -> None

Read menu from file (Excel or image) and upload menu items to database menu table.

Parameters:

Name Type Description Default
event Event

Panel button event.

required
config DictConfig

Hydra configuration dictionary.

required
app Template

Panel app template (used to open modal windows in case of database errors).

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required
Source code in dlunch/core.py
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
def build_menu(
    event: param.parameterized.Event,
    config: DictConfig,
    app: pn.Template,
    gi: gui.GraphicInterface,
) -> None:
    """Read menu from file (Excel or image) and upload menu items to database `menu` table.

    Args:
        event (param.parameterized.Event): Panel button event.
        config (DictConfig): Hydra configuration dictionary.
        app (pn.Template): Panel app template (used to open modal windows in case of database errors).
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).
    """
    # Hide messages
    gi.error_message.visible = False

    # Build image path
    menu_filename = str(
        pathlib.Path(config.db.shared_data_folder) / config.panel.file_name
    )

    # Delete menu file if exist (every extension)
    delete_files(config)

    # Load file from widget
    if gi.file_widget.value is not None:
        # Find file extension
        file_ext = pathlib.PurePath(gi.file_widget.filename).suffix

        # Save file locally
        local_menu_filename = menu_filename + file_ext
        gi.file_widget.save(local_menu_filename)

        # Clean tables
        clean_tables(config)

        # File can be either an excel file or an image
        if file_ext == ".png" or file_ext == ".jpg" or file_ext == ".jpeg":
            # Transform image into a pandas DataFrame
            # Open image with PIL
            img = Image.open(local_menu_filename)
            # Extract text from image
            text = pytesseract.image_to_string(img, lang="ita")
            # Process rows (rows that are completely uppercase are section titles)
            rows = [
                row for row in text.split("\n") if row and not row.isupper()
            ]
            df = pd.DataFrame({"item": rows})
            # Concat additional items
            df = pd.concat(
                [
                    df,
                    pd.DataFrame(
                        {
                            "item": [
                                item["name"]
                                for item in config.panel.additional_items_to_concat
                            ]
                        }
                    ),
                ],
                axis="index",
            )

        elif file_ext == ".xlsx":
            log.info("excel file uploaded")
            df = pd.read_excel(
                local_menu_filename, names=["item"], header=None
            )
            # Concat additional items
            df = pd.concat(
                [
                    df,
                    pd.DataFrame(
                        {
                            "item": [
                                item["name"]
                                for item in config.panel.additional_items_to_concat
                            ]
                        }
                    ),
                ],
                axis="index",
                ignore_index=True,
            )
        else:
            df = pd.DataFrame()
            pn.state.notifications.error(
                "Wrong file type", duration=config.panel.notifications.duration
            )
            log.warning("wrong file type")
            return

        # Upload to database menu table
        engine = models.create_engine(config)
        try:
            df.drop_duplicates(subset="item").to_sql(
                models.Menu.__tablename__,
                engine,
                schema=config.db.get("schema", models.SCHEMA),
                index=False,
                if_exists="append",
            )
            # Update dataframe widget
            reload_menu(
                None,
                config,
                gi,
            )

            pn.state.notifications.success(
                "Menu uploaded", duration=config.panel.notifications.duration
            )
            log.info("menu uploaded")
        except Exception as e:
            # Any exception here is a database fault
            pn.state.notifications.error(
                "Database error", duration=config.panel.notifications.duration
            )
            gi.error_message.object = (
                f"DATABASE ERROR<br><br>ERROR:<br>{str(e)}"
            )
            gi.error_message.visible = True
            log.warning("database error")
            # Open modal window
            app.open_modal()

    else:
        pn.state.notifications.warning(
            "No file selected", duration=config.panel.notifications.duration
        )
        log.warning("no file selected")

change_order_time_takeaway

change_order_time_takeaway(
    event: Event,
    config: DictConfig,
    person: Person,
    gi: GraphicInterface,
) -> None

Change the time and the takeaway flag of an existing order.

Parameters:

Name Type Description Default
event Event

Panel button event.

required
config DictConfig

Hydra configuration dictionary.

required
person Person

class that collect order data for the user that is the target of the order.

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required
Source code in dlunch/core.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def change_order_time_takeaway(
    event: param.parameterized.Event,
    config: DictConfig,
    person: gui.Person,
    gi: gui.GraphicInterface,
) -> None:
    """Change the time and the takeaway flag of an existing order.

    Args:
        event (param.parameterized.Event): Panel button event.
        config (DictConfig): Hydra configuration dictionary.
        person (gui.Person): class that collect order data for the user that is the target of the order.
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).
    """
    # Get username, updated on every keypress
    username_key_press = gi.person_widget._widgets["username"].value_input

    # Create session
    session = models.create_session(config)

    with session:
        # Check if the "no more order" toggle button is pressed
        if models.get_flag(config=config, id="no_more_orders"):
            pn.state.notifications.error(
                "It is not possible to update orders (time)",
                duration=config.panel.notifications.duration,
            )

            # Reload the menu
            reload_menu(
                None,
                config,
                gi,
            )

            return

        if username_key_press:
            # Build and execute the update statement
            update_statement = (
                update(models.Users)
                .where(models.Users.id == username_key_press)
                .values(lunch_time=person.lunch_time, takeaway=person.takeaway)
                .returning(models.Users)
            )

            updated_user = session.scalars(update_statement).one_or_none()

            session.commit()

            if updated_user:
                # Find updated values
                updated_time = updated_user.lunch_time
                updated_takeaway = (
                    (" " + config.panel.gui.takeaway_id)
                    if updated_user.takeaway
                    else ""
                )
                updated_items_names = [
                    order.menu_item.item for order in updated_user.orders
                ]
                # Update dataframe widget
                reload_menu(
                    None,
                    config,
                    gi,
                )

                pn.state.notifications.success(
                    f"{username_key_press}'s<br>lunch time changed to<br>{updated_time}{updated_takeaway}<br>({', '.join(updated_items_names)})",
                    duration=config.panel.notifications.duration,
                )
                log.info(f"{username_key_press}'s order updated")
            else:
                pn.state.notifications.warning(
                    f'No order for user named<br>"{username_key_press}"',
                    duration=config.panel.notifications.duration,
                )
                log.info(f"no order for user named {username_key_press}")
        else:
            pn.state.notifications.warning(
                "Please insert user name",
                duration=config.panel.notifications.duration,
            )
            log.warning("missing username")

clean_tables

clean_tables(config: DictConfig) -> None

Clean tables that should be reset when a new menu is uploaded.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required
Source code in dlunch/core.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def clean_tables(config: DictConfig) -> None:
    """Clean tables that should be reset when a new menu is uploaded.

    Args:
        config (DictConfig): Hydra configuration dictionary.
    """
    # Clean tables
    # Clean orders
    models.Orders.clear(config=config)
    # Clean menu
    models.Menu.clear(config=config)
    # Clean users
    models.Users.clear(config=config)
    # Clean flags
    models.Flags.clear_guest_override(config=config)
    # Reset flags
    models.set_flag(config=config, id="no_more_orders", value=False)
    log.info("reset values in table 'flags'")
    # Clean cache
    pn.state.clear_caches()
    log.info("cache cleaned")

delete_files

delete_files(config: DictConfig) -> None

Delete local temporary files.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required
Source code in dlunch/core.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def delete_files(config: DictConfig) -> None:
    """Delete local temporary files.

    Args:
        config (DictConfig): Hydra configuration dictionary.
    """
    # Delete menu file if exist (every extension)
    files = list(
        pathlib.Path(config.db.shared_data_folder).glob(
            config.panel.file_name + "*"
        )
    )
    log.info(f"delete files {', '.join([f.name for f in files])}")
    for file in files:
        file.unlink(missing_ok=True)

delete_order

delete_order(
    event: Event,
    config: DictConfig,
    app: Template,
    gi: GraphicInterface,
) -> None

Delete an existing order.

Consistency checks about the user and the order are carried out here (existing user, only one order, etc.). The status of the stop_orders flag is checked to avoid that an order is uploaded when it shouldn't.

In addition privileges are taken into account (guest users cannot delete orders that targets a privileged user).

Parameters:

Name Type Description Default
event Event

Panel button event.

required
config DictConfig

Hydra configuration dictionary.

required
app Template

Panel app template (used to open modal windows in case of database errors).

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required
Source code in dlunch/core.py
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
def delete_order(
    event: param.parameterized.Event,
    config: DictConfig,
    app: pn.Template,
    gi: gui.GraphicInterface,
) -> None:
    """Delete an existing order.

    Consistency checks about the user and the order are carried out here (existing user, only one order, etc.).
    The status of the `stop_orders` flag is checked to avoid that an order is uploaded when it shouldn't.

    In addition privileges are taken into account (guest users cannot delete orders that targets a privileged user).

    Args:
        event (param.parameterized.Event): Panel button event.
        config (DictConfig): Hydra configuration dictionary.
        app (pn.Template): Panel app template (used to open modal windows in case of database errors).
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).
    """
    # Get username, updated on every keypress
    username_key_press = gi.person_widget._widgets["username"].value_input

    # Hide messages
    gi.error_message.visible = False

    # Create session
    session = models.create_session(config)

    with session:
        # Check if the "no more order" toggle button is pressed
        if models.get_flag(config=config, id="no_more_orders"):
            pn.state.notifications.error(
                "It is not possible to delete orders",
                duration=config.panel.notifications.duration,
            )

            # Reload the menu
            reload_menu(
                None,
                config,
                gi,
            )

            return

        if username_key_press:
            # If auth is active, check if a guests is deleting an order of a
            # privileged user
            if (
                auth.is_guest(user=pn_user(config), config=config)
                and (username_key_press in auth.list_users(config=config))
                and (auth.is_auth_active(config=config))
            ):
                pn.state.notifications.error(
                    f"You do not have enough privileges<br>to delete<br>{username_key_press}'s order",
                    duration=config.panel.notifications.duration,
                )

                # Reload the menu
                reload_menu(
                    None,
                    config,
                    gi,
                )

                return

            # Delete user
            try:
                num_rows_deleted_users = session.execute(
                    delete(models.Users).where(
                        models.Users.id == username_key_press
                    )
                )
                # Delete also orders (hotfix for Debian)
                num_rows_deleted_orders = session.execute(
                    delete(models.Orders).where(
                        models.Orders.user == username_key_press
                    )
                )
                session.commit()
                if (num_rows_deleted_users.rowcount > 0) or (
                    num_rows_deleted_orders.rowcount > 0
                ):
                    # Update dataframe widget
                    reload_menu(
                        None,
                        config,
                        gi,
                    )

                    pn.state.notifications.success(
                        "Order canceled",
                        duration=config.panel.notifications.duration,
                    )
                    log.info(f"{username_key_press}'s order canceled")
                else:
                    pn.state.notifications.warning(
                        f'No order for user named<br>"{username_key_press}"',
                        duration=config.panel.notifications.duration,
                    )
                    log.info(f"no order for user named {username_key_press}")
            except Exception as e:
                # Any exception here is a database fault
                pn.state.notifications.error(
                    "Database error",
                    duration=config.panel.notifications.duration,
                )
                gi.error_message.object = (
                    f"DATABASE ERROR<br><br>ERROR:<br>{str(e)}"
                )
                gi.error_message.visible = True
                log.error("database error")
                # Open modal window
                app.open_modal()
        else:
            pn.state.notifications.warning(
                "Please insert user name",
                duration=config.panel.notifications.duration,
            )
            log.warning("missing username")

df_list_by_lunch_time

df_list_by_lunch_time(config: DictConfig) -> dict

Build a dictionary of dataframes for each lunch-time, with takeaways included in a dedicated dataframe.

Each datframe includes orders grouped by users, notes and a total column (with the total value for a specific item).

The keys of the dataframe are lunch-times and lunch-times + takeaway_id.

Parameters:

Name Type Description Default
config DictConfig

description

required

Returns:

Type Description
dict

dictionary with dataframes summarizing the orders for each lunch-time/takeaway-time.

Source code in dlunch/core.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
def df_list_by_lunch_time(
    config: DictConfig,
) -> dict:
    """Build a dictionary of dataframes for each lunch-time, with takeaways included in a dedicated dataframe.

    Each datframe includes orders grouped by users, notes and a total column (with the total value
    for a specific item).

    The keys of the dataframe are `lunch-times` and `lunch-times + takeaway_id`.

    Args:
        config (DictConfig): _description_

    Returns:
        dict: dictionary with dataframes summarizing the orders for each lunch-time/takeaway-time.
    """
    # Create database engine and session
    engine = models.create_engine(config)
    # Read menu and save how menu items are sorted (first courses, second courses, etc.)
    original_order = models.Menu.read_as_df(
        config=config,
        index_col="id",
    ).item
    # Create session
    session = models.create_session(config)

    with session:
        # Build takeaway list
        takeaway_list = [
            user.id
            for user in session.scalars(
                select(models.Users).where(models.Users.takeaway == sql_true())
            ).all()
        ]
    # Read dataframe (including notes)
    df = pd.read_sql_query(
        config.db.orders_query.format(
            schema=config.db.get("schema", models.SCHEMA)
        ),
        engine,
    )

    # Build a dict of dataframes, one for each lunch time
    df_dict = {}
    for time in df.lunch_time.sort_values().unique():
        # Take only one lunch time (and remove notes so they do not alter
        # numeric counters inside the pivot table)
        temp_df = (
            df[df.lunch_time == time]
            .drop(columns=["lunch_time", "note"])
            .reset_index(drop=True)
        )
        # Users' selections
        df_users = temp_df.pivot_table(
            index="item", columns="user", aggfunc=len
        )
        # Reorder index in accordance with original menu
        df_users = df_users.reindex(original_order)
        # Split restaurant lunches from takeaway lunches
        df_users_restaurant = df_users.loc[
            :, [c for c in df_users.columns if c not in takeaway_list]
        ]
        df_users_takeaways = df_users.loc[
            :, [c for c in df_users.columns if c in takeaway_list]
        ]

        # The following function prepare the dataframe before saving it into
        # the dictionary that will be returned
        def clean_up_table(
            config: DictConfig, df_in: pd.DataFrame, df_complete: pd.DataFrame
        ):
            df = df_in.copy()
            # Group notes per menu item by concat users notes
            # Use value counts to keep track of how many time a note is repeated
            df_notes = (
                df_complete[
                    (df_complete.lunch_time == time)
                    & (df_complete.note != "")
                    & (df_complete.user.isin(df.columns))
                ]
                .drop(columns=["user", "lunch_time"])
                .value_counts()
                .reset_index(level="note")
            )
            df_notes.note = (
                df_notes["count"]
                .astype(str)
                .str.cat(df_notes.note, sep=config.panel.gui.note_sep.count)
            )
            df_notes = df_notes.drop(columns="count")
            df_notes = (
                df_notes.groupby("item")["note"]
                .apply(config.panel.gui.note_sep.element.join)
                .to_frame()
            )
            # Add columns of totals
            df[config.panel.gui.total_column_name] = df.sum(axis=1)
            # Drop unused rows if requested
            if config.panel.drop_unused_menu_items:
                df = df[df[config.panel.gui.total_column_name] > 0]
            # Add notes
            df = df.join(df_notes)
            df = df.rename(columns={"note": config.panel.gui.note_column_name})
            # Change NaNs to '-'
            df = df.fillna("-")
            # Avoid mixed types (float and notes str)
            df = df.astype(object)

            return df

        # Clean and add resulting dataframes to dict
        # RESTAURANT LUNCH
        if not df_users_restaurant.empty:
            df_users_restaurant = clean_up_table(
                config, df_users_restaurant, df
            )
            df_dict[time] = df_users_restaurant
        # TAKEAWAY
        if not df_users_takeaways.empty:
            df_users_takeaways = clean_up_table(config, df_users_takeaways, df)
            df_dict[f"{time} {config.panel.gui.takeaway_id}"] = (
                df_users_takeaways
            )

    return df_dict

download_dataframe

download_dataframe(
    config: DictConfig, gi: GraphicInterface
) -> BytesIO

Build an Excel file with tables representing orders for every lunch-time/takeaway-time.

Tables are created by the function df_list_by_lunch_time and exported on dedicated Excel worksheets (inside the same workbook).

The result is returned as bytes stream to satisfy panel.widgets.FileDownload class requirements.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required

Returns:

Type Description
BytesIO

download stream for the Excel file.

Source code in dlunch/core.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
def download_dataframe(
    config: DictConfig,
    gi: gui.GraphicInterface,
) -> BytesIO:
    """Build an Excel file with tables representing orders for every lunch-time/takeaway-time.

    Tables are created by the function `df_list_by_lunch_time` and exported on dedicated Excel worksheets
    (inside the same workbook).

    The result is returned as bytes stream to satisfy panel.widgets.FileDownload class requirements.

    Args:
        config (DictConfig): Hydra configuration dictionary.
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).

    Returns:
        BytesIO: download stream for the Excel file.
    """

    # Build a dict of dataframes, one for each lunch time (the key contains
    # a lunch time)
    df_dict = df_list_by_lunch_time(config)
    # Export one dataframe for each lunch time
    bytes_io = BytesIO()
    writer = pd.ExcelWriter(bytes_io)
    # If the dataframe dict is non-empty export one dataframe for each sheet
    if df_dict:
        for time, df in df_dict.items():
            log.info(f"writing sheet {time}")

            # Find users that placed an order for a given time
            users_n = len(
                [
                    c
                    for c in df.columns
                    if c
                    not in (
                        config.panel.gui.total_column_name,
                        config.panel.gui.note_column_name,
                    )
                ]
            )

            # Export dataframe to new sheet
            worksheet_name = time.replace(":", ".")
            df.to_excel(writer, sheet_name=worksheet_name, startrow=1)
            # Add title
            worksheet = writer.sheets[worksheet_name]
            worksheet.cell(
                1,
                1,
                f"Time - {time} | # {users_n}",
            )

            # HEADER FORMAT
            worksheet["A1"].font = Font(size=13, bold=True, color="00FF0000")

            # INDEX ALIGNMENT
            for row in worksheet[worksheet.min_row : worksheet.max_row]:
                cell = row[0]  # column A
                cell.alignment = Alignment(horizontal="left")
                cell = row[users_n + 2]  # column note
                cell.alignment = Alignment(horizontal="left")
                cells = row[1 : users_n + 2]  # from column B to note-1
                for cell in cells:
                    cell.alignment = Alignment(horizontal="center")

            # AUTO SIZE
            # Set auto-size for all columns
            # Use end +1 for ID column, and +2 for 'total' and 'note' columns
            column_letters = get_column_interval(start=1, end=users_n + 1 + 2)
            # Get columns
            columns = worksheet[column_letters[0] : column_letters[-1]]
            for column_letter, column in zip(column_letters, columns):
                # Instantiate max length then loop on cells to find max value
                max_length = 0
                # Cell loop
                for cell in column:
                    log.debug(
                        f"autosize for cell {cell.coordinate} with value '{cell.value}'"
                    )
                    try:  # Necessary to avoid error on empty cells
                        if len(str(cell.value)) > max_length:
                            max_length = len(cell.value)
                            log.debug(f"new max length set to {max_length}")
                    except Exception:
                        log.debug("empty cell")
                log.debug(f"final max length is {max_length}")
                adjusted_width = (max_length + 2) * 0.85
                log.debug(
                    f"adjusted width for column '{column_letter}' is {adjusted_width}"
                )
                worksheet.column_dimensions[column_letter].width = (
                    adjusted_width
                )
            # Since grouping fix width equal to first column width (openpyxl
            # bug), set first column of users' order equal to max width of
            # all users columns to avoid issues
            max_width = 0
            log.debug(
                f"find max width for users' columns '{column_letters[1]}:{column_letters[-3]}'"
            )
            for column_letter in column_letters[1:-2]:
                max_width = max(
                    max_width, worksheet.column_dimensions[column_letter].width
                )
            log.debug(f"max width for first users' columns is {max_width}")
            worksheet.column_dimensions[column_letters[1]].width = max_width

            # GROUPING
            # Group and hide columns, leave only ID, total and note
            column_letters = get_column_interval(start=2, end=users_n + 1)
            worksheet.column_dimensions.group(
                column_letters[0], column_letters[-1], hidden=True
            )

            # Close and reset bytes_io for the next dataframe
            writer.close()  # Important!
            bytes_io.seek(0)  # Important!

        # Message prompt
        pn.state.notifications.success(
            "File with orders downloaded",
            duration=config.panel.notifications.duration,
        )
        log.info("xlsx downloaded")
    else:
        gi.dataframe.value.drop(columns=["order"]).to_excel(
            writer, sheet_name="MENU", index=False
        )
        writer.close()  # Important!
        bytes_io.seek(0)  # Important!
        # Message prompt
        pn.state.notifications.warning(
            "No order<br>Menu downloaded",
            duration=config.panel.notifications.duration,
        )
        log.warning(
            "no order, menu exported to excel in place of orders' list"
        )

    return bytes_io

get_host_name

get_host_name(config: DictConfig) -> str

Return hostname.

This function behavior changes if called from localhost, Docker container or production server.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required

Returns:

Type Description
str

hostname.

Source code in dlunch/core.py
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
def get_host_name(config: DictConfig) -> str:
    """Return hostname.

    This function behavior changes if called from localhost, Docker container or
    production server.

    Args:
        config (DictConfig): Hydra configuration dictionary.

    Returns:
        str: hostname.
    """
    try:
        ip_address = socket.gethostbyname(socket.gethostname())
        dig_res = subprocess.run(
            ["dig", "+short", "-x", ip_address], stdout=subprocess.PIPE
        ).stdout
        host_name = (
            subprocess.run(
                ["cut", "-d.", "-f1"], stdout=subprocess.PIPE, input=dig_res
            )
            .stdout.decode("utf-8")
            .strip()
        )
        if host_name:
            host_name = host_name.replace(f"{config.docker_username}_", "")
        else:
            host_name = "no info"
    except Exception:
        host_name = "not available"

    return host_name

reload_menu

reload_menu(
    event: Event, config: DictConfig, gi: GraphicInterface
) -> None

Main core function that sync Panel widget with database tables.

Stop orders and guest override checks are carried out by this function. Also the banner image is shown based on a check run by this function.

menu, orders and users tables are used to build a list of orders for each lunch time. Takeaway orders are evaluated separately.

At the end stats about lunches are calculated and loaded to database. Finally statistics (values and table) shown inside the app are updated accordingly.

Parameters:

Name Type Description Default
event Event

Panel button event.

required
config DictConfig

Hydra configuration dictionary.

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required
Source code in dlunch/core.py
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
def reload_menu(
    event: param.parameterized.Event,
    config: DictConfig,
    gi: gui.GraphicInterface,
) -> None:
    """Main core function that sync Panel widget with database tables.

    Stop orders and guest override checks are carried out by this function.
    Also the banner image is shown based on a check run by this function.

    `menu`, `orders` and `users` tables are used to build a list of orders for each lunch time.
    Takeaway orders are evaluated separately.

    At the end stats about lunches are calculated and loaded to database. Finally
    statistics (values and table) shown inside the app are updated accordingly.

    Args:
        event (param.parameterized.Event): Panel button event.
        config (DictConfig): Hydra configuration dictionary.
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).
    """
    # Create session
    session = models.create_session(config)

    with session:
        # Check if someone changed the "no_more_order" toggle
        if gi.toggle_no_more_order_button.value != models.get_flag(
            config=config, id="no_more_orders"
        ):
            # The following statement will trigger the toggle callback
            # which will call reload_menu once again
            # This is the reason why this if contains a return (without the return
            # the content will be reloaded twice)
            gi.toggle_no_more_order_button.value = models.get_flag(
                config=config, id="no_more_orders"
            )

            return

        # Check guest override button status (if not in table use False)
        gi.toggle_guest_override_button.value = models.get_flag(
            config=config,
            id=f"{pn_user(config)}_guest_override",
            value_if_missing=False,
        )

        # Set no more orders toggle button and the change order time button
        # visibility and activation
        if auth.is_guest(
            user=pn_user(config), config=config, allow_override=False
        ):
            # Deactivate the no_more_orders_button for guest users
            gi.toggle_no_more_order_button.disabled = True
            gi.toggle_no_more_order_button.visible = False
            # Deactivate the change_order_time_button for guest users
            gi.change_order_time_takeaway_button.disabled = True
            gi.change_order_time_takeaway_button.visible = False
        else:
            # Activate the no_more_orders_button for privileged users
            gi.toggle_no_more_order_button.disabled = False
            gi.toggle_no_more_order_button.visible = True
            # Show the change_order_time_button for privileged users
            # It is disabled by the no more order button if necessary
            gi.change_order_time_takeaway_button.visible = True

        # Guest graphic configuration
        if auth.is_guest(user=pn_user(config), config=config):
            # If guest show guest type selection group
            gi.person_widget.widgets["guest"].disabled = False
            gi.person_widget.widgets["guest"].visible = True
        else:
            # If user is privileged hide guest type selection group
            gi.person_widget.widgets["guest"].disabled = True
            gi.person_widget.widgets["guest"].visible = False

        # Reload menu
        engine = models.create_engine(config)
        df = models.Menu.read_as_df(
            config=config,
            index_col="id",
        )
        # Add order (for selecting items) and note columns
        df["order"] = False
        df[config.panel.gui.note_column_name] = ""
        gi.dataframe.value = df
        gi.dataframe.formatters = {"order": {"type": "tickCross"}}
        gi.dataframe.editors = {
            "id": None,
            "item": None,
            "order": CheckboxEditor(),
            config.panel.gui.note_column_name: "input",
        }
        gi.dataframe.header_align = OmegaConf.to_container(
            config.panel.gui.menu_column_align, resolve=True
        )
        gi.dataframe.text_align = OmegaConf.to_container(
            config.panel.gui.menu_column_align, resolve=True
        )

        if gi.toggle_no_more_order_button.value:
            gi.dataframe.hidden_columns = ["id", "order"]
            gi.dataframe.disabled = True
        else:
            gi.dataframe.hidden_columns = ["id"]
            gi.dataframe.disabled = False

        # If menu is empty show banner image, otherwise show menu
        if df.empty:
            gi.no_menu_col.visible = True
            gi.main_header_row.visible = False
            gi.quote.visible = False
            gi.menu_flexbox.visible = False
            gi.buttons_flexbox.visible = False
            gi.results_divider.visible = False
            gi.res_col.visible = False
        else:
            gi.no_menu_col.visible = False
            gi.main_header_row.visible = True
            gi.quote.visible = True
            gi.menu_flexbox.visible = True
            gi.buttons_flexbox.visible = True
            gi.results_divider.visible = True
            gi.res_col.visible = True

        log.debug("menu reloaded")

        # Load results
        df_dict = df_list_by_lunch_time(config)
        # Clean columns and load text and dataframes
        gi.res_col.clear()
        gi.time_col.clear()
        if df_dict:
            # Titles
            gi.res_col.append(config.panel.result_column_text)
            gi.time_col.append(gi.time_col_title)
            # Build guests list (one per each guest types)
            guests_lists = {}
            for guest_type in config.panel.guest_types:
                guests_lists[guest_type] = [
                    user.id
                    for user in session.scalars(
                        select(models.Users).where(
                            models.Users.guest == guest_type
                        )
                    ).all()
                ]
            # Loop through lunch times
            for time, df in df_dict.items():
                # Find the number of grumbling stomachs
                grumbling_stomachs = len(
                    [
                        c
                        for c in df.columns
                        if c
                        not in (
                            config.panel.gui.total_column_name,
                            config.panel.gui.note_column_name,
                        )
                    ]
                )
                # Set different graphics for takeaway lunches
                if config.panel.gui.takeaway_id in time:
                    res_col_label_kwargs = {
                        "time": time.replace(config.panel.gui.takeaway_id, ""),
                        "diners_n": grumbling_stomachs,
                        "emoji": config.panel.gui.takeaway_emoji,
                        "is_takeaway": True,
                        "takeaway_alert_sign": f"&nbsp{gi.takeaway_alert_sign}&nbsp{gi.takeaway_alert_text}",
                        "css_classes": OmegaConf.to_container(
                            config.panel.gui.takeaway_class_res_col,
                            resolve=True,
                        ),
                        "stylesheets": [
                            config.panel.gui.css_files.labels_path
                        ],
                    }
                    time_col_label_kwargs = {
                        "time": time.replace(config.panel.gui.takeaway_id, ""),
                        "diners_n": str(grumbling_stomachs) + "&nbsp",
                        "separator": "<br>",
                        "emoji": config.panel.gui.takeaway_emoji,
                        "align": ("center", "center"),
                        "sizing_mode": "stretch_width",
                        "is_takeaway": True,
                        "takeaway_alert_sign": gi.takeaway_alert_sign,
                        "css_classes": OmegaConf.to_container(
                            config.panel.gui.takeaway_class_time_col,
                            resolve=True,
                        ),
                        "stylesheets": [
                            config.panel.gui.css_files.labels_path
                        ],
                    }
                else:
                    res_col_label_kwargs = {
                        "time": time,
                        "diners_n": grumbling_stomachs,
                        "emoji": random.choice(config.panel.gui.food_emoji),
                        "css_classes": OmegaConf.to_container(
                            config.panel.gui.time_class_res_col, resolve=True
                        ),
                        "stylesheets": [
                            config.panel.gui.css_files.labels_path
                        ],
                    }
                    time_col_label_kwargs = {
                        "time": time,
                        "diners_n": str(grumbling_stomachs) + "&nbsp",
                        "separator": "<br>",
                        "emoji": config.panel.gui.restaurant_emoji,
                        "per_icon": "&#10006; ",
                        "align": ("center", "center"),
                        "sizing_mode": "stretch_width",
                        "css_classes": OmegaConf.to_container(
                            config.panel.gui.time_class_time_col, resolve=True
                        ),
                        "stylesheets": [
                            config.panel.gui.css_files.labels_path
                        ],
                    }
                # Add text to result column
                gi.res_col.append(pn.Spacer(height=15))
                gi.res_col.append(gi.build_time_label(**res_col_label_kwargs))
                # Add non editable table to result column
                gi.res_col.append(pn.Spacer(height=5))
                gi.res_col.append(
                    gi.build_order_table(
                        config, df=df, time=time, guests_lists=guests_lists
                    )
                )
                # Add also a label to lunch time column
                gi.time_col.append(
                    gi.build_time_label(**time_col_label_kwargs)
                )

        log.debug("results reloaded")

        # Clean stats column
        gi.sidebar_stats_col.clear()
        # Update stats
        # Find how many people eat today (total number) and add value to database
        # stats table (when adding a stats if guest is not specified None is used
        # as default)
        today_locals_count = session.scalar(
            select(func.count(models.Users.id)).where(
                models.Users.guest == "NotAGuest"
            )
        )
        new_stat = models.Stats(hungry_people=today_locals_count)
        # Use an upsert for postgresql, a simple session add otherwise
        models.session_add_with_upsert(
            session=session, constraint="stats_pkey", new_record=new_stat
        )
        # For each guest type find how many guests eat today
        for guest_type in config.panel.guest_types:
            today_guests_count = session.scalar(
                select(func.count(models.Users.id)).where(
                    models.Users.guest == guest_type
                )
            )
            new_stat = models.Stats(
                guest=guest_type, hungry_people=today_guests_count
            )
            # Use an upsert for postgresql, a simple session add otherwise
            models.session_add_with_upsert(
                session=session, constraint="stats_pkey", new_record=new_stat
            )

        # Commit stats
        session.commit()

        # Group stats by month and return how many people had lunch
        df_stats = pd.read_sql_query(
            config.db.stats_query.format(
                schema=config.db.get("schema", models.SCHEMA)
            ),
            engine,
        )
        # Stats top text
        stats_and_info_text = gi.build_stats_and_info_text(
            config=config,
            df_stats=df_stats,
            user=pn_user(config),
            version=__version__,
            host_name=get_host_name(config),
            stylesheets=[config.panel.gui.css_files.stats_info_path],
        )
        # Remove NotAGuest (non-guest users)
        df_stats.Guest = df_stats.Guest.replace(
            "NotAGuest", config.panel.stats_locals_column_name
        )
        # Pivot table on guest type
        df_stats = df_stats.pivot(
            columns="Guest",
            index=config.panel.stats_id_cols,
            values="Hungry People",
        ).reset_index()
        df_stats[config.panel.gui.total_column_name.title()] = df_stats.sum(
            axis="columns", numeric_only=True
        )
        # Add value and non-editable option to stats table
        gi.stats_widget.editors = {c: None for c in df_stats.columns}
        gi.stats_widget.value = df_stats
        gi.sidebar_stats_col.append(stats_and_info_text["stats"])
        gi.sidebar_stats_col.append(gi.stats_widget)
        # Add info below person widget (an empty placeholder was left as last
        # element)
        gi.sidebar_person_column.objects[-1] = stats_and_info_text["info"]
        log.debug("stats and info updated")

send_order

send_order(
    event: Event,
    config: DictConfig,
    app: Template,
    person: Person,
    gi: GraphicInterface,
) -> None

Upload orders and user to database tables.

The user target of the order is uploaded to users table, while the order is uploaded to orders table.

Consistency checks about the user and the order are carried out here (existing user, only one order, etc.). The status of the stop_orders flag is checked to avoid that an order is uploaded when it shouldn't.

Orders for guest users are marked as such before uploading them.

Parameters:

Name Type Description Default
event Event

Panel button event.

required
config DictConfig

Hydra configuration dictionary.

required
app Template

Panel app template (used to open modal windows in case of database errors).

required
person Person

class that collect order data for the user that is the target of the order.

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required
Source code in dlunch/core.py
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
def send_order(
    event: param.parameterized.Event,
    config: DictConfig,
    app: pn.Template,
    person: gui.Person,
    gi: gui.GraphicInterface,
) -> None:
    """Upload orders and user to database tables.

    The user target of the order is uploaded to `users` table, while the order
    is uploaded to `orders` table.

    Consistency checks about the user and the order are carried out here (existing user, only one order, etc.).
    The status of the `stop_orders` flag is checked to avoid that an order is uploaded when it shouldn't.

    Orders for guest users are marked as such before uploading them.

    Args:
        event (param.parameterized.Event): Panel button event.
        config (DictConfig): Hydra configuration dictionary.
        app (pn.Template): Panel app template (used to open modal windows in case of database errors).
        person (gui.Person): class that collect order data for the user that is the target of the order.
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).
    """
    # Get username updated at each key press
    username_key_press = gi.person_widget._widgets["username"].value_input

    # Hide messages
    gi.error_message.visible = False

    # Create session
    session = models.create_session(config)

    with session:
        # Check if the "no more order" toggle button is pressed
        if models.get_flag(config=config, id="no_more_orders"):
            pn.state.notifications.error(
                "It is not possible to place new orders",
                duration=config.panel.notifications.duration,
            )

            # Reload the menu
            reload_menu(
                None,
                config,
                gi,
            )

            return

        # If auth is active, check if a guests is using a name reserved to a
        # privileged user
        if (
            auth.is_guest(user=pn_user(config), config=config)
            and (username_key_press in auth.list_users(config=config))
            and (auth.is_auth_active(config=config))
        ):
            pn.state.notifications.error(
                f"{username_key_press} is a reserved name<br>Please choose a different one",
                duration=config.panel.notifications.duration,
            )

            # Reload the menu
            reload_menu(
                None,
                config,
                gi,
            )

            return

        # Check if a privileged user is ordering for an invalid name
        if (
            not auth.is_guest(user=pn_user(config), config=config)
            and (
                username_key_press
                not in (
                    name
                    for name in auth.list_users(config=config)
                    if name != "guest"
                )
            )
            and (auth.is_auth_active(config=config))
        ):
            pn.state.notifications.error(
                f"{username_key_press} is not a valid name<br>for a privileged user<br>Please choose a different one",
                duration=config.panel.notifications.duration,
            )

            # Reload the menu
            reload_menu(
                None,
                config,
                gi,
            )

            return

        # Write order into database table
        df = gi.dataframe.value.copy()
        df_order = df[df.order]
        # If username is missing or the order is empty return an error message
        if username_key_press and not df_order.empty:
            # Check if the user already placed an order
            if session.get(models.Users, username_key_press):
                pn.state.notifications.warning(
                    f"Cannot overwrite an order<br>Delete {username_key_press}'s order first and retry",
                    duration=config.panel.notifications.duration,
                )
                log.warning(f"an order already exist for {username_key_press}")
            else:
                # Place order
                try:
                    # Add User
                    # Do not pass guest for privileged users (default to NotAGuest)
                    if auth.is_guest(user=pn_user(config), config=config):
                        new_user = models.Users(
                            id=username_key_press,
                            guest=person.guest,
                            lunch_time=person.lunch_time,
                            takeaway=person.takeaway,
                        )
                    else:
                        new_user = models.Users(
                            id=username_key_press,
                            lunch_time=person.lunch_time,
                            takeaway=person.takeaway,
                        )
                    session.add(new_user)
                    session.commit()
                    # Add orders as long table (one row for each item selected by a user)
                    for row in df_order.itertuples(name="OrderTuple"):
                        # Order
                        new_order = models.Orders(
                            user=username_key_press,
                            menu_item_id=row.Index,
                            note=getattr(
                                row, config.panel.gui.note_column_name
                            ).lower(),
                        )
                        session.add(new_order)
                        session.commit()

                    # Update dataframe widget
                    reload_menu(
                        None,
                        config,
                        gi,
                    )

                    pn.state.notifications.success(
                        "Order sent",
                        duration=config.panel.notifications.duration,
                    )
                    log.info(f"{username_key_press}'s order saved")
                except Exception as e:
                    # Any exception here is a database fault
                    pn.state.notifications.error(
                        "Database error",
                        duration=config.panel.notifications.duration,
                    )
                    gi.error_message.object = (
                        f"DATABASE ERROR<br><br>ERROR:<br>{str(e)}"
                    )
                    gi.error_message.visible = True
                    log.error("database error")
                    # Open modal window
                    app.open_modal()
        else:
            if not username_key_press:
                pn.state.notifications.warning(
                    "Please insert user name",
                    duration=config.panel.notifications.duration,
                )
                log.warning("missing username")
            else:
                pn.state.notifications.warning(
                    "Please make a selection",
                    duration=config.panel.notifications.duration,
                )
                log.warning("no selection made")

set_guest_user_password

set_guest_user_password(config: DictConfig) -> str

If guest user is active return a password, otherwise return an empty string.

This function always returns an empty string if basic authentication is not active.

Guest user and basic authentication are handled through configuration files.

If the flag reset_guest_user_password is set to True the password is created and uploaded to database. Otherwise the existing password is queried from database credentials table.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required

Returns:

Type Description
str

guest user password or empty string if basic authentication is not active.

Source code in dlunch/core.py
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
def set_guest_user_password(config: DictConfig) -> str:
    """If guest user is active return a password, otherwise return an empty string.

    This function always returns an empty string if basic authentication is not active.

    Guest user and basic authentication are handled through configuration files.

    If the flag `reset_guest_user_password` is set to `True` the password is created
    and uploaded to database. Otherwise the existing password is queried from database
    `credentials` table.

    Args:
        config (DictConfig): Hydra configuration dictionary.

    Returns:
        str: guest user password or empty string if basic authentication is not active.
    """
    # Check if basic auth is active
    if auth.is_basic_auth_active(config=config):
        # If active basic_auth.guest_user is true if guest user is active
        is_guest_user_active = config.basic_auth.guest_user
        log.debug("guest user flag is {is_guest_user_active}")
    else:
        # Otherwise the guest user feature is not applicable
        is_guest_user_active = False
        log.debug("guest user not applicable")

    # Set the guest password variable
    if is_guest_user_active:
        # If flag for resetting the password does not exist use the default
        # value
        if (
            models.get_flag(config=config, id="reset_guest_user_password")
            is None
        ):
            models.set_flag(
                config=config,
                id="reset_guest_user_password",
                value=config.basic_auth.default_reset_guest_user_password_flag,
            )
        # Generate a random password only if requested (check on flag)
        # otherwise load from pickle
        if models.get_flag(config=config, id="reset_guest_user_password"):
            # Turn off reset user password (in order to reset it only once)
            # This statement also acquire a lock on database (so it is
            # called first)
            models.set_flag(
                config=config,
                id="reset_guest_user_password",
                value=False,
            )
            # Create password
            guest_password = auth.generate_password(
                special_chars=config.basic_auth.psw_special_chars,
                length=config.basic_auth.generated_psw_length,
            )
            # Add hashed password to database
            auth.add_user_hashed_password(
                "guest", guest_password, config=config
            )
        else:
            # Load from database
            session = models.create_session(config)
            with session:
                try:
                    guest_password = session.get(
                        models.Credentials, "guest"
                    ).password_encrypted.decrypt()
                except cryptography.fernet.InvalidToken:
                    # Notify exception and suggest to reset guest user password
                    guest_password = ""
                    log.warning(
                        "Unable to decrypt 'guest' user password because an invalid token has been detected: reset password from backend"
                    )
                    pn.state.notifications.warning(
                        "Unable to decrypt 'guest' user password<br>Invalid token detected: reset password from backend",
                        duration=config.panel.notifications.duration,
                    )
    else:
        guest_password = ""

    return guest_password

submit_password

submit_password(
    gi: GraphicInterface, config: DictConfig
) -> bool

Same as backend_submit_password with an additional check on old password.

Parameters:

Name Type Description Default
config DictConfig

Hydra configuration dictionary.

required
gi GraphicInterface

graphic interface object (used to interact with Panel widgets).

required

Returns:

Type Description
bool

true if successful, false otherwise.

Source code in dlunch/core.py
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
def submit_password(gi: gui.GraphicInterface, config: DictConfig) -> bool:
    """Same as backend_submit_password with an additional check on old
    password.

    Args:
        config (DictConfig): Hydra configuration dictionary.
        gi (gui.GraphicInterface): graphic interface object (used to interact with Panel widgets).

    Returns:
        bool: true if successful, false otherwise.
    """
    # Get user's password hash
    password_hash = auth.get_hash_from_user(pn_user(config), config=config)
    # Get username, updated updated at each key press
    old_password_key_press = gi.password_widget._widgets[
        "old_password"
    ].value_input
    # Check if old password is correct
    if password_hash == old_password_key_press:
        # Check if new password match repeat password
        return backend_submit_password(
            gi=gi, config=config, user=pn_user(config), logout_on_success=True
        )
    else:
        pn.state.notifications.error(
            "Incorrect old password!",
            duration=config.panel.notifications.duration,
        )

    return False