106 lines
3.5 KiB
Python
106 lines
3.5 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Item Code Catalog — migration & CSV import script
|
|
----------------------------------------------------
|
|
Run this once to:
|
|
1. Create the `item_codes` table in users.db (if it doesn't exist yet)
|
|
2. Import any rows from drug_list.csv into it (skips codes already in the table)
|
|
|
|
This is the same thing app_new_updated.py already does automatically on
|
|
startup (ensure_catalog_table() + import_csv_into_catalog_if_empty()), so
|
|
you normally don't need to run this by hand — it's here for cases where you
|
|
want to inspect/import without starting the full Flask app, or want to
|
|
re-import a *new* CSV without wiping the catalog (import_csv_into_catalog_if_empty()
|
|
in the app only runs when the table is empty; this script will import any
|
|
row in the CSV that isn't already in the table, safe to re-run any time).
|
|
"""
|
|
|
|
import sqlite3
|
|
import sys
|
|
import pandas as pd
|
|
|
|
DATABASE = 'users.db'
|
|
CSV_PATH = 'drug_list.csv'
|
|
|
|
|
|
def get_conn():
|
|
conn = sqlite3.connect(DATABASE)
|
|
conn.row_factory = sqlite3.Row
|
|
return conn
|
|
|
|
|
|
def ensure_table():
|
|
conn = get_conn()
|
|
cursor = conn.cursor()
|
|
cursor.execute('''
|
|
CREATE TABLE IF NOT EXISTS item_codes (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
item_code TEXT UNIQUE NOT NULL,
|
|
name TEXT NOT NULL,
|
|
category TEXT NOT NULL DEFAULT 'Uncategorized',
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
created_by INTEGER,
|
|
FOREIGN KEY (created_by) REFERENCES users(id)
|
|
)
|
|
''')
|
|
cursor.execute('CREATE INDEX IF NOT EXISTS idx_item_codes_name ON item_codes(name)')
|
|
cursor.execute('CREATE INDEX IF NOT EXISTS idx_item_codes_category ON item_codes(category)')
|
|
conn.commit()
|
|
conn.close()
|
|
print("✅ item_codes table ready")
|
|
|
|
|
|
def import_csv():
|
|
try:
|
|
df = pd.read_csv(CSV_PATH)
|
|
except FileNotFoundError:
|
|
print(f"⚠️ {CSV_PATH} not found — skipping import (table still created).")
|
|
return
|
|
|
|
if 'item_code' not in df.columns or 'name' not in df.columns:
|
|
print(f"❌ {CSV_PATH} needs at least 'item_code' and 'name' columns. Found: {list(df.columns)}")
|
|
return
|
|
|
|
has_category = 'category' in df.columns
|
|
|
|
conn = get_conn()
|
|
cursor = conn.cursor()
|
|
imported, skipped = 0, 0
|
|
|
|
for _, row in df.iterrows():
|
|
code = str(row['item_code']).strip()
|
|
name = str(row['name']).strip()
|
|
if not code or not name or code.lower() == 'nan' or name.lower() == 'nan':
|
|
continue
|
|
category = 'Uncategorized'
|
|
if has_category:
|
|
raw_cat = str(row.get('category', '')).strip()
|
|
if raw_cat and raw_cat.lower() != 'nan':
|
|
category = raw_cat
|
|
try:
|
|
cursor.execute(
|
|
'INSERT INTO item_codes (item_code, name, category) VALUES (?, ?, ?)',
|
|
(code, name, category)
|
|
)
|
|
imported += 1
|
|
except sqlite3.IntegrityError:
|
|
skipped += 1 # item_code already in the catalog
|
|
|
|
conn.commit()
|
|
conn.close()
|
|
print(f"✅ Imported {imported} new item codes ({skipped} already existed and were skipped)")
|
|
|
|
|
|
def main():
|
|
print("=" * 60)
|
|
print(" 📦 ITEM CODE CATALOG SETUP")
|
|
print("=" * 60)
|
|
ensure_table()
|
|
import_csv()
|
|
print("\n✅ Done. Restart the Flask app (or call load_drug_database())")
|
|
print(" so newly imported codes are used for matching immediately.")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |