patch: change user when other user is scanned

This commit is contained in:
Lunaresk 2021-12-06 00:03:49 +01:00
parent 222a335ddc
commit b24ea7530f
3 changed files with 123 additions and 67 deletions

View File

@ -1,3 +1,7 @@
server:
host: "http://localhost"
port: "5000"
port: "5000"
options:
barcode:
codeid_position: Null

View File

@ -1,14 +1,18 @@
from copy import deepcopy
from datetime import date
from json import dump as jdump, load as jload
from os import remove
from os import makedirs, remove
from os.path import exists
from select import select as timedInput
from sys import stdin
from yaml import safe_load
import connection
import logging
if not exists("../logs"):
makedirs("../logs")
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
logFormatter = logging.Formatter(
@ -23,70 +27,51 @@ consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
LOGGER.addHandler(consoleHandler)
with open("config.yaml", 'r') as file:
data = safe_load(file)['options']
CODEID_POS = data['barcode']['codeid_position']
TEMPFILE = "scans.json"
TIMEOUT = 60 # Number of seconds for a timeout after being logged in
def main(TEMP: list = None) -> None:
def main() -> None:
while True:
user = input("Enter Login: ")
user = login()
if not user:
continue
if user == "quit":
break
if not connection.check_login(user):
LOGGER.debug("Login failed")
continue # Send Error that login wasn't possible
LOGGER.debug("Login successful")
scanned = scanning()
scanned = group_scanning(scanned)
result = connection.send_scan(user, scanned)
if result != True:
result['date'] = str(date.today())
TEMP.append(result)
if TEMP:
TEMP = group_temp(TEMP)
for bought in list(TEMP):
result = connection.send_scan(bought['user'], bought['items'], bought['date'])
TEMP.remove(bought)
if result != True:
TEMP.append(result)
with open(TEMPFILE, "w") as file:
jdump(TEMP, file)
elif exists(TEMPFILE):
remove(TEMPFILE)
LOGGER.info(TEMP)
scanning(user)
def delete(scanned: list):
i, _, _ = timedInput([stdin], [], [], TIMEOUT)
if not i:
return #TODO send a short timeout message before return
scan = stdin.readline().strip()
codeid, scan = split_codeid(scan, "A")
match scan:
case "delete":
try:
scanned.pop()
except IndexError as e:
LOGGER.exception(e)
case _:
try:
scanned.remove(scan)
except ValueError as e:
LOGGER.exception(e)
def scanning() -> list:
scan, scanned = "", []
while True:
i, _, _ = timedInput([stdin], [], [], TIMEOUT)
if not i:
break # send a short timeout message before break
scan = stdin.readline().strip()
match scan:
case "logout":
break
case "delete":
while True:
i, _, _ = timedInput([stdin], [], [], TIMEOUT)
if not i:
break # send a short timeout message before break
scan = stdin.readline().strip()
match scan:
case "delete":
try:
scanned.pop()
except IndexError as e:
LOGGER.exception(e)
case _:
try:
scanned.remove(scan)
except ValueError as e:
LOGGER.exception(e)
case _:
scanned.append(scan)
return scanned
def group_scanning(scanned: list[int]) -> dict[int: int]:
scan_dict = {}
for scan in scanned:
if scan not in scan_dict:
scan_dict[scan] = 1
else:
scan_dict[scan] += 1
return scan_dict
def group_temp(TEMP: list):
NEWTEMP = []
@ -105,18 +90,80 @@ def group_temp(TEMP: list):
NEWTEMP.append(deepcopy(temp))
return NEWTEMP
def group_scanning(scanned: list[int]) -> dict[int: int]:
scan_dict = {}
for scan in scanned:
if scan not in scan_dict:
scan_dict[scan] = 1
else:
scan_dict[scan] += 1
return scan_dict
def login(user: str = None):
if not user:
user = input("Enter Login: ")
codeid, user = split_codeid(user, "D")
else:
codeid = "D"
if codeid != "D":
return None
if not connection.check_login(user):
LOGGER.debug("Login failed")
if not ("users" in data and user in data['users']):
return None
LOGGER.debug("Using local login")
return user
if __name__ == '__main__':
TEMP = None
def scanning(user: str) -> dict[int: int]:
scan, scanned = "", []
while True:
i, _, _ = timedInput([stdin], [], [], TIMEOUT)
if not i:
break # send a short timeout message before break
scan = stdin.readline().strip()
codeid, scan = split_codeid(scan, "A")
match codeid:
case "A":
scanned.append(scan)
case "D":
match scan:
case "logout":
break
case "delete":
delete(scanned)
case _:
altuser = login(scan)
if not altuser:
continue
LOGGER.debug("Login successful")
scanning(altuser)
break
case _:
LOGGER.debug(f"Unknown barcode scanned: {codeid}_{scan}")
scanned = group_scanning(scanned)
send_scan(user, scanned)
def send_scan(user: str, scanned: list, temp: list[dict] = []):
if exists(TEMPFILE):
with open(TEMPFILE, "r") as file:
TEMP = jload(file)
main(TEMP)
temp.extend(jload(file))
result = connection.send_scan(user, scanned)
if result != True:
result['date'] = str(date.today())
temp.append(result)
if temp:
temp = group_temp(temp)
for bought in list(temp):
result = connection.send_scan(bought['user'], bought['items'], bought['date'])
temp.remove(bought)
if result != True:
temp.append(result)
if temp: # if temp still present, save it
with open(TEMPFILE, "w") as file:
jdump(temp, file)
elif exists(TEMPFILE):
remove(TEMPFILE)
LOGGER.info(temp)
def split_codeid(scan: str, default_codeid: str = ""):
match CODEID_POS:
case "prefix":
return(scan[0], scan[1:])
case "suffix":
return(scan[-1], scan[:-1])
case _:
return(default_codeid, scan)
if __name__ == '__main__':
main()

View File

@ -2,9 +2,14 @@ from database import Database
from flask import Flask, abort, request
from flask.json import jsonify
from gevent.pywsgi import WSGIServer
from os import makedirs
from os.path import exists
import logging
if not exists("../logs"):
makedirs("../logs")
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
logFormatter = logging.Formatter(