Kaynağa Gözat

filter db side when getting autocompletions

Daniel Sheffield 2 yıl önce
ebeveyn
işleme
86b97aabdf
2 değiştirilmiş dosya ile 25 ekleme ve 11 silme
  1. 2 2
      app/data/QueryManager.py
  2. 23 9
      app/data/TransactionView.py

+ 2 - 2
app/data/QueryManager.py

@@ -61,7 +61,7 @@ def get_session_transactions(cursor, statement, display):
     if df.empty:
         return ''
     return df.drop(labels=[
-        'id', 'ts', 'store', 'code',
+        'id', 'ts', 'store', 'code', 'quantity',
     ], axis=1).to_string(header=[
         'Description', 'Volume', 'Unit', 'Price', '$/unit', 'Total',
         'Group', 'Category', 'Product', 'Organic',
@@ -145,7 +145,7 @@ class QueryManager(object):
         return get_session_transactions(self.cursor, statement, self.display)
 
     def unique_suggestions(self, name, **kwargs):
-        statement = get_transactions_statement()
+        statement = get_transactions_statement(name, **kwargs)
         return unique_suggestions(self.cursor, statement, name, self.display, **kwargs)
 
     def insert_new_product(self, product, category, group):

+ 23 - 9
app/data/TransactionView.py

@@ -14,23 +14,36 @@ from psycopg.sql import (
     Literal,
 )
 from .util import get_select, get_from
+ALIAS_TO_TABLE = {
+    'product': 'products',
+    'category': 'categories',
+    'group': 'groups',
+    'unit': 'units',
+    'store': 'stores',
+}
 
 def get_table_statement(alias):
-    tables = {
-        'product': 'products',
-        'category': 'categories',
-        'group': 'groups',
-        'unit': 'units',
-        'store': 'stores',
-    }
+    tables = ALIAS_TO_TABLE
     return SQL("SELECT {column} AS {alias} FROM {table}").format(
         column=Identifier(tables[alias], 'name'),
         table=Identifier(tables[alias]),
         alias=Identifier(alias),
     )
 
-def get_transactions_statement():
-    return SQL("SELECT * FROM transaction_view")
+def get_transactions_statement(name, **kwargs):
+    where = []
+    for k,v in kwargs.items():
+        where.append(SQL('{key} {condition} {value}').format(
+            key=Identifier(ALIAS_TO_TABLE[k], 'name'),
+            condition=SQL('ILIKE' if k == name else '='),
+            value=Literal(f'%{v}%' if k == name else v),
+        ) if k in ALIAS_TO_TABLE and v else SQL('TRUE'))
+    statement = SQL('\n').join([
+        get_select(SELECT),
+        get_from("transactions", JOINS),
+        SQL('').join([SQL('WHERE '), SQL('\n    AND ').join(where)]),
+    ])
+    return statement
 
 SELECT = OrderedDict([
     ('id', Identifier('transactions', 'id')),
@@ -41,6 +54,7 @@ SELECT = OrderedDict([
     ('volume', Identifier('quantity')),
     ('unit', Identifier('units', 'name')),
     ('price', Identifier('price')),
+    ('quantity', Identifier('quantity')),
     ('$/unit', SQL("""TRUNC(price/quantity,4)""")),
     ('total', SQL("""sum(transactions.price)
 OVER (