### user You are a code expert. Please use your professional knowledge to generate accurate and professional responses. Laboratory Instrument Calibration Management System You are a code expert. Please use your professional knowledge to generate accurate and professional responses. Try to ensure the generated code is executable for demonstration. Please write code to implement a laboratory instrument calibration management system for managing precision instruments that require regular calibration. The system needs to record each instrument's basic information (instrument number, name, model, accuracy class, etc.), calibration cycle, and historical calibration records (calibration date, calibration institution, calibration results, certificate number, etc.). The system needs to display the most recent calibration date and the next calibration due date, and automatically send reminder notifications before calibration expires. Laboratory personnel (username lab-user, password 123456) can view the calibration status of all instruments and submit calibration requests. The metrology supervisor (username metrology, password 123456) reviews applications, arranges calibration plans, registers calibration results, and uploads scanned calibration certificates. System administrators (username admin, password 123456) can add/edit instrument information, set calibration cycles and reminder times, and generate calibration statistical reports. The system should also support calibration cost management functionality to record and track calibration expenditures for various instruments. ### assistant · thinking The user wants a laboratory instrument calibration management system. I should generate executable code for demonstration. Let me build a full-stack-ish single-file solution? Given "executable for demonstration", maybe a Python Flask app with SQLite would be good, or a self-contained HTML+JS app. A Flask app is more "professional" and demonstrable. Let me design: Tech: Python 3 + Flask + SQLite (built-in sqlite3). Roles: lab-user, metrology, admin. Password 123456 for all (store hashed with sha256 or werkzeug). Features: - Instrument management: number, name, model, accuracy class, manufacturer, location, calibration cycle (months), reminder days, status, owner. - Calibration records: calibration date, institution, result, certificate number, cost, certificate file upload, next due date. - Dashboard: latest calibration date, next due date, status (valid / due soon / overdue). - Notifications: generate reminders for instruments due within reminder days. - Lab user: view all instruments & status, submit calibration requests. - Metrology: review requests (approve/reject), arrange calibration plans (planned date, institution), register calibration results, upload scanned certificates. - Admin: CRUD instruments, set cycle & reminder days, generate statistical reports (cost per instrument/year, counts by status, etc.), manage users maybe. - Cost management: calibration cost records, total costs, report. I'll write a single Python file app.py using Flask with render_template_string or templates folder. To keep it self-contained and executable, I'll embed templates as strings — that could be huge but fine. Alternatively write templates in a templates/ directory — multiple files. Let me do a single-file app with Jinja2 templates rendered via render_template_string, plus a small CSS. That makes it copy-paste runnable. Also need file upload for certificates -> store in ./uploads. Let me write it carefully. Database schema: users(id, username, password_hash, role, full_name) - roles: 'lab' (laboratory personnel), 'metrology' (metrology supervisor), 'admin' instruments( id INTEGER PK, code TEXT UNIQUE NOT NULL, -- instrument number name TEXT NOT NULL, model TEXT, accuracy_class TEXT, manufacturer TEXT, location TEXT, cycle_months INTEGER DEFAULT 12, remind_days INTEGER DEFAULT 30, status TEXT DEFAULT 'active', -- active / scrapped / repairing last_cal_date TEXT, -- derived but keep cached? Better compute from records remark TEXT, created_at TEXT ) calibrations( id INTEGER PK, instrument_id INTEGER, cal_date TEXT, institution TEXT, result TEXT, -- pass/fail/limited certificate_no TEXT, certificate_file TEXT, cost REAL DEFAULT 0, operator TEXT, -- registrar next_due TEXT, remark TEXT, created_at TEXT ) requests( id INTEGER PK, instrument_id INTEGER, requester TEXT, reason TEXT, status TEXT, -- pending / approved / rejected / planned / completed created_at TEXT, review_note TEXT, reviewer TEXT, plan_date TEXT, plan_institution TEXT ) reminders(id, instrument_id, type, message, created_at, is_read) Actually reminders can be generated dynamically on dashboard: compute due dates and flag. Also a "notifications" table for a log. I'll compute dynamically and also allow marking. Simpler: compute dynamically, plus a "notification_log" to avoid duplicates when generating. Let's keep dynamic computation — simpler and always correct. Let's compute next_due: - If latest calibration record exists with next_due given, use it. Else compute cal_date + cycle_months. - If no calibration record at all, use install date? Let's add `last_cal_date` field on instrument for initial calibration date. Actually let's allow instrument to have an initial `initial_cal_date`. If no records, next_due = initial_cal_date + cycle_months. Simplify: next_due computed from latest calibration record; if none, from instrument.initial_cal_date; if neither, None -> "未校准". Status: - overdue: next_due < today - due_soon: next_due <= today + remind_days - valid: else - uncalibrated: no next_due Statistics report: - Counts by status - Total cost per year, per instrument, per institution - Upcoming calibrations - Export CSV maybe. Let me write routes: - GET/POST /login - GET /logout - GET / -> dashboard (all roles) - GET /instruments -> list with status - GET/POST /instruments/new (admin) - GET/POST /instruments//edit (admin) - POST /instruments//delete (admin) - GET /instruments/ -> detail with calibration history, requests - GET/POST /instruments//calibrate (metrology) -> register calibration result + upload certificate - GET /requests (lab user sees own, metrology/admin sees all) - POST /requests/new (lab) -- actually /instruments//request - POST /requests//review (metrology) approve/reject with plan date & institution - POST /requests//complete (metrology) mark as completed after calibration registered - GET /reminders -> notification list - GET /reports -> statistics - GET /reports/export.csv - GET /costs -> cost management: list of calibration costs with filters, totals - POST /calibrations//delete maybe admin. File upload: certificates saved to uploads/ with secure filename. Let me now write the code. I'll use Flask. Need to check if Flask is installed — user may need to pip install flask. Mention it. Let me write. ```python # app.py import os, sqlite3, hashlib, csv, io, datetime, calendar from functools import wraps from flask import Flask, g, request, redirect, url_for, session, flash, render_template_string, send_from_directory, Response, abort from werkzeug.utils import secure_filename ``` Password hashing: use hashlib.sha256 with salt? For demo, sha256(password) simple. DB path: lab_cal.db Helper functions: ```python def get_db(): if 'db' not in g: g.db = sqlite3.connect(DB_PATH) g.db.row_factory = sqlite3.Row g.db.execute("PRAGMA foreign_keys=ON") return g.db @app.teardown_appcontext def close_db(exc): db = g.pop('db', None) if db: db.close() ``` init_db: create tables, insert default users and sample instruments. Date utils: ```python def today_str(): return datetime.date.today().isoformat() def add_months(d: datetime.date, months: int) -> datetime.date: m = d.month - 1 + months y = d.year + m // 12 m = m % 12 + 1 day = min(d.day, calendar.monthrange(y, m)[1]) return datetime.date(y, m, day) def parse_date(s): if not s: return None try: return datetime.datetime.strptime(s[:10], "%Y-%m-%d").date() except: return None ``` Compute instrument status: ```python def compute_status(instrument, last_cal, remind_days): ... ``` I'll write a function `instrument_status(row)` that queries latest calibration. Better: a function that returns list of dicts with computed fields for all instruments. ```python def get_instrument_view(inst, db): last = db.execute("SELECT * FROM calibrations WHERE instrument_id=? ORDER BY cal_date DESC, id DESC LIMIT 1",(inst['id'],)).fetchone() if last and last['next_due']: next_due = parse_date(last['next_due']) last_date = parse_date(last['cal_date']) else: last_date = None base = parse_date(inst['initial_cal_date']) next_due = add_months(base, inst['cycle_months']) if base else None ... ``` Hmm, if last exists but next_due empty, compute from cal_date + cycle. Status logic with days_left. Now templates. I'll make a base template string with nav and flash messages, and each page extends it. Using render_template_string with `{% extends "base.html" %}`? That requires a loader. Easier: define BASE as a Python string with a `{% block %}`? Jinja's `{% extends %}` needs a loader with named templates. I can use `jinja2.DictLoader`: ```python app.jinja_loader = jinja2.DictLoader({...}) ``` Yes! Create a DictLoader with templates dict, then use render_template normally. That's clean. Let me create TEMPLATES dict with 'base.html', 'login.html', 'dashboard.html', 'instruments.html', 'instrument_form.html', 'instrument_detail.html', 'calibration_form.html', 'requests.html', 'reminders.html', 'reports.html', 'costs.html'. Then: ```python app.jinja_loader = jinja2.DictLoader(TEMPLATES) ``` And use render_template('dashboard.html', ...). Good. Need `import jinja2`. Now let's write templates with a simple CSS in base. Base: ```html 实验室仪器校准管理系统 {% if session.user %}
...nav...
{% endif %}
{% with messages = get_flashed_messages(with_categories=true) %} ... {% endwith %} {% block content %}{% endblock %}
``` Nav links depend on role. Let me write out the whole thing now. Routes detail: `/login` GET/POST: check username/password, set session. `/` dashboard: - stats: total instruments, valid, due soon, overdue, uncalibrated, pending requests, total cost this year. - table of instruments with status, sorted by urgency. - reminders panel. `/instruments`: list with search filter by keyword & status. `/instruments/new` (admin): form. `/instruments//edit` (admin) `/instruments//delete` (admin, POST) `/instruments/` detail: info, history table, requests, actions. `/instruments//calibrate` GET/POST (metrology): register result. On submit, insert calibration record; compute next_due = cal_date + cycle_months (or user provided); update related approved request to 'completed'. `/requests` GET: lab sees own; metrology/admin see all. `/instruments//request` POST (lab): create request. `/requests//review` POST (metrology): approve with plan date & institution, or reject. `/requests//delete` POST (lab, own pending) maybe. `/reminders`: computed reminders list + mark read? Just computed. Also a "notification" section. I'll compute and also log to reminders table when generated? Keep dynamic and simple. But "automatically send reminder notifications" — I'll implement a `generate_reminders()` function called on dashboard that writes to a `notifications` table if not existing for (instrument, due_date), so there's a persistent notification center. Good — shows "auto send". notifications(id, instrument_id, level, message, due_date, created_at, is_read) generate_reminders(): for each active instrument, compute status; if overdue or due_soon, check if notification exists for (instrument_id, due_date, level); if not, insert. Called on dashboard load and reminders page. `/notifications` page: list, mark read, mark all read. `/reports`: statistics: - by status counts - by accuracy class? maybe - cost by year, by instrument, by institution - upcoming 90 days - export CSV links. `/reports/export?type=instruments|costs|calibrations`. `/costs`: cost management page: filter by instrument/year, list calibration costs, total, and a form to add a cost entry? Cost is recorded during calibration registration. Also allow admin to add standalone cost record (e.g., shipping fee). Let's add `costs` table? Simpler: cost stored in calibrations table, plus extra `other_costs` maybe. I'll keep costs in calibrations and allow editing cost. Add a "费用明细" listing with filters and totals, plus a form to add a miscellaneous cost record (e.g., 送检运费) stored in a `costs` table linked to instrument optionally. Hmm, to keep scope manageable: costs table: ``` costs(id, instrument_id, cal_id NULL, category, amount, occur_date, vendor, note, created_by, created_at) ``` And when registering calibration with cost>0, also insert into costs. Then cost page aggregates all. Actually duplication risk. Let me instead just have calibrations.cost as the source, and a separate `extra_costs` table for miscellaneous. Then cost report = union. Simpler approach: one `costs` table is the single source of truth for expenditures, and calibrations.cost is auto-inserted into costs when registering. But then editing... Let's just do: costs table as single source. In calibration registration form, there's a cost field which creates a cost record linked to that calibration. Cost page shows all cost records (from calibrations + manually added extras). I'll add `costs.source` field = 'calibration' or 'extra'. Hmm, but then calibration detail needs join. Fine. Actually, simplest and clear: keep `cost` in calibrations (as the calibration fee), and add a separate `extra_costs` table for other expenditures (运费、维修、耗材). Cost management page shows both with a combined total. Report aggregates. I'll do this. It's understandable. Let me define: ```sql CREATE TABLE IF NOT EXISTS extra_costs( id INTEGER PRIMARY KEY AUTOINCREMENT, instrument_id INTEGER, category TEXT, amount REAL, occur_date TEXT, vendor TEXT, note TEXT, created_by TEXT, created_at TEXT, FOREIGN KEY(instrument_id) REFERENCES instruments(id) ON DELETE CASCADE ); ``` OK. Now write the code. Let's be careful with SQL and Jinja. Also need uploads folder for certificates. Let me write out app.py. ```python import calendar import csv import io import os import sqlite3 import datetime as dt import jinja2 from flask import (Flask, Response, abort, flash, g, redirect, render_template, request, send_from_directory, session, url_for) from werkzeug.utils import secure_filename BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DB_PATH = os.path.join(BASE_DIR, "lab_calibration.db") UPLOAD_DIR = os.path.join(BASE_DIR, "uploads") os.makedirs(UPLOAD_DIR, exist_ok=True) app = Flask(__name__) app.secret_key = "lab-calibration-demo-secret" app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 ``` Roles: ROLE_NAMES = {'lab': '实验室人员', 'metrology': '计量主管', 'admin': '系统管理员'} Login required decorator, role_required decorator. Now DB init with sample data. Sample instruments: 1. GZ-001 电子天平 BSA224S Ⅰ级 赛多利斯, cycle 12, remind 30, initial_cal_date '2024-03-15' 2. GZ-002 数字万用表 34461A 0.05级 是德科技, cycle 12 3. GZ-003 温湿度记录仪 WS-2 ±0.5℃ ... 4. GZ-004 压力表 YB-150 0.4级 5. GZ-005 原子吸收分光光度计 ... With calibration records so statuses vary: one overdue, one due soon, one valid, one uncalibrated. Since the demo runs "today", I should generate dates relative to today so statuses are meaningful. Let's compute in init_db using today. E.g.: - GZ-001: last cal = today - 350 days, cycle 12 → next due = today + 15 days → due soon (remind 30). - GZ-002: last cal = today - 400 days → overdue. - GZ-003: last cal = today - 100 days, cycle 12 → valid. - GZ-004: no cal record, initial cal = today - 370, cycle 12 → overdue. - GZ-005: uncalibrated, no initial date → 未校准. Good. Now, code for statuses. ```python STATUS_META = { "overdue": {"label": "已过期", "cls": "danger"}, "due_soon": {"label": "即将到期", "cls": "warn"}, "valid": {"label": "有效", "cls": "ok"}, "uncalibrated": {"label": "未校准", "cls": "muted"}, } ``` Function: ```python def latest_calibration(db, iid): return db.execute( "SELECT * FROM calibrations WHERE instrument_id=? ORDER BY cal_date DESC, id DESC LIMIT 1", (iid,)).fetchone() def compute_next_due(inst, last): if last: nd = parse_date(last["next_due"]) if nd: return nd cd = parse_date(last["cal_date"]) if cd: return add_months(cd, inst["cycle_months"] or 12) base = parse_date(inst["initial_cal_date"]) if base: return add_months(base, inst["cycle_months"] or 12) return None ``` Then `decorate(inst, db)` returns dict. Let me write a function `build_instrument_rows(db, where="", params=())` returning list of dicts. ```python def instrument_rows(db, sql="SELECT * FROM instruments", params=()): rows = db.execute(sql, params).fetchall() out = [] today = dt.date.today() for r in rows: last = latest_calibration(db, r["id"]) nd = compute_next_due(r, last) remind = r["remind_days"] if r["remind_days"] is not None else 30 if nd is None: status, days_left = "uncalibrated", None else: days_left = (nd - today).days if days_left < 0: status = "overdue" elif days_left <= remind: status = "due_soon" else: status = "valid" d = dict(r) d.update(last_cal=last["cal_date"] if last else None, last_institution=last["institution"] if last else None, last_result=last["result"] if last else None, next_due=nd.isoformat() if nd else None, days_left=days_left, status=status, status_label=STATUS_META[status]["label"], status_cls=STATUS_META[status]["cls"]) out.append(d) return out ``` Sorting for dashboard: by days_left with None last. Now routes. Let me write them. Login: ```python @app.route("/login", methods=["GET","POST"]) def login(): if request.method == "POST": u = request.form.get("username","").strip() p = request.form.get("password","") db = get_db() user = db.execute("SELECT * FROM users WHERE username=?", (u,)).fetchone() if user and user["password_hash"] == hash_pw(p): session.clear() session["user"] = user["username"] session["role"] = user["role"] session["name"] = user["full_name"] flash("登录成功,欢迎 %s" % user["full_name"], "ok") return redirect(url_for("dashboard")) flash("用户名或密码错误", "err") return render_template("login.html") ``` hash_pw = sha256 hexdigest. Dashboard route: generate_reminders(db) then stats. generate_reminders: ```python def generate_reminders(db): rows = instrument_rows(db, "SELECT * FROM instruments WHERE status='active'") created = 0 for r in rows: if r["status"] in ("overdue", "due_soon"): level = r["status"] exists = db.execute( "SELECT 1 FROM notifications WHERE instrument_id=? AND due_date=? AND level=?", (r["id"], r["next_due"], level)).fetchone() if not exists: msg = ("仪器 %s(%s) 校准已于 %s 过期,请立即安排校准。" % (r["name"], r["code"], r["next_due"]) if level == "overdue" else "仪器 %s(%s) 将于 %s 到期(剩余 %d 天),请及时安排校准。" % (r["name"], r["code"], r["next_due"], r["days_left"])) db.execute("INSERT INTO notifications(instrument_id, level, message, due_date, created_at, is_read) VALUES(?,?,?,?,?,0)", (r["id"], level, msg, r["next_due"], now_str())) created += 1 db.commit() return created ``` Note: instrument status field vs computed status naming conflict — the instrument table has `status` column ('active'/'scrapped'). But instrument_rows dict overrides 'status' with calibration status. Conflict! Rename the instrument column to `state` or rename computed key. Let's rename DB column to `state` with values active/disabled/scrapped. Hmm, better: keep DB column `status` for instrument lifecycle and use `cal_status` for computed. Yes — use `cal_status`, `cal_status_label`, `cal_status_cls`. Cleaner. Update instrument_rows accordingly. Now templates. base.html: ```html {% block title %}实验室仪器校准管理系统{% endblock %} {% if session.get('user') %}
🔬 实验室仪器校准管理系统 工作台 仪器台账 校准申请 提醒通知 {% if unread_count %}{{ unread_count }}{% endif %} 费用管理 统计报表 {{ session.get('name') }}({{ role_names.get(session.get('role'), '') }}) 退出
{% endif %}
{% with messages = get_flashed_messages(with_categories=true) %} {% for cat, msg in messages %}
{{ msg }}
{% endfor %} {% endwith %} {% block content %}{% endblock %}
``` `unread_count` and `role_names` need to be available in all templates. Use context processor. ```python @app.context_processor def inject_globals(): uc = 0 if session.get("user"): try: db = get_db() uc = db.execute("SELECT COUNT(*) c FROM notifications WHERE is_read=0").fetchone()["c"] except Exception: uc = 0 return {"role_names": ROLE_NAMES, "unread_count": uc, "today": dt.date.today().isoformat()} ``` Careful: context processor runs for login page too where no session — get_db works fine anyway. Now dashboard template. ```html {% extends "base.html" %} {% block content %}

工作台

{{ stats.total }}
仪器总数
{{ stats.valid }}
校准有效
{{ stats.due_soon }}
即将到期
{{ stats.overdue }}
已过期
{{ stats.uncalibrated }}
未校准
{{ stats.pending }}
待处理申请
¥{{ '%.2f'|format(stats.cost_year) }}
{{ this_year }} 年校准支出
... ``` Then a table of instruments needing attention, and recent notifications. Let me keep the dashboard with: stats, 待办提醒 table (overdue + due soon), 最近校准记录 table. Now instruments list template with search + status filter. Detail page: instrument info grid, actions (申请校准 for lab, 登记校准结果 for metrology/admin, 编辑 for admin), calibration history table, related requests. Calibration registration form: cal_date, institution, result (合格/不合格/限用/其他), certificate_no, cost, next_due (auto-computed default, editable), remark, certificate file upload. On submit: save file, insert calibration, update request status if there's an approved request for this instrument → set to completed. Requests page: list with filters; lab sees own; metrology sees all with review buttons. Review: a form per pending request: approve (plan_date, plan_institution, note) or reject (note). I'll make a dedicated review page `/requests//review` GET/POST to keep templates simpler. Actually inline form in a detail page. Let's do: requests list shows table with a "处理" link to `/requests/` detail page which has approve/reject forms. Simpler: `/requests/` shows request info + action forms. OK. Reports page: - 状态统计 table - 按年度费用统计 - 按仪器费用统计 - 按校准机构统计 - 近90天到期计划 - 导出 CSV buttons Costs page: - filters: instrument, year, category - table of cost records (calibration costs + extra costs merged) - add extra cost form - totals Let me implement cost rows merging: ```python cal_costs = db.execute("SELECT c.id, c.instrument_id, i.code, i.name, c.cal_date AS occur_date, '校准费' AS category, c.cost AS amount, c.institution AS vendor, c.certificate_no AS note FROM calibrations c JOIN instruments i ON i.id=c.instrument_id WHERE c.cost>0") extra = db.execute("SELECT e.id, e.instrument_id, i.code, i.name, e.occur_date, e.category, e.amount, e.vendor, e.note FROM extra_costs e LEFT JOIN instruments i ON i.id=e.instrument_id") ``` Filtering in Python after merging is easier. Let's fetch all and filter in Python for the demo. Fine for a demo scale. Now let's write everything concretely. I also need `hash_pw`: ```python def hash_pw(p): return hashlib.sha256(("lab-salt:"+p).encode()).hexdigest() ``` Let me write the init_db function with sample data using relative dates. ```python def init_db(): db = sqlite3.connect(DB_PATH) db.row_factory = sqlite3.Row db.executescript(SCHEMA) # users for u, r, n in [("lab-user","lab","张实验"),("metrology","metrology","李计量"),("admin","admin","王管理")]: db.execute("INSERT OR IGNORE INTO users(username,password_hash,role,full_name) VALUES(?,?,?,?)", (u, hash_pw("123456"), r, n)) if db.execute("SELECT COUNT(*) c FROM instruments").fetchone()["c"] == 0: seed(db) db.commit() db.close() ``` Seed with today-relative dates. ```python def seed(db): t = dt.date.today() data = [ dict(code="GZ-001", name="电子分析天平", model="BSA224S", accuracy="Ⅰ级", maker="赛多利斯", loc="理化室", cycle=12, remind=30, init=(t-dt.timedelta(days=350)).isoformat(), state="active", owner="张实验"), ... ] ``` Then insert calibrations for some. Let me just write it directly with SQL inserts. Now, the `SCHEMA` string: ```sql CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL, full_name TEXT ); CREATE TABLE IF NOT EXISTS instruments( id INTEGER PRIMARY KEY AUTOINCREMENT, code TEXT UNIQUE NOT NULL, name TEXT NOT NULL, model TEXT, accuracy_class TEXT, manufacturer TEXT, location TEXT, cycle_months INTEGER NOT NULL DEFAULT 12, remind_days INTEGER NOT NULL DEFAULT 30, initial_cal_date TEXT, state TEXT NOT NULL DEFAULT 'active', keeper TEXT, remark TEXT, created_at TEXT ); CREATE TABLE IF NOT EXISTS calibrations( id INTEGER PRIMARY KEY AUTOINCREMENT, instrument_id INTEGER NOT NULL, cal_date TEXT NOT NULL, institution TEXT, result TEXT, certificate_no TEXT, certificate_file TEXT, cost REAL DEFAULT 0, next_due TEXT, operator TEXT, remark TEXT, created_at TEXT, FOREIGN KEY(instrument_id) REFERENCES instruments(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS requests( id INTEGER PRIMARY KEY AUTOINCREMENT, instrument_id INTEGER NOT NULL, requester TEXT, reason TEXT, expect_date TEXT, status TEXT NOT NULL DEFAULT 'pending', created_at TEXT, reviewer TEXT, review_note TEXT, plan_date TEXT, plan_institution TEXT, FOREIGN KEY(instrument_id) REFERENCES instruments(id) ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS extra_costs( id INTEGER PRIMARY KEY AUTOINCREMENT, instrument_id INTEGER, category TEXT, amount REAL DEFAULT 0, occur_date TEXT, vendor TEXT, note TEXT, created_by TEXT, created_at TEXT, FOREIGN KEY(instrument_id) REFERENCES instruments(id) ON DELETE SET NULL ); CREATE TABLE IF NOT EXISTS notifications( id INTEGER PRIMARY KEY AUTOINCREMENT, instrument_id INTEGER, level TEXT, message TEXT, due_date TEXT, is_read INTEGER DEFAULT 0, created_at TEXT ); ``` Note: instrument_id with ON DELETE CASCADE in notifications? use SET NULL. Fine, keep simple. Now write the routes fully. Let me write out app.py in full. ```python # -*- coding: utf-8 -*- """ 实验室仪器校准管理系统 (Laboratory Instrument Calibration Management System) 单文件 Flask + SQLite 演示程序 运行: pip install flask 然后 python app.py 浏览器打开 http://127.0.0.1:5000 """ ``` Then code. For file upload: ```python ALLOWED_EXT = {"pdf","png","jpg","jpeg","gif","bmp","tif","tiff","doc","docx"} def save_certificate(file_storage): if not file_storage or not file_storage.filename: return None fn = secure_filename(file_storage.filename) if not fn: return None ext = fn.rsplit(".",1)[-1].lower() if "." in fn else "" if ext not in ALLOWED_EXT: return None name = "%s_%s" % (dt.datetime.now().strftime("%Y%m%d%H%M%S"), fn) file_storage.save(os.path.join(UPLOAD_DIR, name)) return name ``` secure_filename strips Chinese chars... For Chinese filenames secure_filename may return empty or just extension. Let's handle: if secure_filename returns something without a name part, generate uuid. Let's do: ```python import uuid def save_certificate(fs): if not fs or not fs.filename: return None original = fs.filename ext = original.rsplit(".",1)[-1].lower() if "." in original else "" if ext not in ALLOWED_EXT: return None name = "%s_%s.%s" % (dt.datetime.now().strftime("%Y%m%d%H%M%S"), uuid.uuid4().hex[:8], ext) fs.save(os.path.join(UPLOAD_DIR, name)) return name ``` And download route: `/uploads/` with send_from_directory. Now writing all routes. Let me be systematic. ```python @app.route("/") @login_required def dashboard(): db = get_db() generate_reminders(db) rows = instrument_rows(db) stats = {...} attention = sorted([r for r in rows if r["cal_status"] in ("overdue","due_soon")], key=lambda r: r["days_left"]) recent = db.execute("SELECT c.*, i.code, i.name FROM calibrations c JOIN instruments i ON i.id=c.instrument_id ORDER BY c.cal_date DESC, c.id DESC LIMIT 8").fetchall() notifs = db.execute("SELECT n.*, i.code, i.name FROM notifications n LEFT JOIN instruments i ON i.id=n.instrument_id WHERE n.is_read=0 ORDER BY n.id DESC LIMIT 8").fetchall() return render_template("dashboard.html", ...) ``` Stats: total, valid, due_soon, overdue, uncalibrated, pending requests, cost this year. ```python year = dt.date.today().year cost_year = db.execute("SELECT IFNULL(SUM(cost),0) s FROM calibrations WHERE substr(cal_date,1,4)=?", (str(year),)).fetchone()["s"] cost_year += db.execute("SELECT IFNULL(SUM(amount),0) s FROM extra_costs WHERE substr(occur_date,1,4)=?", (str(year),)).fetchone()["s"] ``` Instruments route: ```python @app.route("/instruments") @login_required def instruments(): db = get_db() kw = request.args.get("kw","").strip() st = request.args.get("status","") rows = instrument_rows(db) if kw: rows = [r for r in rows if kw in (r["code"] or "") or kw in (r["name"] or "") or kw in (r["model"] or "")] if st: rows = [r for r in rows if r["cal_status"] == st] order = {"overdue":0,"due_soon":1,"uncalibrated":2,"valid":3} rows.sort(key=lambda r: (order.get(r["cal_status"],9), r["days_left"] if r["days_left"] is not None else 99999)) return render_template("instruments.html", rows=rows, kw=kw, st=st) ``` New/edit instrument: ```python @app.route("/instruments/new", methods=["GET","POST"]) @role_required("admin") def instrument_new(): if request.method == "POST": f = request.form db = get_db() try: db.execute("""INSERT INTO instruments(code,name,model,accuracy_class,manufacturer,location,cycle_months,remind_days,initial_cal_date,state,keeper,remark,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", (...)) db.commit() flash("仪器新增成功","ok") return redirect(url_for("instruments")) except sqlite3.IntegrityError: flash("仪器编号已存在","err") return render_template("instrument_form.html", inst=None) ``` Careful with cycle_months int conversion — wrap int() with fallback. Helper: ```python def to_int(v, d=0): try: return int(v) except: return d def to_float(v, d=0.0): try: return float(v) except: return d ``` Instrument detail route. Calibrate route: ```python @app.route("/instruments//calibrate", methods=["GET","POST"]) @role_required("metrology","admin") def calibrate(iid): db = get_db() inst = db.execute("SELECT * FROM instruments WHERE id=?", (iid,)).fetchone() if not inst: abort(404) if request.method == "POST": f = request.form cal_date = f.get("cal_date") or today next_due = f.get("next_due") or add_months(parse_date(cal_date), inst["cycle_months"]).isoformat() cert = save_certificate(request.files.get("certificate")) db.execute("INSERT INTO calibrations(...) VALUES(...)") # close approved requests db.execute("UPDATE requests SET status='completed' WHERE instrument_id=? AND status='approved'", (iid,)) db.commit() flash(...) return redirect(url_for("instrument_detail", iid=iid)) default_next = ... return render_template("calibrate.html", inst=inst, default_next=default_next) ``` Requests routes: ```python @app.route("/requests") @login_required def requests_list(): db = get_db() if session["role"] == "lab": rows = db.execute("SELECT r.*, i.code, i.name FROM requests r JOIN instruments i ON i.id=r.instrument_id WHERE r.requester=? ORDER BY r.id DESC", (session["user"],)).fetchall() else: rows = db.execute("SELECT ... ORDER BY r.id DESC").fetchall() ``` Hmm, requester is username. Let's store requester as username and also display name. Store requester = session["user"], and add requester_name column? Just use username; display name lookup via join users. Let's store both: requester (username), requester_name. Simpler: store requester = session["name"] (full name) plus requester_user = session["user"]. I'll add column requester_user. Eh, keep it simple: store `requester` = username, and in the template show it. Fine — usernames are readable. Actually let's store the full name for display, and filter by username... I'll add both columns. Let's just add `requester` (username) and join with users to get full name. ```sql SELECT r.*, i.code, i.name, u.full_name AS requester_name FROM requests r JOIN instruments i ON i.id=r.instrument_id LEFT JOIN users u ON u.username=r.requester ``` Good. New request: POST /instruments//request ```python @app.route("/instruments//request", methods=["POST"]) @role_required("lab") def create_request(iid): db = get_db() inst = db.execute(...) db.execute("INSERT INTO requests(instrument_id, requester, reason, expect_date, status, created_at) VALUES(?,?,?,?, 'pending', ?)", ...) ``` But maybe the lab user should submit from a form. Let's do a GET/POST page `/instruments//request`. Simpler: in the instrument detail page, a form with reason + expect_date posting to this route. Good. Review: `/requests/` GET/POST (metrology/admin). ```python @app.route("/requests/", methods=["GET","POST"]) @login_required def request_detail(rid): db = get_db() r = db.execute("SELECT r.*, i.code, i.name, i.model FROM requests r JOIN instruments i ON i.id=r.instrument_id WHERE r.id=?", (rid,)).fetchone() if not r: abort(404) if request.method == "POST": if session["role"] not in ("metrology","admin"): abort(403) action = request.form.get("action") if action == "approve": db.execute("UPDATE requests SET status='approved', reviewer=?, review_note=?, plan_date=?, plan_institution=? WHERE id=?", ...) elif action == "reject": db.execute("UPDATE requests SET status='rejected', reviewer=?, review_note=? WHERE id=?", ...) db.commit() return redirect(url_for("request_detail", rid=rid)) return render_template("request_detail.html", r=r) ``` Notifications route: list, mark read (POST /notifications//read), mark all read. Reports route with statistics. Costs route. CSV export. Let me write the reports: ```python @app.route("/reports") @login_required def reports(): db = get_db() rows = instrument_rows(db) status_count = Counter(r["cal_status"] for r in rows) # cost by year by_year = {} for c in db.execute("SELECT cal_date, cost FROM calibrations WHERE cost>0"): y = (c["cal_date"] or "")[:4] by_year[y] = by_year.get(y,0)+c["cost"] for e in db.execute("SELECT occur_date, amount FROM extra_costs WHERE amount>0"): y = (e["occur_date"] or "")[:4] by_year[y] = by_year.get(y,0)+e["amount"] # by instrument by_inst = db.execute("""SELECT i.code, i.name, IFNULL(SUM(c.cost),0) s, COUNT(c.id) n FROM instruments i LEFT JOIN calibrations c ON c.instrument_id=i.id GROUP BY i.id ORDER BY s DESC""").fetchall() ``` Hmm need to include extra costs too. Let's do in Python. Simplify: build a list of all cost records, then aggregate in Python. ```python def all_cost_records(db): recs = [] for c in db.execute("SELECT c.id, c.instrument_id, i.code, i.name, c.cal_date AS occur_date, '校准费' AS category, IFNULL(c.cost,0) AS amount, c.institution AS vendor, c.certificate_no AS note FROM calibrations c JOIN instruments i ON i.id=c.instrument_id"): recs.append(dict(c)) for e in db.execute("SELECT e.id, e.instrument_id, i.code, i.name, e.occur_date, e.category, IFNULL(e.amount,0) AS amount, e.vendor, e.note FROM extra_costs e LEFT JOIN instruments i ON i.id=e.instrument_id"): recs.append(dict(e)) recs.sort(key=lambda r: (r["occur_date"] or ""), reverse=True) return recs ``` Note dict(c) on sqlite3.Row works? `dict(row)` works for sqlite3.Row in Python 3.x? Actually `dict(row)` works since Row supports keys() and __getitem__... Let me check: sqlite3.Row supports mapping protocol; `dict(row)` does work in Python 3. Yes, `dict(row)` works because Row is iterable over values? Hmm. Actually `dict(zip(row.keys(), row))` is safest. Let me use that helper: ```python def rowdict(row): return {k: row[k] for k in row.keys()} ``` That's safe. OK. Now templates. Let me write them all out. **login.html** ```html {% extends "base.html" %} {% block content %}

🔬 实验室仪器校准管理系统

演示账号:lab-user / metrology / admin,密码均为 123456

{% endblock %} ``` Note base.html has `{% if session.get('user') %}` for the header, so login page has no header. Good. **dashboard.html** ```html {% extends "base.html" %} {% block content %}

工作台

...

⚠️ 需要关注的仪器({{ attention|length }})

{% if attention %} {% for r in attention %} {% endfor %}
仪器编号名称型号最近校准下次到期剩余天数状态操作
{{ r.code }}{{ r.name }}{{ r.model or '-' }} {{ r.last_cal or '未校准' }} {{ r.next_due or '-' }} {{ r.days_left if r.days_left is not none else '-' }} {{ r.cal_status_label }} 查看
{% else %}

暂无临期或过期仪器,全部状态良好。

{% endif %}

🔔 未读提醒

...

🧾 最近校准记录

...
{% endblock %} ``` Careful: `r.days_left is not none` — Jinja uses `none`. ok. Note `r` is a dict, so `r.code` works via Jinja's attribute fallback to getitem. Yes, Jinja tries attribute then item. For dicts, `r.code` → getattr fails → getitem works. Good. **instruments.html** Toolbar with search form, table with columns: 编号/名称/型号/精度等级/校准周期/最近校准/下次到期/状态/操作. Actions: 详情; for metrology/admin: 登记校准; for lab: 申请校准 (link to detail page). Let's just have 详情 button plus quick action. **instrument_form.html** — used for both new and edit. Fields: code, name, model, accuracy_class, manufacturer, location, cycle_months, remind_days, initial_cal_date, state, keeper, remark. **instrument_detail.html** Info grid + history table + requests table + action panel. **calibrate.html** — form. **requests.html** — table. **request_detail.html** — info + action forms. **notifications.html** **costs.html** **reports.html** Let me now write all code carefully. One more: `role_required` decorator. ```python def login_required(f): @wraps(f) def wrapper(*a, **kw): if not session.get("user"): return redirect(url_for("login", next=request.path)) return f(*a, **kw) return wrapper def role_required(*roles): def deco(f): @wraps(f) def wrapper(*a, **kw): if not session.get("user"): return redirect(url_for("login")) if session.get("role") not in roles: flash("没有权限执行该操作", "err") return redirect(url_for("dashboard")) return f(*a, **kw) return wrapper return deco ``` Now writing seed data. Let's produce: ```python def seed(db): t = dt.date.today() def d(days): return (t - dt.timedelta(days=days)).isoformat() instruments = [ ("GZ-001","电子分析天平","BSA224S","Ⅰ级","赛多利斯","理化分析室",12,30,d(350),"active","张实验","用于标准物质称量"), ("GZ-002","数字多用表","34461A","0.05级","是德科技","电学实验室",12,30,d(400),"active","张实验",""), ("GZ-003","温湿度记录仪","WS-2","±0.5℃","华控仪器","样品间",12,45,d(100),"active","李计量",""), ("GZ-004","精密压力表","YB-150A","0.4级","西安仪表","压力实验室",6,20,d(200),"active","李计量",""), ("GZ-005","原子吸收分光光度计","AA-7000","--","岛津","理化分析室",24,60,None,"active","张实验","新购仪器,待首次校准"), ] ``` Check statuses: - GZ-001: last cal = t-350, next = t-350+12mo ≈ t+15 → due_soon (remind 30). ✓ - GZ-002: last cal = t-400, next ≈ t-35 → overdue. ✓ - GZ-003: last cal = t-100, next ≈ t+265 → valid. ✓ - GZ-004: initial = t-200, cycle 6 → next ≈ t-20 → overdue. ✓ (no cal records, initial date) - GZ-005: no dates → uncalibrated. ✓ Calibration records: - GZ-001: cal_date t-350, institution "省计量科学研究院", result 合格, cert "JL2024-0231", cost 800, next_due = add_months(t-350, 12) - GZ-002: cal_date t-400, institution "市计量测试所", result 合格, cert "JL2024-0188", cost 650, next_due = add_months(t-400,12) - GZ-003: cal_date t-100, institution "省计量科学研究院", result 合格, cert "JL2025-0117", cost 400, next_due = add_months(t-100,12) - also an older record for GZ-001: t-720 with cost 800, next_due add_months(t-720,12) → t-355. Good for history. Extra costs: 送检运输费 for GZ-002 120元 etc. Notifications generated on the fly. Requests: one pending from lab-user for GZ-005, one approved for GZ-002. Now let's write. I'll compute next_due in Python with add_months. Let me write the seed carefully: ```python def seed(db): t = dt.date.today() def ds(days): return (t - dt.timedelta(days=days)).isoformat() def nxt(cal_date_str, months): return add_months(parse_date(cal_date_str), months).isoformat() insts = [...] for code,name,model,acc,maker,loc,cycle,remind,init,state,keeper,remark in insts: db.execute("INSERT INTO instruments(code,name,model,accuracy_class,manufacturer,location,cycle_months,remind_days,initial_cal_date,state,keeper,remark,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", (code,name,model,acc,maker,loc,cycle,remind,init,state,keeper,remark,now_str())) # map code -> id ids = {r["code"]: r["id"] for r in db.execute("SELECT id, code FROM instruments")} cals = [ ("GZ-001", ds(720), "省计量科学研究院", "合格", "JL2023-0912", 800.0, 12, "李计量", "年度周期检定"), ("GZ-001", ds(350), "省计量科学研究院", "合格", "JL2024-0231", 800.0, 12, "李计量", "年度周期检定"), ("GZ-002", ds(400), "市计量测试技术研究院", "合格", "JL2024-0188", 650.0, 12, "李计量", "年度周期检定"), ("GZ-003", ds(100), "省计量科学研究院", "合格", "JL2025-0117", 400.0, 12, "李计量", "温湿度记录仪校准"), ] for code, cd, inst, res, cert, cost, cycle, op, remark in cals: db.execute("INSERT INTO calibrations(instrument_id,cal_date,institution,result,certificate_no,cost,next_due,operator,remark,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)", (ids[code], cd, inst, res, cert, cost, nxt(cd, cycle), op, remark, now_str())) ``` For GZ-004, initial_cal_date = ds(200) with cycle 6 → next due = t-200+6mo ≈ t-20 → overdue. Good. Extra costs: ```python extras = [ ("GZ-002", "送检运输费", 120.0, ds(400), "顺丰速运", "往返运费"), ("GZ-001", "送检运输费", 150.0, ds(350), "顺丰速运", "往返运费"), ] ``` Requests: ```python db.execute("INSERT INTO requests(instrument_id,requester,reason,expect_date,status,created_at) VALUES(?,?,?,?,?,?)", (ids["GZ-005"], "lab-user", "新购仪器需进行首次校准,申请安排计量检定。", (t+dt.timedelta(days=14)).isoformat(), "pending", now_str())) db.execute("INSERT INTO requests(...)", (ids["GZ-002"], "lab-user", "仪器即将到期,申请送检。", ..., "approved", ...)) ``` with review fields for the approved one. OK. Now writing all the templates. Let me carefully produce them. I need to make sure `url_for` endpoints match function names. Endpoints: - login, logout, dashboard, instruments, instrument_new, instrument_edit, instrument_delete, instrument_detail, calibrate, requests_list, request_detail, create_request, notifications_page, notification_read, notifications_read_all, costs, cost_add, cost_delete, reports, export_csv, uploads (download). Let me write. For the costs page, need a form to add extra cost: instrument select, category, amount, occur_date, vendor, note. For report export: `/reports/export.csv?type=costs|instruments|calibrations`. Now, let me write the whole file. Also `@app.errorhandler(404)` maybe not needed. One concern: `generate_reminders` called on dashboard only. Also call it in notifications page. Fine. Let me write the code now in full. ```python # -*- coding: utf-8 -*- import calendar import csv import datetime as dt import hashlib import io import os import sqlite3 import uuid from collections import Counter import jinja2 from flask import (Flask, Response, abort, flash, g, redirect, render_template, request, send_from_directory, session, url_for) from werkzeug.utils import secure_filename ``` secure_filename might not be used; drop it to avoid lint. Actually I'll not import it. Now the templates dict. That's a big chunk. Let's write. I'll write `TEMPLATES = { "base.html": BASE_HTML, ... }` and set loader. Let me now compose each template string. Watch out for `{` `}` in CSS inside a Python string — fine since not using .format. Let me write. ```python BASE_HTML = """ {% block title %}实验室仪器校准管理系统{% endblock %} {% if session.get('user') %}
...
{% endif %}
{% with messages = get_flashed_messages(with_categories=true) %} {% for cat, msg in messages %}
{{ msg }}
{% endfor %} {% endwith %} {% block content %}{% endblock %}
""" ``` Good. Now, careful with Jinja in `url_for('notifications_page')`. Let me finalize route names: - `notifications` — but `notifications` might conflict with nothing. I'll use `notifications_page`. Write out. Now the full code. Let me be thorough but concise. For the instrument detail page requests section: show requests for this instrument. Let me write `instrument_detail.html`: ```html {% extends "base.html" %} {% block content %}

{{ inst.name }} {{ inst.code }} {{ inst.cal_status_label }}

基本信息

{{ inst.code }}
...
``` Hmm `