db_utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #
  2. # Copyright (c) Daniel Sheffield 2021 - 2022
  3. #
  4. # All rights reserved
  5. #
  6. # THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
  7. from sqlite3 import Cursor
  8. import time
  9. from typing import Any, Callable
  10. from .txn_view import (
  11. get_table_statement,
  12. get_transactions_statement,
  13. get_session_transactions_statement,
  14. )
  15. from .price_view import(
  16. get_historic_prices_statement,
  17. )
  18. from dateutil.parser import parse as parse_time
  19. import pandas as pd
  20. NON_IDENTIFIER_COLUMNS = [
  21. 'ts',
  22. 'store',
  23. 'quantity',
  24. 'unit',
  25. 'price',
  26. 'organic',
  27. ]
  28. display_map = {
  29. 'ts': lambda x: f"{time.strftime('%Y-%m-%d %H:%M', (x.year, x.month, x.day, x.hour, x.minute, 0, 0, 0, 0))}",
  30. '%d/%m/%y %_I%P': lambda x: f"{time.strftime('%d/%m/%y %_I%P', (x.year, x.month, x.day, x.hour, x.minute, 0, 0, 0, 0))}",
  31. 'price': lambda x: f'{x:.4f}',
  32. 'quantity': lambda x: f'{x:.2f}',
  33. 'organic': lambda x: 'yes' if x else 'no',
  34. }
  35. display_mapper: Callable[
  36. [Any, str], str
  37. ] = lambda data, name: display_map[name](data) if name in display_map else data
  38. def cursor_as_dict(cur):
  39. _col_idx_map=dict(map(lambda col: (col[1].name, col[0]), enumerate(cur.description)))
  40. for row in map(lambda row, _map=_col_idx_map: dict([
  41. (name, row[i]) for name, i in _map.items()
  42. ]), cur.fetchall()):
  43. #print(row)
  44. yield row
  45. def get_data(cursor, statement, display=None):
  46. cursor.execute(statement)
  47. if display is not None:
  48. yield from map(lambda x: dict(
  49. map(lambda k: (k, display(x[k], k)), x)
  50. ), cursor_as_dict(cursor))
  51. else:
  52. yield from cursor_as_dict(cursor)
  53. def get_session_transactions(cursor, statement, display):
  54. #print(cur.mogrify(statement).decode("utf-8"))
  55. #input()
  56. df = pd.DataFrame(get_data(cursor, statement, display))
  57. if df.empty:
  58. return ''
  59. return df.drop(labels=[
  60. 'id', 'ts', 'store', 'code',
  61. ], axis=1).to_string(header=[
  62. 'Description', 'Volume', 'Unit', 'Price', '$/unit', 'Total',
  63. 'Group', 'Category', 'Product', 'Organic',
  64. ], justify='justify-all', max_colwidth=60, index=False)
  65. def record_matches(record, strict=None, **kwargs):
  66. strict = [ x.lower() for x in (strict or []) ]
  67. for key, query, candidate in (
  68. (k.lower(), f"{v}".lower(), f"{record[k]}".lower()) for k, v in kwargs.items()
  69. ):
  70. if not query:
  71. continue
  72. if key in strict and query != candidate:
  73. return False
  74. for term in query.split():
  75. if term not in candidate:
  76. return False
  77. return True
  78. def unique_suggestions(cur, statement, name, display, exclude=NON_IDENTIFIER_COLUMNS, **kwargs):
  79. exclude = filter(
  80. lambda x: x != name or name == 'ts',
  81. exclude,
  82. )
  83. [ kwargs.pop(k) for k in exclude if k in kwargs]
  84. items = suggestions(cur, statement, name, display, exclude=exclude, **kwargs)
  85. ret = sorted(set(map(lambda x: x[name], items)))
  86. tables = {
  87. 'product',
  88. 'category',
  89. 'group',
  90. 'unit',
  91. 'store',
  92. }
  93. if len(ret) > 0 or name not in tables:
  94. return ret
  95. items = (i for i in filter(lambda x: record_matches(x, **{ name: kwargs[name] }),
  96. get_data(cur, get_table_statement(name), display)))
  97. ret = sorted(set(map(lambda x: x[name], items)))
  98. return ret
  99. def suggestions(cur, statement, name, display, exclude=NON_IDENTIFIER_COLUMNS, **kwargs):
  100. exclude = filter(
  101. lambda x: x != name or name == 'ts',
  102. exclude,
  103. )
  104. [ kwargs.pop(k) for k in exclude if k in kwargs]
  105. yield from filter(lambda x: record_matches(
  106. x, strict=[ k for k in kwargs if k != name ], **kwargs
  107. ), get_data(cur, statement, display))
  108. def get_insert_product_statement(product, category, group):
  109. return f'CALL insert_product($prod${product}$prod$, $category${category}$category$, $group${group}$group$)'
  110. class QueryManager(object):
  111. def __init__(self, cursor: Cursor, display: Callable[
  112. [Any, str], str
  113. ]):
  114. self.display = display
  115. self.cursor = cursor
  116. def get_historic_prices_data(self, unit, sort=None, product=None, category=None, group=None, organic=None, limit=None):
  117. statement = get_historic_prices_statement(unit, sort=sort, product=product, category=category, group=group, organic=organic, limit=limit)
  118. #print(self.cursor.mogrify(statement).decode('utf-8'))
  119. #input()
  120. data = get_data(self.cursor, statement)
  121. return pd.DataFrame(map(lambda x: dict(
  122. map(lambda k: (k, self.display(x[k], k)), x)
  123. ), data))
  124. def get_session_transactions(self, date, store):
  125. statement = get_session_transactions_statement(
  126. parse_time(date), store, full_name=True, exact_time=True
  127. )
  128. return get_session_transactions(self.cursor, statement, self.display)
  129. def unique_suggestions(self, name, **kwargs):
  130. statement = get_transactions_statement()
  131. return unique_suggestions(self.cursor, statement, name, self.display, **kwargs)
  132. def insert_new_product(self, product, category, group):
  133. self.cursor.execute(get_insert_product_statement(product, category, group))