Files
2026-10-07 17:31:08 +05:30

96 lines
3.7 KiB
Python

@app.route("/manual-item-codes")
def manual_item_codes_page():
user_id = session.get("user_id")
role = session.get("role")
if not user_id or role not in ["user", "dmh"]:
return redirect(url_for("login"))
return render_template("manual_item_codes.html")
@app.route("/api/manual-extract", methods=["POST"])
def api_manual_extract():
"""JSON upload endpoint for the Manual Item Codes page. Extracts the
invoice, saves it to extraction_history like /upload_image does, and
returns the extraction id so the page can save item codes against it."""
user_id = session.get("user_id")
role = session.get("role")
if not user_id or role not in ["user", "dmh"]:
return jsonify({"error": "Unauthorized"}), 401
file = request.files.get("file")
if not file or not allowed_file(file.filename):
return jsonify({"success": False, "error": "Invalid file. Upload PDF or Image."}), 400
use_drug_list = request.form.get("use_drug_list", "true").strip().lower() != "false"
original_filename = secure_filename(file.filename)
unique_filename = f"{uuid.uuid4()}_{original_filename}"
file_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)
file.save(file_path)
try:
ext = original_filename.lower()
invoice_source = "manual" if ext.endswith((".jpg", ".jpeg", ".png")) else "email"
is_dmh = (role == "dmh")
extracted_data = extract_invoice_fields(
file_path, invoice_source, is_dmh=is_dmh, use_drug_list=use_drug_list
)
if not extracted_data or "error" in extracted_data:
err = extracted_data.get("error", "Extraction failed") if isinstance(extracted_data, dict) else "Extraction failed"
return jsonify({"success": False, "error": err}), 400
invoice_id = extracted_data.get("invoice_id")
# Pull billing metadata out before saving the JSON, same as /upload_image
_input_tokens = extracted_data.pop("_input_tokens", 0)
_output_tokens = extracted_data.pop("_output_tokens", 0)
_cost_usd = extracted_data.pop("_cost_usd", 0.0)
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"UPDATE users SET invoices_extracted = invoices_extracted + 1 WHERE username = %s",
(session["user"],),
)
cursor.execute(
"""
INSERT INTO extraction_history
(invoice_id, invoice_source, user_id, timestamp, image_name, pages_extracted,
extraction_type, extracted_data, file_path, input_tokens, output_tokens, cost_usd)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
""",
(
invoice_id,
invoice_source,
user_id,
datetime.now(),
original_filename,
len(extracted_data.get("items", [])),
"invoice",
json.dumps(extracted_data),
file_path,
_input_tokens,
_output_tokens,
_cost_usd,
),
)
conn.commit()
extraction_id = cursor.lastrowid
finally:
cursor.close()
conn.close()
return jsonify({"success": True, "data": extracted_data, "extraction_id": extraction_id}), 200
except Exception as e:
logging.error(f"Manual-extract error: {e}", exc_info=True)
return jsonify({"success": False, "error": str(e)}), 500
finally:
try:
if os.path.exists(file_path):
os.remove(file_path)
except Exception:
pass