Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53e9ccf57d | ||
|
|
8ceb157e5e | ||
|
|
95a7f5f6ff | ||
|
|
e11eb252a4 |
@@ -0,0 +1,27 @@
|
||||
# Optional overlay for a separately approved, fresh finance integration instance.
|
||||
# Never point FINANCE_DATA at the standalone server's real database.
|
||||
services:
|
||||
backend:
|
||||
environment:
|
||||
FINANCE_SSO_ENABLED: "true"
|
||||
FINANCE_SSO_SECRET: ${FINANCE_SSO_SECRET}
|
||||
FINANCE_SSO_CALLBACK_URL: ${FINANCE_PUBLIC_URL}/portal-sso
|
||||
finance:
|
||||
image: ${FINANCE_IMAGE}
|
||||
container_name: jinniu-finance-portal-integration
|
||||
ports: ["${TEST_HOST}:18124:4173"]
|
||||
environment:
|
||||
PORTAL_SSO_ENABLED: "1"
|
||||
PORTAL_SSO_SECRET: ${FINANCE_SSO_SECRET}
|
||||
PORTAL_INTERNAL_URL: http://backend:8000
|
||||
PORTAL_PUBLIC_URL: http://${TEST_HOST}:18091
|
||||
APP_DB_PATH: /app/data/app.db
|
||||
APP_STORAGE_DIR: /app/data/files
|
||||
volumes:
|
||||
- ${FINANCE_SOURCE}/server.py:/app/server.py:ro
|
||||
- ${FINANCE_SOURCE}/src:/app/src:ro
|
||||
- ${FINANCE_SOURCE}/web:/app/web:ro
|
||||
- ${FINANCE_DATA}:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/healthz',timeout=3)"]
|
||||
depends_on: [backend]
|
||||
@@ -0,0 +1,13 @@
|
||||
# 统一门户适配(2026-09-22)
|
||||
|
||||
分支 feature/portal-integration,基于 main 6eccbe9。代码完成但尚未替换外网测试实例;部署方向等待用户决定。
|
||||
|
||||
`PORTAL_SSO_ENABLED=1` 开启门户模式;必须配置独立的 PORTAL_SSO_SECRET、PORTAL_INTERNAL_URL、PORTAL_PUBLIC_URL。若使用 HTTPS,部署时还需相应安全 Cookie 配置。门户配置 FINANCE_SSO_ENABLED、FINANCE_SSO_SECRET、FINANCE_SSO_CALLBACK_URL,回调固定为 `/portal-sso`。
|
||||
|
||||
员工在门户中绑定已有财务用户的数字 ID;本地角色及 company_id 继续决定业务权限,不读取门户 admin 作为业务角色。每名员工应有独立本地账号,同一公司可有多名员工;不将多人映射到共享公司登录身份。账户停用及财务本地停用均拒绝访问。门户模式不允许原生登录、登出、改密、创建凭证或重置密码;管理员/出纳页面仍分开。
|
||||
|
||||
初始化会增量创建 portal_identity、portal_sessions 两表,不改银行流水、业务计算或原会话表。已有银行数据迁移不包含在本次工作中。全新实例须先配置测试公司和测试业务身份,再绑定门户员工;不会默认生成管理员密码。
|
||||
|
||||
候选内网部署 overlay 为 deploy/portal-integration.compose.yml,应叠加现有门户/OA融合 Compose,使用独立 FINANCE_DATA 目录并赋予容器用户 10001 写权限。健康检查使用 `/healthz`,原主页在门户模式跳回门户。FINANCE_IMAGE 应为已准备好依赖的 Python 3.12 财务镜像,代码目录通过 FINANCE_SOURCE 只读挂载。不得把候选测试实例数据路径指向现有正式或独立测试库。
|
||||
|
||||
验证命令:`PYTHONPATH=src python -m unittest discover -s tests`。本轮 395 项:391 通过、4 跳过,其中新增 6 项 SSO 回调/权限/隔离测试。外网到内网门户目前不可达,实际财务跨系统端到端部署验收待完成。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 员工与公司分配
|
||||
|
||||
门户决定员工是否可以进入财务系统;财务本地角色区分管理端和公司端。公司端员工可以暂未分配公司,一名出纳可负责多家公司,一家公司可分配多名出纳。
|
||||
|
||||
管理端“公司与账号”通过姓名和工号选择出纳。候选人必须同时满足:本地公司端角色且启用、门户仍授权财务系统、双方不可变身份绑定一致。门户不可用时拒绝保存分配,不使用过期名单继续授权。
|
||||
|
||||
`company_memberships` 是公司操作范围的唯一依据。`users.company_id` 仅保留兼容信息;公司业务接口每次请求都从分配表解析当前公司。多公司员工必须提交明确的公司范围,未分配、越权和已撤销范围均拒绝。CSV 下载也进行同样校验。浏览器按标签页保存所选公司,切换时确认并重载以清空未提交内容。
|
||||
|
||||
分配调整记录原员工和新员工 ID,不转移或重写历史业务记录。部门或岗位名称不自动授予财务管理权限。
|
||||
|
||||
迁移 11 保留原用户 ID、密码、会话及业务记录,把既有单公司关联迁入分配表。迁移禁止新增外键错误;已有孤立审计引用保持原样,不借升级重写历史。存在多公司或未分配公司员工时,回滚到旧结构会明确拒绝,需先制定人员迁移方案或恢复部署前备份。
|
||||
|
||||
验证包含真实 HTTP 的未分配拒绝、多公司范围、同公司多人、旧会话撤权、导出越权、员工停用、门户身份不匹配及迁移历史保留;另有完整回归测试和隔离页面检查。
|
||||
@@ -19,6 +19,8 @@ from bank_importer import (
|
||||
positions, reminders, settings, subjects,
|
||||
)
|
||||
from bank_importer.db import connect, migrate, transaction, utc_now
|
||||
from bank_importer import portal_sso
|
||||
from bank_importer import company_access
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
@@ -26,13 +28,13 @@ WEB_ROOT = ROOT / "web"
|
||||
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
|
||||
DB_PATH = Path(os.environ.get("APP_DB_PATH", ROOT / "data" / "app.db"))
|
||||
STORAGE_DIR = Path(os.environ.get("APP_STORAGE_DIR", ROOT / "data" / "files"))
|
||||
SESSION_COOKIE = "cw_session"
|
||||
SESSION_COOKIE = "cw_fusion_session" if portal_sso.enabled() else "cw_session"
|
||||
# Local plain-HTTP deployment: the cookie intentionally carries no Secure
|
||||
# flag (see docs/decisions/003-auth.md).
|
||||
COOKIE_FLAGS = "HttpOnly; SameSite=Lax; Path=/"
|
||||
COOKIE_FLAGS = "HttpOnly; SameSite=Lax; Path=/" + ("; Secure" if os.environ.get("PORTAL_COOKIE_SECURE") == "1" else "")
|
||||
|
||||
|
||||
class AppHandler(SimpleHTTPRequestHandler):
|
||||
class AppHandler(portal_sso.PortalMixin, SimpleHTTPRequestHandler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, directory=str(WEB_ROOT), **kwargs)
|
||||
|
||||
@@ -44,6 +46,15 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
parsed = urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = parse_qs(parsed.query)
|
||||
if path == "/healthz":
|
||||
self._send_json(200, {"status": "ok"})
|
||||
return
|
||||
if path == "/portal-sso":
|
||||
self._portal_callback(query, DB_PATH)
|
||||
return
|
||||
if portal_sso.enabled() and path in {"/", "/index.html", "/login-admin.html", "/login-company.html"}:
|
||||
self._portal_redirect(portal_sso.base_url("PORTAL_PUBLIC_URL"))
|
||||
return
|
||||
|
||||
if path == "/api/me":
|
||||
self._handle_me()
|
||||
@@ -68,6 +79,9 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if path == "/api/admin/companies":
|
||||
self._handle_admin_companies()
|
||||
return
|
||||
if path == "/api/admin/company-cashiers":
|
||||
self._handle_company_cashiers()
|
||||
return
|
||||
if path == "/api/admin/users":
|
||||
self._handle_admin_users()
|
||||
return
|
||||
@@ -274,6 +288,10 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
|
||||
def do_POST(self) -> None:
|
||||
path = urlparse(self.path).path
|
||||
if portal_sso.enabled() and (path in {"/api/login", "/api/logout", "/api/password/change", "/api/admin/users"}
|
||||
or re.fullmatch(r"/api/admin/users/\d+/reset-password", path)):
|
||||
self._send_json(403, {"message": "账号和登录请前往统一门户管理。"})
|
||||
return
|
||||
|
||||
if path == "/api/login":
|
||||
self._handle_login()
|
||||
@@ -463,6 +481,11 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
token = self._session_token()
|
||||
if not token:
|
||||
return None
|
||||
if portal_sso.enabled():
|
||||
try:
|
||||
return portal_sso.resolve(connection, token)
|
||||
except Exception:
|
||||
return None # Fail closed; no local-password fallback.
|
||||
return auth.resolve_session(connection, token)
|
||||
|
||||
def _require_user(self, connection, *, pending_password_ok: bool = False):
|
||||
@@ -470,12 +493,20 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if user is None:
|
||||
self._send_json(401, {"status": "error", "message": "请先登录。"})
|
||||
return None
|
||||
if user["must_change_password"] and not pending_password_ok:
|
||||
if user["must_change_password"] and not pending_password_ok and not portal_sso.enabled():
|
||||
self._send_json(
|
||||
403,
|
||||
{"status": "error", "message": "首次登录须修改密码后才能继续操作。"},
|
||||
)
|
||||
return None
|
||||
if user['role'] == 'company' and not pending_password_ok:
|
||||
try:
|
||||
query = parse_qs(urlparse(self.path).query)
|
||||
selected = self.headers.get('X-Company-ID') or (query.get('_company_scope') or [None])[0]
|
||||
user = company_access.scoped_user(connection, user, selected)
|
||||
except ValueError as exc:
|
||||
self._send_json(403, {'status': 'error', 'code': 'company_scope_required', 'message': str(exc)})
|
||||
return None
|
||||
return user
|
||||
|
||||
def _require_admin(self, connection):
|
||||
@@ -609,6 +640,13 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
connection.close()
|
||||
|
||||
def _user_payload(self, connection, user) -> dict[str, object]:
|
||||
companies = company_access.companies_for(connection, user['id']) if user['role'] == 'company' else []
|
||||
if user['role'] == 'company':
|
||||
selected = self.headers.get('X-Company-ID')
|
||||
chosen = next((c for c in companies if str(c['id']) == selected), None)
|
||||
if chosen is None and len(companies) == 1:
|
||||
chosen = companies[0]
|
||||
user = {**dict(user), 'company_id': chosen['id'] if chosen else None}
|
||||
company_name = None
|
||||
if user["company_id"] is not None:
|
||||
company = connection.execute(
|
||||
@@ -619,9 +657,11 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
"status": "ok",
|
||||
"username": user["username"],
|
||||
"role": user["role"],
|
||||
"must_change_password": bool(user["must_change_password"]),
|
||||
"must_change_password": bool(user["must_change_password"]) and not portal_sso.enabled(),
|
||||
"company_id": user["company_id"],
|
||||
"company_name": company_name,
|
||||
"companies": companies,
|
||||
"display_name": user['display_name'],
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -1121,13 +1161,18 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
(SELECT COUNT(*) FROM bank_accounts a WHERE a.company_id = c.id)
|
||||
AS account_count,
|
||||
(SELECT GROUP_CONCAT(u.username, '、') FROM users u
|
||||
WHERE u.company_id = c.id AND u.role = 'company')
|
||||
JOIN company_memberships m ON m.user_id=u.id
|
||||
WHERE m.company_id = c.id AND u.role = 'company' AND u.status='active')
|
||||
AS usernames
|
||||
FROM companies c
|
||||
ORDER BY c.id
|
||||
"""
|
||||
).fetchall()
|
||||
self._send_json(200, {"status": "ok", "companies": [dict(row) for row in rows]})
|
||||
companies = [dict(row) for row in rows]
|
||||
for company in companies:
|
||||
company['cashier_user_ids'] = [r['user_id'] for r in connection.execute(
|
||||
'SELECT user_id FROM company_memberships WHERE company_id=? ORDER BY user_id', (company['id'],))]
|
||||
self._send_json(200, {"status": "ok", "companies": companies})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@@ -1142,6 +1187,12 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
return
|
||||
name = str(data.get("name") or "").strip()
|
||||
username = str(data.get("username") or "").strip()
|
||||
if portal_sso.enabled() and username:
|
||||
self._send_json(403, {"message": "员工账号请在统一门户建立,再配置财务权限绑定。"})
|
||||
return
|
||||
if 'cashier_user_ids' in data:
|
||||
self._save_company_members(connection, user, data)
|
||||
return
|
||||
try:
|
||||
company_id = master_data.create_company(
|
||||
connection,
|
||||
@@ -1199,6 +1250,36 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_company_cashiers(self):
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
if self._require_admin(connection) is None:
|
||||
return
|
||||
try:
|
||||
employees = company_access.candidates(connection)
|
||||
except Exception:
|
||||
self._send_json(503, {'message': '暂时无法核对门户员工权限,请稍后重试。'})
|
||||
return
|
||||
self._send_json(200, {'employees': employees})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _save_company_members(self, connection, user, data):
|
||||
try:
|
||||
available = company_access.candidates(connection)
|
||||
except Exception:
|
||||
self._send_json(503, {'message': '暂时无法核对门户员工权限,未保存更改。'})
|
||||
return
|
||||
try:
|
||||
cid = data.get('id')
|
||||
if cid is not None and type(cid) is not int:
|
||||
raise ValueError('公司编号无效。')
|
||||
cid = company_access.save_company(connection, cid, data, user, available)
|
||||
except ValueError as exc:
|
||||
self._send_json(400, {'message': str(exc)})
|
||||
return
|
||||
self._send_json(200, {'status': 'ok', 'company_id': cid})
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Bank account master data
|
||||
# ------------------------------------------------------------------
|
||||
@@ -4416,7 +4497,8 @@ def main() -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
migrate(connection)
|
||||
initial_password = ensure_bootstrap_admin(connection)
|
||||
portal_sso.migrate(connection)
|
||||
initial_password = None if portal_sso.enabled() else ensure_bootstrap_admin(connection)
|
||||
finally:
|
||||
connection.close()
|
||||
if initial_password is not None:
|
||||
|
||||
@@ -106,6 +106,7 @@ def create_user(
|
||||
role: str,
|
||||
company_id: int | None = None,
|
||||
must_change_password: bool = True,
|
||||
allow_unassigned: bool = False,
|
||||
) -> int:
|
||||
"""Create a user, enforcing the role/company binding rules. Returns the id."""
|
||||
username = username.strip()
|
||||
@@ -114,12 +115,12 @@ def create_user(
|
||||
if role not in ("admin", "company"):
|
||||
raise ValueError("角色必须是 admin 或 company。")
|
||||
if role == "company":
|
||||
if company_id is None:
|
||||
if company_id is None and not allow_unassigned:
|
||||
raise ValueError("公司账号必须绑定公司。")
|
||||
company = connection.execute(
|
||||
"SELECT id FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if company is None:
|
||||
if company_id is not None and company is None:
|
||||
raise ValueError("绑定的公司不存在。")
|
||||
elif company_id is not None:
|
||||
raise ValueError("管理员账号不能绑定公司。")
|
||||
@@ -144,6 +145,9 @@ def create_user(
|
||||
now,
|
||||
),
|
||||
)
|
||||
if role == 'company' and company_id is not None:
|
||||
connection.execute('INSERT INTO company_memberships(company_id,user_id,assigned_at) VALUES(?,?,?)',
|
||||
(company_id, cursor.lastrowid, now))
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ValueError("用户名已存在。") from exc
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Explicit many-to-many company assignments; no company means no business access."""
|
||||
import json
|
||||
|
||||
from . import auth, master_data, portal_sso
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
def companies_for(connection, user_id):
|
||||
return [dict(r) for r in connection.execute(
|
||||
"SELECT c.id,c.name FROM company_memberships m JOIN companies c ON c.id=m.company_id "
|
||||
"WHERE m.user_id=? AND c.status='active' ORDER BY c.id", (user_id,))]
|
||||
|
||||
|
||||
def scoped_user(connection, user, selected=None):
|
||||
if user['role'] != 'company':
|
||||
return user
|
||||
companies = companies_for(connection, user['id'])
|
||||
ids = {str(c['id']) for c in companies}
|
||||
if selected is not None and selected not in ids:
|
||||
raise ValueError('该公司的操作权限已失效,请重新选择公司。')
|
||||
if selected is None:
|
||||
if not companies:
|
||||
raise ValueError('尚未分配负责公司,请联系财务管理员。')
|
||||
if len(companies) > 1:
|
||||
raise ValueError('请先选择本次操作的公司。')
|
||||
selected = str(companies[0]['id'])
|
||||
return {**dict(user), 'company_id': int(selected)}
|
||||
|
||||
|
||||
def candidates(connection):
|
||||
rows = [dict(r) for r in connection.execute(
|
||||
"SELECT id,username,display_name FROM users WHERE role='company' AND status='active' ORDER BY username")]
|
||||
if not portal_sso.enabled():
|
||||
return rows
|
||||
# Read current portal grants rather than trusting an old synchronized flag.
|
||||
identities = portal_sso.call('directory', {})['employees']
|
||||
eligible = {}
|
||||
for identity in identities:
|
||||
pin = connection.execute('SELECT empid FROM portal_identity WHERE uid=?', (identity['local_uid'],)).fetchone()
|
||||
if pin and pin['empid'] == identity['empid']:
|
||||
eligible[identity['local_uid']] = identity
|
||||
return [{**r, 'username': eligible[r['id']]['username'],
|
||||
'display_name': eligible[r['id']]['display_name']} for r in rows if r['id'] in eligible]
|
||||
|
||||
|
||||
def validate_members(value, available):
|
||||
if not isinstance(value, list) or any(type(i) is not int for i in value):
|
||||
raise ValueError('请选择有效的出纳员工。')
|
||||
ids = set(value)
|
||||
if len(ids) != len(value) or not ids.issubset({u['id'] for u in available}):
|
||||
raise ValueError('所选员工已停用、未获财务公司端权限或身份绑定无效,请刷新后重选。')
|
||||
return sorted(ids)
|
||||
|
||||
|
||||
def replace_members(connection, company_id, ids, actor):
|
||||
with transaction(connection):
|
||||
before = [r['user_id'] for r in connection.execute(
|
||||
'SELECT user_id FROM company_memberships WHERE company_id=? ORDER BY user_id', (company_id,))]
|
||||
connection.execute('DELETE FROM company_memberships WHERE company_id=?', (company_id,))
|
||||
connection.executemany('INSERT INTO company_memberships(company_id,user_id,assigned_at,assigned_by) VALUES(?,?,?,?)',
|
||||
[(company_id, uid, utc_now(), actor['id']) for uid in ids])
|
||||
# Legacy column is informational only; all company-side requests use memberships.
|
||||
for uid in set(before) | set(ids):
|
||||
connection.execute('UPDATE users SET company_id=(SELECT MIN(company_id) FROM company_memberships WHERE user_id=?) WHERE id=?', (uid, uid))
|
||||
if before != ids:
|
||||
auth.audit(connection, 'company_members_changed', actor=actor, target=f'company:{company_id}',
|
||||
detail=json.dumps({'before': before, 'after': ids}))
|
||||
|
||||
|
||||
def save_company(connection, company_id, data, actor, available):
|
||||
ids = validate_members(data.get('cashier_user_ids', []), available)
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('公司名称不能为空。')
|
||||
credit = str(data.get('credit_code') or '').strip()
|
||||
names = '、'.join(u['display_name'] or u['username'] for u in available if u['id'] in ids)
|
||||
with transaction(connection):
|
||||
if company_id is None:
|
||||
company_id = master_data.create_company(connection, name, credit, names, actor)
|
||||
else:
|
||||
before = connection.execute('SELECT * FROM companies WHERE id=?', (company_id,)).fetchone()
|
||||
if before is None:
|
||||
raise ValueError('公司不存在。')
|
||||
duplicate = connection.execute('SELECT id FROM companies WHERE name=? AND id<>?', (name, company_id)).fetchone()
|
||||
if duplicate:
|
||||
raise ValueError('公司名称已存在。')
|
||||
connection.execute('UPDATE companies SET name=?,credit_code=?,cashier_name=?,updated_at=? WHERE id=?',
|
||||
(name, credit, names, utc_now(), company_id))
|
||||
after = connection.execute('SELECT * FROM companies WHERE id=?', (company_id,)).fetchone()
|
||||
master_data.record_change(connection, 'company', company_id, 'update', dict(before), dict(after), '更新公司资料和负责出纳', actor)
|
||||
replace_members(connection, company_id, ids, actor)
|
||||
return company_id
|
||||
@@ -1226,6 +1226,57 @@ MIGRATIONS: tuple[Migration, ...] = (
|
||||
)
|
||||
|
||||
|
||||
# Rebuild users without the old mandatory single-company constraint. IDs and
|
||||
# all referenced history survive; membership rows become the authority.
|
||||
MIGRATIONS += (Migration(
|
||||
version=11, name="0011_employee_company_memberships",
|
||||
up="""
|
||||
CREATE TABLE users_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL CHECK(role IN ('admin','company')),
|
||||
company_id INTEGER REFERENCES companies(id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','disabled')),
|
||||
must_change_password INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
CHECK(role != 'admin' OR company_id IS NULL)
|
||||
);
|
||||
INSERT INTO users_new(id,username,password_hash,role,company_id,status,must_change_password,created_at,updated_at)
|
||||
SELECT id,username,password_hash,role,company_id,status,must_change_password,created_at,updated_at FROM users;
|
||||
DROP TABLE users;
|
||||
ALTER TABLE users_new RENAME TO users;
|
||||
CREATE TABLE company_memberships (
|
||||
company_id INTEGER NOT NULL REFERENCES companies(id),
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
assigned_at TEXT NOT NULL,
|
||||
assigned_by INTEGER REFERENCES users(id),
|
||||
PRIMARY KEY(company_id,user_id)
|
||||
);
|
||||
CREATE INDEX company_memberships_user ON company_memberships(user_id);
|
||||
INSERT INTO company_memberships(company_id,user_id,assigned_at)
|
||||
SELECT company_id,id,updated_at FROM users WHERE role='company' AND company_id IS NOT NULL;
|
||||
""",
|
||||
down="""
|
||||
DROP TABLE company_memberships;
|
||||
CREATE TABLE users_old (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('admin','company')),
|
||||
company_id INTEGER REFERENCES companies(id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','disabled')),
|
||||
must_change_password INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
|
||||
CHECK(role != 'company' OR company_id IS NOT NULL),
|
||||
CHECK(role != 'admin' OR company_id IS NULL)
|
||||
);
|
||||
INSERT INTO users_old SELECT id,username,password_hash,role,company_id,status,must_change_password,created_at,updated_at FROM users;
|
||||
DROP TABLE users;
|
||||
ALTER TABLE users_old RENAME TO users;
|
||||
""",
|
||||
),)
|
||||
|
||||
|
||||
def connect(path: str | Path) -> sqlite3.Connection:
|
||||
db_path = Path(path)
|
||||
if str(db_path) != ":memory:":
|
||||
@@ -1270,6 +1321,26 @@ def migrate(connection: sqlite3.Connection) -> list[int]:
|
||||
for migration in MIGRATIONS:
|
||||
if migration.version in applied:
|
||||
continue
|
||||
if migration.version == 11:
|
||||
# SQLite table rebuild: disable FKs outside the transaction and
|
||||
# verify every preserved reference before committing the version.
|
||||
connection.commit()
|
||||
existing_fk_errors = {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')}
|
||||
connection.execute('PRAGMA foreign_keys=OFF')
|
||||
try:
|
||||
connection.executescript('BEGIN IMMEDIATE;\n' + migration.up)
|
||||
if {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')} - existing_fk_errors:
|
||||
raise ValueError('Company membership migration found invalid references')
|
||||
connection.execute('INSERT INTO schema_migrations(version,name,applied_at) VALUES(?,?,?)',
|
||||
(migration.version, migration.name, utc_now()))
|
||||
connection.commit()
|
||||
except Exception:
|
||||
connection.rollback()
|
||||
raise
|
||||
finally:
|
||||
connection.execute('PRAGMA foreign_keys=ON')
|
||||
newly_applied.append(migration.version)
|
||||
continue
|
||||
with connection:
|
||||
connection.executescript(migration.up)
|
||||
connection.execute(
|
||||
@@ -1287,6 +1358,28 @@ def rollback(connection: sqlite3.Connection, target_version: int = 0) -> list[in
|
||||
for migration in sorted(MIGRATIONS, key=lambda item: item.version, reverse=True):
|
||||
if migration.version <= target_version or migration.version not in applied:
|
||||
continue
|
||||
if migration.version == 11 and connection.execute(
|
||||
"SELECT u.id FROM users u LEFT JOIN company_memberships m ON m.user_id=u.id "
|
||||
"WHERE u.role='company' GROUP BY u.id HAVING COUNT(m.company_id)<>1"
|
||||
).fetchone():
|
||||
raise ValueError('Cannot roll back multi-company or unassigned employees without an explicit account migration')
|
||||
if migration.version == 11:
|
||||
connection.commit()
|
||||
existing_fk_errors = {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')}
|
||||
connection.execute('PRAGMA foreign_keys=OFF')
|
||||
try:
|
||||
connection.executescript('BEGIN IMMEDIATE;\n' + migration.down)
|
||||
if {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')} - existing_fk_errors:
|
||||
raise ValueError('Company membership rollback found invalid references')
|
||||
connection.execute('DELETE FROM schema_migrations WHERE version=?', (migration.version,))
|
||||
connection.commit()
|
||||
except Exception:
|
||||
connection.rollback()
|
||||
raise
|
||||
finally:
|
||||
connection.execute('PRAGMA foreign_keys=ON')
|
||||
reversed_versions.append(migration.version)
|
||||
continue
|
||||
with connection:
|
||||
connection.executescript(migration.down)
|
||||
connection.execute(
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Optional portal identity bridge. Financial role and company scope stay local."""
|
||||
import hashlib
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from http.cookies import SimpleCookie
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
from urllib.request import Request, build_opener, HTTPRedirectHandler
|
||||
|
||||
from . import auth
|
||||
from .db import connect
|
||||
|
||||
|
||||
def enabled():
|
||||
return os.environ.get("PORTAL_SSO_ENABLED") == "1"
|
||||
|
||||
|
||||
def base_url(name):
|
||||
value = os.environ.get(name, "").rstrip("/")
|
||||
url = urlsplit(value)
|
||||
if (url.scheme not in {"http", "https"} or not url.hostname or url.username
|
||||
or url.password or url.path or url.query or url.fragment):
|
||||
raise ValueError("Portal URL unavailable")
|
||||
return value
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def call(operation, payload):
|
||||
secret = os.environ.get("PORTAL_SSO_SECRET", "")
|
||||
if len(secret) < 32:
|
||||
raise ValueError("Portal secret unavailable")
|
||||
req = Request(base_url("PORTAL_INTERNAL_URL") + "/api/sso/apps/finance/" + operation,
|
||||
data=json.dumps(payload).encode(),
|
||||
headers={"Content-Type": "application/json", "Authorization": "Bearer " + secret})
|
||||
with build_opener(NoRedirect).open(req, timeout=5) as response:
|
||||
body = response.read(32769)
|
||||
if len(body) > 32768:
|
||||
raise ValueError("Invalid portal response")
|
||||
return json.loads(body)
|
||||
|
||||
|
||||
def migrate(connection):
|
||||
connection.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS portal_identity (
|
||||
uid INTEGER PRIMARY KEY REFERENCES users(id), empid TEXT UNIQUE NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS portal_sessions (
|
||||
token_hash TEXT PRIMARY KEY, handle TEXT NOT NULL,
|
||||
empid TEXT NOT NULL, uid INTEGER NOT NULL REFERENCES users(id)
|
||||
);
|
||||
""")
|
||||
|
||||
|
||||
def resolve(connection, token):
|
||||
user = auth.resolve_session(connection, token)
|
||||
if user is None:
|
||||
return None
|
||||
row = connection.execute("SELECT * FROM portal_sessions WHERE token_hash=?",
|
||||
(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
result = call("introspect", {"session_handle": row["handle"]})
|
||||
who = result.get("identity") or {}
|
||||
if (not result.get("active") or who.get("local_uid") != user["id"]
|
||||
or who.get("empid") != row["empid"] or row["uid"] != user["id"]):
|
||||
auth.revoke_session(connection, token)
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
class PortalMixin:
|
||||
def _portal_error(self, status, message):
|
||||
home = html.escape(base_url("PORTAL_PUBLIC_URL"), quote=True)
|
||||
body = ('<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
|
||||
'<title>金牛财务往来</title><p>' + html.escape(message)
|
||||
+ '</p><a href="' + home + '">返回统一门户</a></html>').encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _portal_redirect(self, target, cookie=None):
|
||||
self.send_response(303)
|
||||
self.send_header("Location", target)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
if cookie:
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def _portal_callback(self, query, db_path):
|
||||
if not enabled():
|
||||
self.send_error(404)
|
||||
return
|
||||
secure = "; Secure" if os.environ.get("PORTAL_COOKIE_SECURE") == "1" else ""
|
||||
flags = "; HttpOnly; SameSite=Lax; Path=/portal-sso" + secure
|
||||
if "ticket" not in query:
|
||||
verifier = secrets.token_hex(32)
|
||||
theme = "night" if query.get("theme") == ["night"] else "day"
|
||||
self._portal_redirect(base_url("PORTAL_PUBLIC_URL") + "/api/sso/apps/finance/authorize?"
|
||||
+ urlencode({"challenge": hashlib.sha256(verifier.encode()).hexdigest()}),
|
||||
"cw_portal_proof=" + verifier + "." + theme + flags + "; Max-Age=120")
|
||||
return
|
||||
cookie = SimpleCookie()
|
||||
cookie.load(self.headers.get("Cookie", ""))
|
||||
proof = cookie.get("cw_portal_proof")
|
||||
parts = proof.value.split(".") if proof else []
|
||||
ticket = query["ticket"][0]
|
||||
if len(parts) != 2 or not re.fullmatch("[a-f0-9]{64}", parts[0]) or not re.fullmatch("[a-f0-9]{64}", ticket):
|
||||
self._portal_error(401, "登录请求已失效,请从统一门户重新进入。")
|
||||
return
|
||||
connection = connect(db_path)
|
||||
try:
|
||||
result = call("exchange", {"ticket": ticket, "verifier": parts[0]})
|
||||
who = result["identity"]
|
||||
handle = result["session_handle"]
|
||||
if not re.fullmatch("[a-f0-9]{64}", handle) or not re.fullmatch("[a-f0-9-]{36}", who["empid"]):
|
||||
raise ValueError("Invalid identity")
|
||||
user = connection.execute("SELECT * FROM users WHERE id=? AND status='active'", (who["local_uid"],)).fetchone()
|
||||
if user is None:
|
||||
raise ValueError("Local account unavailable")
|
||||
with connection:
|
||||
connection.execute("INSERT OR IGNORE INTO portal_identity(uid,empid) VALUES (?,?)", (user["id"], who["empid"]))
|
||||
binding = connection.execute("SELECT empid FROM portal_identity WHERE uid=?", (user["id"],)).fetchone()
|
||||
if not binding or binding["empid"] != who["empid"]:
|
||||
raise ValueError("Binding mismatch")
|
||||
token = auth.create_session(connection, user["id"])
|
||||
with connection:
|
||||
connection.execute("INSERT INTO portal_sessions(token_hash,handle,empid,uid) VALUES (?,?,?,?)",
|
||||
(hashlib.sha256(token.encode()).hexdigest(), handle, who["empid"], user["id"]))
|
||||
connection.execute("DELETE FROM portal_sessions WHERE token_hash NOT IN (SELECT token_hash FROM sessions)")
|
||||
auth.audit(connection, "portal_login", actor=user, detail=who["empid"])
|
||||
target = "/admin.html" if user["role"] == "admin" else "/company.html"
|
||||
theme = "night" if parts[1] == "night" else "day"
|
||||
self.send_response(303)
|
||||
self._set_session_cookie(token)
|
||||
self.send_header("Set-Cookie", "cw_portal_proof=" + flags + "; Max-Age=0")
|
||||
self.send_header("Location", target + "?theme=" + theme)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
except Exception:
|
||||
self._portal_error(401, "无法进入,请检查门户授权、账号绑定及子系统可用状态。")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def send_head(self):
|
||||
# Serve the existing two business surfaces, with account controls hidden
|
||||
# before first paint. The API gate separately blocks native credentials.
|
||||
path = urlsplit(self.path).path
|
||||
if enabled() and path in {"/admin.html", "/company.html"}:
|
||||
from pathlib import Path
|
||||
body = Path(self.directory, path[1:]).read_text(encoding="utf-8")
|
||||
home = base_url("PORTAL_PUBLIC_URL")
|
||||
script = '<script>window.PORTAL_HOME=' + json.dumps(home) + ';</script>'
|
||||
style = '<style>.account-box,.portal-native-account{display:none!important}</style>'
|
||||
style += '<link rel="stylesheet" href="/portal-return.css?v=20260924">'
|
||||
style += '<style>.topbar.jn-portal-bar{position:sticky;padding-top:10px;padding-bottom:10px}</style>'
|
||||
body = body.replace('</head>', script + style + '</head>')
|
||||
portal_link = '<a class="jn-portal-return" data-return-portal title="返回统一门户" aria-label="返回统一门户" href="' + html.escape(home, quote=True) + '"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1Z"/></svg><span>统一门户</span></a>'
|
||||
body = body.replace('<div class="topbar">', '<div class="topbar jn-portal-bar">' + portal_link)
|
||||
data = body.encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
return io.BytesIO(data)
|
||||
return super().send_head()
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
# Callback URLs contain short-lived credentials. Never write them to logs.
|
||||
if urlsplit(self.path).path == "/portal-sso":
|
||||
return
|
||||
super().log_message(fmt, *args)
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -13,6 +14,7 @@ from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
class LedgerBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._source_file_sequence = 0
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
@@ -66,13 +68,15 @@ class LedgerBase(unittest.TestCase):
|
||||
summary: str | None = None,
|
||||
purpose: str | None = None,
|
||||
) -> int:
|
||||
self._source_file_sequence = getattr(self, "_source_file_sequence", 0) + 1
|
||||
fixture_hash = hashlib.sha256(f"ledger-fixture-{self._source_file_sequence}".encode()).hexdigest()
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, '测试.xlsx', 1, 'data/files/测试.xlsx', ?)
|
||||
""",
|
||||
(utc_now(), utc_now()),
|
||||
(fixture_hash, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Company assignments checked through real HTTP routes, including old sessions."""
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import server
|
||||
from bank_importer import auth, company_access, master_data, portal_sso
|
||||
from bank_importer.db import connect, migrate, MIGRATIONS, utc_now
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
|
||||
class CompanyMembershipTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.path = Path(self.temp.name) / 'test.db'
|
||||
self.db = connect(self.path)
|
||||
self.addCleanup(self.db.close)
|
||||
migrate(self.db)
|
||||
self.admin = auth.create_user(self.db, 'manager', 'Password123', 'admin', must_change_password=False)
|
||||
self.cashier = auth.create_user(self.db, '010013', 'Password123', 'company', allow_unassigned=True, must_change_password=False)
|
||||
self.other = auth.create_user(self.db, '010015', 'Password123', 'company', allow_unassigned=True, must_change_password=False)
|
||||
self.actor = self.db.execute('SELECT * FROM users WHERE id=?', (self.admin,)).fetchone()
|
||||
self.a, self.b, self.c = [master_data.create_company(self.db, name, '', '', self.actor) for name in ['公司甲','公司乙','公司丙']]
|
||||
self.env = patch.dict('os.environ', {'PORTAL_SSO_ENABLED':'0'})
|
||||
self.env.start(); self.addCleanup(self.env.stop)
|
||||
self.dbpatch = patch.object(server, 'DB_PATH', self.path)
|
||||
self.dbpatch.start(); self.addCleanup(self.dbpatch.stop)
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
self.httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
self.addCleanup(self.httpd.server_close); self.addCleanup(self.httpd.shutdown)
|
||||
self.client = self.client_for(self.cashier)
|
||||
self.manager = self.client_for(self.admin)
|
||||
|
||||
def client_for(self, uid):
|
||||
client = Client('127.0.0.1', self.httpd.server_port)
|
||||
client.cookies[server.SESSION_COOKIE] = auth.create_session(self.db, uid)
|
||||
return client
|
||||
|
||||
def assign(self, cid, ids):
|
||||
company_access.replace_members(self.db, cid, ids, self.actor)
|
||||
|
||||
def test_unassigned_can_see_identity_but_no_business_endpoints(self):
|
||||
status, _, body = self.client.get('/api/me')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(as_json(body)['companies'], [])
|
||||
for route in ['/api/batches','/api/flows','/api/export.csv','/api/company/workspace', '/api/company/accounts', '/api/company/intercompany/export.csv']:
|
||||
self.assertEqual(self.client.get(route)[0], 403, route)
|
||||
self.assertEqual(self.client.post_json('/api/parse', {})[0], 403)
|
||||
|
||||
def test_multiple_companies_require_explicit_scope_and_reject_forged_scope(self):
|
||||
self.assign(self.a,[self.cashier]); self.assign(self.b,[self.cashier])
|
||||
me = as_json(self.client.get('/api/me')[2])
|
||||
self.assertEqual([c['id'] for c in me['companies']], [self.a,self.b])
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
for cid in [self.a, self.b]:
|
||||
self.assertEqual(self.client.request('GET','/api/batches',headers={'X-Company-ID':str(cid)})[0],200)
|
||||
for route in ['/api/batches','/api/flows','/api/export.csv','/api/company/accounts']:
|
||||
self.assertEqual(self.client.request('GET',route,headers={'X-Company-ID':str(self.c)})[0],403)
|
||||
self.assertEqual(self.client.get(f'/api/export.csv?_company_scope={self.c}')[0],403)
|
||||
self.assertEqual(self.client.get(f'/api/export.csv?_company_scope={self.b}')[0],200)
|
||||
|
||||
def test_two_cashiers_and_revocation_apply_to_existing_session(self):
|
||||
self.assign(self.a,[self.cashier,self.other])
|
||||
other = self.client_for(self.other)
|
||||
self.assertEqual(self.client.get('/api/batches')[0],200)
|
||||
self.assertEqual(other.get('/api/batches')[0],200)
|
||||
self.assign(self.a,[self.other])
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
self.assertEqual(other.get('/api/batches')[0],200)
|
||||
audit = self.db.execute("SELECT detail FROM audit_log WHERE action='company_members_changed' ORDER BY id DESC").fetchone()
|
||||
self.assertEqual(json.loads(audit['detail'])['before'], [self.cashier,self.other])
|
||||
|
||||
def test_company_admin_assignment_is_atomic_and_role_limited(self):
|
||||
payload = {'name':'新公司','credit_code':'','cashier_user_ids':[self.cashier,self.other]}
|
||||
self.assertEqual(self.client.post_json('/api/admin/companies',payload)[0],403)
|
||||
status,_,body = self.manager.post_json('/api/admin/companies',payload)
|
||||
self.assertEqual(status,200)
|
||||
cid=as_json(body)['company_id']
|
||||
self.assertEqual(len(self.db.execute('SELECT * FROM company_memberships WHERE company_id=?',(cid,)).fetchall()),2)
|
||||
payload.update(id=cid,name='新公司改名',cashier_user_ids=[self.admin])
|
||||
self.assertEqual(self.manager.post_json('/api/admin/companies',payload)[0],400)
|
||||
self.assertEqual(self.db.execute('SELECT name FROM companies WHERE id=?',(cid,)).fetchone()[0],'新公司')
|
||||
payload['cashier_user_ids']=[]
|
||||
self.assertEqual(self.manager.post_json('/api/admin/companies',payload)[0],200)
|
||||
|
||||
def test_disabled_employee_cannot_be_assigned_and_disabled_company_denies_access(self):
|
||||
with self.db: self.db.execute("UPDATE users SET status='disabled' WHERE id=?",(self.other,))
|
||||
status,_,_=self.manager.post_json('/api/admin/companies',{'id':self.a,'name':'公司甲','cashier_user_ids':[self.other]})
|
||||
self.assertEqual(status,400)
|
||||
self.assign(self.a,[self.cashier])
|
||||
with self.db: self.db.execute("UPDATE companies SET status='disabled' WHERE id=?",(self.a,))
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
|
||||
def test_portal_directory_requires_matching_pinned_identity(self):
|
||||
portal_sso.migrate(self.db)
|
||||
with self.db: self.db.execute('INSERT INTO portal_identity(uid,empid) VALUES(?,?)',(self.cashier,'correct'))
|
||||
with patch.object(portal_sso,'enabled',return_value=True), patch.object(portal_sso,'call',return_value={'employees':[
|
||||
{'local_uid':self.cashier,'empid':'wrong','username':'010013','display_name':'某出纳'}]}):
|
||||
self.assertEqual(company_access.candidates(self.db),[])
|
||||
|
||||
|
||||
class MembershipMigrationTests(unittest.TestCase):
|
||||
def test_upgrade_preserves_preexisting_orphan_audit_instead_of_rewriting_history(self):
|
||||
db=connect(':memory:'); self.addCleanup(db.close)
|
||||
with patch('bank_importer.db.MIGRATIONS', MIGRATIONS[:-1]): migrate(db)
|
||||
db.execute('PRAGMA foreign_keys=OFF')
|
||||
with db: db.execute("INSERT INTO audit_log(actor_user_id,actor_username,action,created_at) VALUES(99,'former-employee','history',?)",(utc_now(),))
|
||||
db.execute('PRAGMA foreign_keys=ON')
|
||||
before=[tuple(r) for r in db.execute('PRAGMA foreign_key_check')]
|
||||
self.assertEqual(len(before),1)
|
||||
migrate(db)
|
||||
self.assertEqual([tuple(r) for r in db.execute('PRAGMA foreign_key_check')],before)
|
||||
self.assertEqual(db.execute('SELECT actor_username FROM audit_log').fetchone()[0],'former-employee')
|
||||
|
||||
def test_upgrade_keeps_ids_passwords_sessions_and_audit_history(self):
|
||||
db=connect(':memory:')
|
||||
self.addCleanup(db.close)
|
||||
with patch('bank_importer.db.MIGRATIONS', MIGRATIONS[:-1]): migrate(db)
|
||||
now=utc_now()
|
||||
with db:
|
||||
db.execute('INSERT INTO companies(id,name,created_at,updated_at) VALUES(7,?,?,?)',('历史公司',now,now))
|
||||
db.execute("INSERT INTO users(id,username,password_hash,role,company_id,created_at,updated_at) VALUES(9,'old','unchanged','company',7,?,?)",(now,now))
|
||||
db.execute("INSERT INTO audit_log(actor_user_id,actor_username,action,created_at) VALUES(9,'old','history',?)",(now,))
|
||||
token=auth.create_session(db,9)
|
||||
migrate(db)
|
||||
self.assertEqual(auth.resolve_session(db,token)['id'],9)
|
||||
self.assertEqual(db.execute('SELECT password_hash FROM users WHERE id=9').fetchone()[0],'unchanged')
|
||||
self.assertEqual(company_access.companies_for(db,9),[{'id':7,'name':'历史公司'}])
|
||||
self.assertEqual(db.execute('PRAGMA foreign_key_check').fetchall(),[])
|
||||
self.assertEqual(migrate(db),[])
|
||||
@@ -5,6 +5,7 @@ idempotency, concurrency, Decimal precision and B-44 eligibility."""
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
@@ -17,6 +18,7 @@ from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
class MatchingBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._source_file_sequence = 0
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
@@ -74,13 +76,15 @@ class MatchingBase(unittest.TestCase):
|
||||
summary: str | None = None,
|
||||
sheet: str = "流水",
|
||||
) -> int:
|
||||
self._source_file_sequence = getattr(self, "_source_file_sequence", 0) + 1
|
||||
fixture_hash = hashlib.sha256(f"matching-fixture-{self._source_file_sequence}".encode()).hexdigest()
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, '测试.xlsx', 1, 'data/files/测试.xlsx', ?)
|
||||
""",
|
||||
(utc_now(), utc_now()),
|
||||
(fixture_hash, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
|
||||
@@ -41,7 +41,7 @@ class PersistenceTestCase(unittest.TestCase):
|
||||
class MigrationTests(PersistenceTestCase):
|
||||
def test_migrate_creates_schema_and_is_idempotent(self) -> None:
|
||||
first = applied_versions(self.connection)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], first)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], first)
|
||||
self.assertEqual([], migrate(self.connection))
|
||||
self.assertEqual(first, applied_versions(self.connection))
|
||||
tables = {
|
||||
@@ -98,14 +98,14 @@ class MigrationTests(PersistenceTestCase):
|
||||
self.assertIn(table, tables)
|
||||
|
||||
def test_rollback_removes_schema_and_forward_rebuilds_it(self) -> None:
|
||||
self.assertEqual([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], rollback(self.connection, 0))
|
||||
self.assertEqual([11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], rollback(self.connection, 0))
|
||||
self.assertEqual([], applied_versions(self.connection))
|
||||
remaining = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_rows'"
|
||||
).fetchone()
|
||||
self.assertIsNone(remaining)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], migrate(self.connection))
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], applied_versions(self.connection))
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], migrate(self.connection))
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], applied_versions(self.connection))
|
||||
|
||||
def test_rollback_to_4_keeps_bank_evidence_and_drops_event_layer(self) -> None:
|
||||
self.import_sample()
|
||||
@@ -113,7 +113,7 @@ class MigrationTests(PersistenceTestCase):
|
||||
"SELECT COUNT(*) AS n FROM source_rows"
|
||||
).fetchone()["n"]
|
||||
self.assertGreater(row_count, 0)
|
||||
self.assertEqual([10, 9, 8, 7, 6, 5], rollback(self.connection, 4))
|
||||
self.assertEqual([11, 10, 9, 8, 7, 6, 5], rollback(self.connection, 4))
|
||||
# The pre-migration evidence and schema are untouched.
|
||||
self.assertEqual(
|
||||
row_count,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import hashlib
|
||||
from http.client import HTTPConnection
|
||||
from http.cookies import SimpleCookie
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from bank_importer import auth, portal_sso
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
import server
|
||||
from test_server_auth import Client
|
||||
|
||||
|
||||
class PortalSsoTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.db_path = Path(self.temp.name) / 'app.db'
|
||||
self.db = connect(self.db_path)
|
||||
self.addCleanup(self.db.close)
|
||||
migrate(self.db)
|
||||
portal_sso.migrate(self.db)
|
||||
with self.db:
|
||||
self.db.execute('INSERT INTO companies(name,created_at,updated_at) VALUES (?,?,?)', ('测试公司甲', utc_now(), utc_now()))
|
||||
self.db.execute('INSERT INTO companies(name,created_at,updated_at) VALUES (?,?,?)', ('测试公司乙', utc_now(), utc_now()))
|
||||
self.uid = auth.create_user(self.db, 'staff-a', 'UnusedPass123', 'company', company_id=1)
|
||||
self.token = auth.create_session(self.db, self.uid)
|
||||
self.empid = '11111111-2222-3333-4444-555555555555'
|
||||
self.claims = {'active': True, 'identity': {'empid': self.empid, 'local_uid': self.uid}}
|
||||
self.env = patch.dict(os.environ, {'PORTAL_SSO_ENABLED': '1', 'PORTAL_PUBLIC_URL': 'http://portal.test'})
|
||||
self.env.start()
|
||||
self.addCleanup(self.env.stop)
|
||||
|
||||
def bind_session(self):
|
||||
with self.db:
|
||||
self.db.execute('INSERT INTO portal_sessions VALUES (?,?,?,?)',
|
||||
(hashlib.sha256(self.token.encode()).hexdigest(), 'a' * 64, self.empid, self.uid))
|
||||
|
||||
def test_native_session_does_not_bypass_portal(self):
|
||||
with patch.object(portal_sso, 'call') as call:
|
||||
self.assertIsNone(portal_sso.resolve(self.db, self.token))
|
||||
call.assert_not_called()
|
||||
|
||||
def test_native_role_and_company_are_retained(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', return_value=self.claims):
|
||||
user = portal_sso.resolve(self.db, self.token)
|
||||
self.assertEqual('company', user['role'])
|
||||
self.assertEqual(1, user['company_id'])
|
||||
|
||||
def test_revocation_mismatch_and_local_disable_reject(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', return_value={'active': False}):
|
||||
self.assertIsNone(portal_sso.resolve(self.db, self.token))
|
||||
self.assertIsNone(auth.resolve_session(self.db, self.token))
|
||||
|
||||
def test_portal_outage_does_not_fallback(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', side_effect=TimeoutError):
|
||||
with self.assertRaises(TimeoutError):
|
||||
portal_sso.resolve(self.db, self.token)
|
||||
|
||||
def test_http_guards_company_scope_and_hidden_credentials(self):
|
||||
self.bind_session()
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
with patch.object(server, 'DB_PATH', self.db_path), patch.object(portal_sso, 'call', return_value=self.claims):
|
||||
httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = Client('127.0.0.1', httpd.server_port)
|
||||
self.assertEqual(401, client.get('/api/company/accounts')[0])
|
||||
client.cookies[server.SESSION_COOKIE] = self.token
|
||||
self.assertEqual(200, client.get('/api/company/accounts?company_id=2')[0])
|
||||
self.assertEqual(403, client.get('/api/admin/companies')[0])
|
||||
status, _, data = client.get('/api/me')
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual(1, json.loads(data)['company_id'])
|
||||
for path in ['/api/login', '/api/logout', '/api/password/change', '/api/admin/users', '/api/admin/users/1/reset-password']:
|
||||
self.assertEqual(403, client.post_json(path, {})[0])
|
||||
status, _, data = client.get('/company.html')
|
||||
self.assertEqual(200, status)
|
||||
self.assertIn(b'data-return-portal', data)
|
||||
self.assertIn(b'display:none!important', data)
|
||||
self.assertEqual('http://portal.test', client.get('/login-company.html')[1]['location'])
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_callback_checks_browser_proof_and_pins_local_identity(self):
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
def response(operation, payload):
|
||||
if operation == 'exchange':
|
||||
self.assertEqual('a' * 64, payload['verifier'])
|
||||
return {'session_handle': 'b' * 64, 'identity': self.claims['identity']}
|
||||
return self.claims
|
||||
with patch.object(server, 'DB_PATH', self.db_path), patch.object(portal_sso, 'call', side_effect=response):
|
||||
httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = Client('127.0.0.1', httpd.server_port)
|
||||
status, headers, _ = client.get('/portal-sso?theme=night')
|
||||
self.assertEqual(303, status)
|
||||
self.assertIn('/api/sso/apps/finance/authorize?challenge=', headers['location'])
|
||||
client.cookies.clear()
|
||||
status, _, body = client.get('/portal-sso?ticket=' + 'c' * 64)
|
||||
self.assertEqual(401, status)
|
||||
self.assertIn(b'http://portal.test', body)
|
||||
conn = HTTPConnection('127.0.0.1', httpd.server_port)
|
||||
conn.request('GET', '/portal-sso?ticket=' + 'c' * 64,
|
||||
headers={'Cookie': 'cw_portal_proof=' + 'a' * 64 + '.night'})
|
||||
res = conn.getresponse()
|
||||
self.assertEqual(303, res.status)
|
||||
self.assertEqual('/company.html?theme=night', res.getheader('Location'))
|
||||
for key, value in res.getheaders():
|
||||
if key.lower() == 'set-cookie':
|
||||
cookies = SimpleCookie(value)
|
||||
if server.SESSION_COOKIE in cookies:
|
||||
client.cookies[server.SESSION_COOKIE] = cookies[server.SESSION_COOKIE].value
|
||||
res.read()
|
||||
conn.close()
|
||||
self.assertEqual(1, json.loads(client.get('/api/me')[2])['company_id'])
|
||||
self.assertEqual(self.empid, self.db.execute('SELECT empid FROM portal_identity WHERE uid=?', (self.uid,)).fetchone()['empid'])
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
thread.join()
|
||||
@@ -477,7 +477,7 @@ class MigrationTests(unittest.TestCase):
|
||||
versions = connection.execute(
|
||||
"SELECT version FROM schema_migrations ORDER BY version"
|
||||
).fetchall()
|
||||
self.assertEqual(10, versions[-1]["version"])
|
||||
self.assertEqual(11, versions[-1]["version"])
|
||||
connection.execute("DELETE FROM schema_migrations WHERE version = 10")
|
||||
connection.executescript(
|
||||
"""
|
||||
|
||||
+14
-26
@@ -205,8 +205,8 @@
|
||||
</div>
|
||||
<div class="detail-box row-between" style="margin-top: 12px;">
|
||||
<div>
|
||||
<div style="font-weight: 650;">金牛农业 → 应收 386.24 万元</div>
|
||||
<div class="meta" style="margin-top: 2px;">14 笔(借 9 / 贷 5)· 最早未结 2026-03-12</div>
|
||||
<div style="font-weight: 650;">查看所选公司的实际往来</div>
|
||||
<div class="meta" style="margin-top: 2px;">金额、统计截止日及未解决事项以往来查询结果为准</div>
|
||||
</div>
|
||||
<button class="btn btn-sm" data-view-link="pair">查看逐笔往来</button>
|
||||
</div>
|
||||
@@ -217,9 +217,9 @@
|
||||
<span class="card-title">账期与结账<span class="sub" id="dashboardPeriodSub">每月 5 日结账 · 全局起算日 2026-01-01</span></span>
|
||||
</div>
|
||||
<dl class="kv">
|
||||
<dt>当前账期</dt><dd>2026-07 · 进行中</dd>
|
||||
<dt>结账日</dt><dd style="color: var(--warn); font-weight: 650;">2026-08-29(顺延)· 距今 9 天</dd>
|
||||
<dt>上一账期</dt><dd>2026-06 · 已于 07-03 结账</dd>
|
||||
<dt>待结账期</dt><dd id="dashboardClosePeriod">正在读取</dd>
|
||||
<dt>结账状态</dt><dd id="dashboardCloseStatus">正在读取</dd>
|
||||
<dt>最近结账</dt><dd id="dashboardCloseHistory">正在读取</dd>
|
||||
</dl>
|
||||
<button class="btn" data-view-link="settings" style="width: 100%; margin-top: 14px;">进入结账检查</button>
|
||||
</div>
|
||||
@@ -475,7 +475,7 @@
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>公司与账号</h1>
|
||||
<p class="page-sub">集团成员公司的档案、银行账户与登录账号管理。公司新登记的银行账户须经审核中心确认后方可参与流水归集。</p>
|
||||
<p class="page-sub">管理成员公司资料及负责出纳。一家公司可分配多名出纳,每名出纳可负责多家公司。新登记的银行账户仍须审核。</p>
|
||||
</div>
|
||||
<div class="page-actions">
|
||||
<button class="btn btn-primary" id="openCompanyDialog">新增公司</button>
|
||||
@@ -493,7 +493,7 @@
|
||||
|
||||
<div class="card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">成员公司<span class="sub">数据截至 2026-08-20</span></span>
|
||||
<span class="card-title">成员公司</span>
|
||||
</div>
|
||||
<div class="table-wrap" style="border: 0;">
|
||||
<table class="ds-table" id="companyTable">
|
||||
@@ -501,7 +501,7 @@
|
||||
<tr>
|
||||
<th>公司名称</th>
|
||||
<th class="num-col">银行账户数</th>
|
||||
<th>登录账号</th>
|
||||
<th>负责员工工号</th>
|
||||
<th>出纳</th>
|
||||
<th>启用状态</th>
|
||||
<th>操作</th>
|
||||
@@ -512,7 +512,7 @@
|
||||
</div>
|
||||
<div class="table-foot" style="border: 1px solid var(--border); border-radius: 0 0 var(--radius-lg) var(--radius-lg);">
|
||||
<span id="companyFoot">共 0 家公司</span>
|
||||
<span class="meta">创建账号时生成一次性随机密码,仅当时显示一次</span>
|
||||
<span class="meta">员工账号统一在门户管理,公司操作范围在此分配</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -876,7 +876,7 @@
|
||||
<span class="modal-title">新增成员公司</span>
|
||||
<button type="button" class="modal-close" data-close="companyDialog" aria-label="关闭">×</button>
|
||||
</div>
|
||||
<p class="modal-sub">登记后可同时生成公司端登录账号。系统会发一次性随机初始密码,仅创建成功时显示一次,请当场复制后交给出纳;首次登录必须改密。没有全公司通用默认密码。</p>
|
||||
<p class="modal-sub">选择已获财务公司端权限的员工。保存后生效;移除员工会收回其对本公司的操作权限,历史记录保留。</p>
|
||||
<form id="companyForm" novalidate>
|
||||
<div class="field" style="margin-bottom: 12px;">
|
||||
<label for="f-name">公司全称</label>
|
||||
@@ -886,23 +886,11 @@
|
||||
<label for="f-code">统一社会信用代码</label>
|
||||
<input class="input num-input" id="f-code" name="creditCode" type="text" maxlength="18" placeholder="18 位,如 91410100MA9K2X417A" />
|
||||
</div>
|
||||
<label class="row" style="gap: 6px; font-size: 13px; margin-bottom: 12px; cursor: pointer;">
|
||||
<input type="checkbox" name="createUser" checked style="width: auto;" />同时创建公司账号
|
||||
</label>
|
||||
<div class="grid grid-2">
|
||||
<div class="field">
|
||||
<label for="f-login">登录账号</label>
|
||||
<input class="input" id="f-login" name="loginName" type="text" required />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="f-cashier">出纳人员</label>
|
||||
<input class="input" id="f-cashier" name="cashier" type="text" required />
|
||||
</div>
|
||||
</div>
|
||||
<p class="hint" style="margin-top: 10px;">创建成功后弹出一次性口令窗口,可复制账号和密码。关闭后无法再次查看明文,列表与日志也不会保存密码。</p>
|
||||
<fieldset class="field"><legend>负责出纳(可多选)</legend><div id="companyCashierChoices"></div></fieldset>
|
||||
<p class="hint" style="margin-top: 10px;">可先不分配出纳。未分配公司的员工进入财务系统后会看到待分配提示。</p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn" data-close="companyDialog">取消</button>
|
||||
<button type="submit" class="btn btn-primary">创建公司与账号</button>
|
||||
<button type="submit" class="btn btn-primary">保存公司与分配</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -1257,6 +1245,6 @@
|
||||
<script src="theme.js?v=1"></script>
|
||||
<script src="select.js?v=1"></script>
|
||||
<script src="datepicker.js?v=2"></script>
|
||||
<script src="app.js?v=18"></script>
|
||||
<script src="app.js?v=18-cloud1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+140
-42
@@ -2,6 +2,45 @@ const $ = (selector, scope = document) => scope.querySelector(selector);
|
||||
const $$ = (selector, scope = document) => [...scope.querySelectorAll(selector)];
|
||||
|
||||
const portal = document.body.dataset.portal || "entry";
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
const fetch = async function(input, options = {}) {
|
||||
const url = new URL(typeof input === "string" ? input : input.url, location.href);
|
||||
const headers = new Headers(options.headers);
|
||||
if (portal === "company" && state.companyId && url.origin === location.origin && url.pathname.startsWith('/api/')) {
|
||||
headers.set('X-Company-ID', String(state.companyId));
|
||||
}
|
||||
const response = await nativeFetch(input, {...options, headers});
|
||||
if (portal === 'company' && response.status === 403) {
|
||||
const result = await response.clone().json().catch(() => ({}));
|
||||
if (result.code === 'company_scope_required') {
|
||||
showCompanyWaiting(result.message);
|
||||
// Stop existing request handlers from treating this as a logout.
|
||||
return new Response(JSON.stringify(result), {status: 409, headers: {'Content-Type': 'application/json'}});
|
||||
}
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
function scopedDownload(url) {
|
||||
const result = new URL(url, location.href);
|
||||
if (portal === 'company' && state.companyId) result.searchParams.set('_company_scope', state.companyId);
|
||||
return result.pathname + result.search;
|
||||
}
|
||||
|
||||
function showCompanyWaiting(message) {
|
||||
const main = $('#main-content');
|
||||
const box = document.createElement('section');
|
||||
box.className = 'card'; box.style.padding = '24px'; box.setAttribute('role', 'status');
|
||||
const title = document.createElement('h1'); title.textContent = '公司业务端';
|
||||
const text = document.createElement('p'); text.textContent = message;
|
||||
const retry = document.createElement('button'); retry.className = 'btn'; retry.textContent = '刷新公司分配';
|
||||
retry.onclick = () => location.reload();
|
||||
const home = document.createElement('a'); home.className = 'btn'; home.textContent = '返回统一门户';
|
||||
home.href = window.PORTAL_HOME || '/';
|
||||
box.append(title, text, retry, home); main.replaceChildren(box);
|
||||
$$('.side-nav [data-view]').forEach(el => { el.hidden = true; el.style.display = 'none'; });
|
||||
$$('.modal-backdrop').forEach(el => el.classList.remove('is-open', 'open', 'show'));
|
||||
}
|
||||
const viewNames = portal === "admin"
|
||||
? { dashboard: "管理总览", pair: "往来查询", audit: "审核中心", flows: "流水管理", companies: "公司与账号", settings: "结账与期初", "period-audit": "审计记录", reminders: "提醒管理" }
|
||||
: { workspace: "工作台", upload: "流水导入", manual: "手工记录", flows: "流水管理", transfers: "转账往来", reconcile: "往来确认", accounts: "银行账户", notifications: "通知" };
|
||||
@@ -433,19 +472,42 @@ async function initAuthGuard() {
|
||||
try {
|
||||
const response = await fetch("/api/me");
|
||||
if (response.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return false;
|
||||
}
|
||||
const me = await response.json();
|
||||
if (!response.ok || me.role !== portal) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return false;
|
||||
}
|
||||
state.me = me;
|
||||
if (portal === 'company') {
|
||||
const companies = me.companies || [];
|
||||
if (!companies.length) {
|
||||
showCompanyWaiting('尚未分配负责公司,请联系财务管理员。');
|
||||
return false;
|
||||
}
|
||||
let saved;
|
||||
try { saved = sessionStorage.getItem('finance-company:' + me.username); } catch {}
|
||||
const chosen = companies.find(c => String(c.id) === saved) || companies[0];
|
||||
state.companyId = chosen.id;
|
||||
me.company_id = chosen.id; me.company_name = chosen.name;
|
||||
const label = document.createElement('label'); label.textContent = '当前公司 ';
|
||||
const select = document.createElement('select'); select.className = 'input'; select.id = 'activeCompany';
|
||||
select.setAttribute('aria-label', '当前操作公司');
|
||||
companies.forEach(c => select.add(new Option(c.name, String(c.id), false, c.id === chosen.id)));
|
||||
select.onchange = () => {
|
||||
if (!window.confirm('切换公司将清除本页尚未提交的内容,是否继续?')) { select.value = String(state.companyId); return; }
|
||||
try { sessionStorage.setItem('finance-company:' + me.username, select.value); } catch {}
|
||||
location.reload();
|
||||
};
|
||||
label.append(select); $('.topbar-right').prepend(label);
|
||||
}
|
||||
applyCompanyIdentity(me);
|
||||
return true;
|
||||
} catch {
|
||||
return true;
|
||||
if (portal === 'company') showCompanyWaiting('暂时无法核对身份和公司分配,请刷新重试。');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,7 +574,7 @@ function initShell() {
|
||||
try {
|
||||
await fetch("/api/logout", { method: "POST" });
|
||||
} catch { /* 网络异常时仍然回到登录页 */ }
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
}));
|
||||
$$("[data-metric-link]").forEach((card) => {
|
||||
const activate = () => showView(card.dataset.metricLink);
|
||||
@@ -810,7 +872,7 @@ async function loadCompanyAccounts() {
|
||||
showTableLoading(tbody, 6);
|
||||
const response = await fetch("/api/company/accounts").catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
if (!response?.ok) {
|
||||
@@ -984,7 +1046,7 @@ async function loadAdminAuditQueue() {
|
||||
]);
|
||||
|
||||
if ([accountsRes, manualsRes, exceptionsRes].some((res) => res?.status === 401)) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
if (![accountsRes, manualsRes, exceptionsRes].every((res) => res?.ok)) {
|
||||
@@ -1103,7 +1165,7 @@ function renderAdminCompanyTable(companies) {
|
||||
const badge = companyStatusBadge(company.status);
|
||||
statusCell.innerHTML = `<span class="pill ${pillClass(badge.className)}">${badge.label}</span>`;
|
||||
const actionCell = document.createElement("td");
|
||||
actionCell.innerHTML = `<button type="button" class="btn btn-sm" data-company-view="${company.id}">查看</button>`;
|
||||
actionCell.innerHTML = `<button type="button" class="btn btn-sm" data-company-view="${company.id}">查看</button> <button type="button" class="btn btn-sm" data-company-edit="${company.id}">编辑与分配出纳</button>`;
|
||||
row.append(nameCell, accounts, usernames, cashier, statusCell, actionCell);
|
||||
return row;
|
||||
}));
|
||||
@@ -1900,7 +1962,7 @@ async function loadAdminRemindersPending() {
|
||||
const sendAll = $("#pending-send-all");
|
||||
if (!list) return;
|
||||
const response = await fetch("/api/admin/reminders/pending").catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) return;
|
||||
const findings = result.findings || [];
|
||||
@@ -1957,7 +2019,7 @@ async function loadAdminRemindersHistory(sourceFilter) {
|
||||
if (!tbody) return;
|
||||
const query = sourceFilter && sourceFilter !== "all" ? `?source=${sourceFilter === "system" ? "auto" : "manual"}` : "";
|
||||
const response = await fetch(`/api/admin/reminders${query}`).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) return;
|
||||
const items = result.reminders || [];
|
||||
@@ -2002,7 +2064,7 @@ async function sendPendingReminders(keys) {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ dedupe_keys: keys }),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return null; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return null; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) {
|
||||
showToast("发送失败", result?.message || "请稍后重试", "danger");
|
||||
@@ -2054,7 +2116,7 @@ function initAdminReminders() {
|
||||
|
||||
$("#reminder-scan-btn")?.addEventListener("click", async () => {
|
||||
const response = await fetch("/api/admin/reminders/scan", { method: "POST" }).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) {
|
||||
showToast("扫描失败", result?.message || "请稍后重试", "danger");
|
||||
@@ -2138,7 +2200,7 @@ function initAdminReminders() {
|
||||
deadline: deadline || null,
|
||||
}),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) {
|
||||
showToast("发送失败", result?.message || "请稍后重试", "danger");
|
||||
@@ -2179,7 +2241,7 @@ function initAdminReminders() {
|
||||
if (!remindBtn) return;
|
||||
const tr = remindBtn.closest("tr");
|
||||
const response = await fetch(`/api/admin/reminders/${tr.dataset.reminderId}/resend`, { method: "POST" }).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) {
|
||||
showToast("再提醒失败", result?.message || "请稍后重试", "danger");
|
||||
@@ -2278,6 +2340,11 @@ function applyClosePanel(overview) {
|
||||
state.periodClose = overview;
|
||||
const close = overview.close || {};
|
||||
const ym = close.year_month || overview.target_month || "—";
|
||||
if ($("#dashboardClosePeriod")) $("#dashboardClosePeriod").textContent = ym;
|
||||
if ($("#dashboardCloseStatus")) $("#dashboardCloseStatus").textContent =
|
||||
({ closed: "已结账", closing: "处理中", failed: "结账失败", reopened: "已重开", open: "未结账" })[close.status] || "待结账检查";
|
||||
if ($("#dashboardCloseHistory")) $("#dashboardCloseHistory").textContent = overview.history
|
||||
? `${overview.history.year_month} · ${String(overview.history.closed_at || "").slice(0, 10)}` : "尚无结账记录";
|
||||
renderTimeline(overview.timeline);
|
||||
const start = state.calculationStart || "—";
|
||||
if ($("#timelineSub")) $("#timelineSub").textContent = `全局起算日 ${start} 起,每月 ${overview.closing_day || "—"} 日结账`;
|
||||
@@ -2385,9 +2452,12 @@ function applyClosePanel(overview) {
|
||||
async function loadPeriodClose() {
|
||||
if (!$("#closingPanel")) return;
|
||||
const response = await fetch("/api/admin/period-closes").catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => null);
|
||||
if (!response?.ok || result?.status !== "ok") {
|
||||
for (const id of ['dashboardClosePeriod', 'dashboardCloseStatus', 'dashboardCloseHistory']) {
|
||||
if ($(`#${id}`)) $(`#${id}`).textContent = '读取失败,请重试';
|
||||
}
|
||||
showToast("结账状态加载失败", result?.message || "请稍后重试", "danger");
|
||||
return;
|
||||
}
|
||||
@@ -2755,7 +2825,7 @@ function initAdmin() {
|
||||
body: JSON.stringify({ decision: apiDecision, reason }),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -2779,7 +2849,7 @@ function initAdmin() {
|
||||
}),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -2801,7 +2871,7 @@ function initAdmin() {
|
||||
}),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -2914,20 +2984,46 @@ function initAdmin() {
|
||||
submitAuditResult(state.auditRow);
|
||||
});
|
||||
|
||||
$("#openCompanyDialog")?.addEventListener("click", () => openModal("companyDialog"));
|
||||
async function editCompany(company = null) {
|
||||
const response = await fetch('/api/admin/company-cashiers').catch(() => null);
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) { showToast('无法加载出纳名单', result?.message || '请稍后重试', 'danger'); return; }
|
||||
const form = $('#companyForm'); form.reset();
|
||||
form.dataset.companyId = company ? String(company.id) : '';
|
||||
$('#f-name').value = company?.name || ''; $('#f-code').value = company?.credit_code || '';
|
||||
const choices = $('#companyCashierChoices'); choices.replaceChildren();
|
||||
for (const employee of result.employees) {
|
||||
const label = document.createElement('label'); label.className = 'row';
|
||||
const input = document.createElement('input'); input.type = 'checkbox'; input.name = 'cashierUser'; input.value = employee.id;
|
||||
input.checked = (company?.cashier_user_ids || []).includes(employee.id);
|
||||
label.append(input, document.createTextNode(`${employee.display_name || employee.username}(${employee.username})`));
|
||||
choices.append(label);
|
||||
}
|
||||
if (!result.employees.length) choices.textContent = '暂无已授权的公司端员工,可先保存公司资料,稍后分配。';
|
||||
const eligible = new Set(result.employees.map(e => e.id));
|
||||
if ((company?.cashier_user_ids || []).some(id => !eligible.has(id))) {
|
||||
const note = document.createElement('p'); note.textContent = '原分配中有员工已停用或失去权限,本次保存将移除这些无效分配。'; choices.append(note);
|
||||
}
|
||||
$('#companyDialog .modal-title').textContent = company ? '编辑公司与负责出纳' : '新增成员公司';
|
||||
$('#companyForm button[type="submit"]').textContent = '保存公司与分配';
|
||||
openModal('companyDialog');
|
||||
}
|
||||
$("#openCompanyDialog")?.addEventListener("click", () => editCompany());
|
||||
$("#companyForm")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = new FormData(form);
|
||||
const companyName = String(data.get("companyName") || "").trim();
|
||||
const loginName = String(data.get("loginName") || "").trim();
|
||||
const createUser = data.get("createUser") !== null;
|
||||
const createUser = !window.PORTAL_HOME && data.get("createUser") !== null;
|
||||
|
||||
const payload = {
|
||||
name: companyName,
|
||||
credit_code: String(data.get("creditCode") || "").trim(),
|
||||
cashier_name: String(data.get("cashier") || "").trim(),
|
||||
cashier_user_ids: data.getAll('cashierUser').map(Number),
|
||||
};
|
||||
if (form.dataset.companyId) payload.id = Number(form.dataset.companyId);
|
||||
if (createUser && loginName) payload.username = loginName;
|
||||
|
||||
const response = await fetch("/api/admin/companies", {
|
||||
@@ -2936,7 +3032,7 @@ function initAdmin() {
|
||||
body: JSON.stringify(payload),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -2957,7 +3053,7 @@ function initAdmin() {
|
||||
});
|
||||
showToast("公司与账号已创建", "请在一次性口令窗口复制初始密码,关闭后无法再看", "success");
|
||||
} else {
|
||||
showToast("公司已创建", "可稍后在账号管理中创建公司账号", "success");
|
||||
showToast("公司资料和出纳分配已保存", "员工从统一门户进入后即可操作负责的公司", "success");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2982,6 +3078,8 @@ function initAdmin() {
|
||||
}
|
||||
|
||||
$("#companyTable tbody")?.addEventListener("click", (event) => {
|
||||
const edit = event.target.closest('[data-company-edit]');
|
||||
if (edit) { editCompany(state.companies.find(c => String(c.id) === edit.dataset.companyEdit)); return; }
|
||||
const btn = event.target.closest("[data-company-view]");
|
||||
if (btn) openCompanyDetail(btn.dataset.companyView);
|
||||
});
|
||||
@@ -2993,7 +3091,7 @@ function initAdmin() {
|
||||
const user = (usersResult?.users || []).find((u) => String(u.company_id) === String(companyId) && u.role === "company");
|
||||
if (!user) { showToast("重置失败", "该公司尚无公司登录账号", "danger"); return; }
|
||||
const response = await fetch(`/api/admin/users/${user.id}/reset-password`, { method: "POST" }).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response || !response.ok) { showToast("重置失败", result?.message || "请稍后重试", "danger"); return; }
|
||||
$("#btn-reset-pwd").disabled = true;
|
||||
@@ -3049,7 +3147,7 @@ function initAdmin() {
|
||||
async function loadSystemSettings() {
|
||||
const response = await fetch("/api/admin/settings").catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -3084,7 +3182,7 @@ function initAdmin() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ calculation_start_date: nextStart, reason }),
|
||||
}).catch(() => null);
|
||||
if (calcResp?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (calcResp?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const calcResult = await calcResp?.json().catch(() => ({}));
|
||||
if (!calcResp?.ok) {
|
||||
showToast("起算日保存失败", calcResult?.message || "请稍后重试", "danger");
|
||||
@@ -3106,7 +3204,7 @@ function initAdmin() {
|
||||
body: JSON.stringify(payload),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -3125,7 +3223,7 @@ function initAdmin() {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ settings: { monthly_start_day: String(day || 5), gap_days: String(gapDays) } }),
|
||||
}).catch(() => null);
|
||||
if (reminderResp?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (reminderResp?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
if (!reminderResp?.ok) {
|
||||
showToast("提醒扫描参数保存失败", "", "danger");
|
||||
return;
|
||||
@@ -3234,7 +3332,7 @@ async function loadFlows() {
|
||||
if ($("#flowKeyword")?.value.trim()) params.set("keyword", $("#flowKeyword").value.trim());
|
||||
params.set("limit", "200");
|
||||
const response = await fetch(`/api/flows?${params.toString()}`).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => null);
|
||||
if (!response?.ok || result?.status !== "ok") {
|
||||
showTableError(tbody, portal === "admin" ? 9 : 8);
|
||||
@@ -3340,7 +3438,7 @@ function exportFlows() {
|
||||
const company = companyByName(companyName);
|
||||
if (company) params.set("company_id", String(company.id));
|
||||
}
|
||||
window.location.href = `/api/export.csv${params.toString() ? `?${params}` : ""}`;
|
||||
window.location.href = scopedDownload(`/api/export.csv${params.toString() ? `?${params}` : ""}`);
|
||||
showToast("开始导出", "仅含出纳已确认工作表的银行原始流水", "success");
|
||||
}
|
||||
|
||||
@@ -3415,7 +3513,7 @@ function renderCompanyManualRecords(records) {
|
||||
async function loadCompanyManualRecords() {
|
||||
if (!$("#manualRecordRows")) return;
|
||||
const response = await fetch("/api/company/manual-records").catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401 || response?.status === 403) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) {
|
||||
showToast("手工记录加载失败", result?.message || "请稍后重试", "danger");
|
||||
@@ -3493,7 +3591,7 @@ async function parseFile() {
|
||||
try {
|
||||
const response = await fetch("/api/parse", { method: "POST", body: formData });
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
result = await response.json();
|
||||
@@ -3634,7 +3732,7 @@ async function sheetReviewAction(batchId, sheetName, decision) {
|
||||
body: JSON.stringify(payload),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -3682,7 +3780,7 @@ async function confirmImport() {
|
||||
body: JSON.stringify({ sheets: pending }),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const outcome = await response?.json().catch(() => ({}));
|
||||
@@ -3764,7 +3862,7 @@ async function loadImportBatches() {
|
||||
showTableLoading(tbody, 8);
|
||||
const response = await fetch("/api/batches").catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
if (!response?.ok) {
|
||||
@@ -3894,7 +3992,7 @@ function applyCompanyWorkspace(payload) {
|
||||
async function loadCompanyWorkspace() {
|
||||
const response = await fetch("/api/company/workspace").catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return null;
|
||||
}
|
||||
const result = await response?.json().catch(() => null);
|
||||
@@ -3970,7 +4068,7 @@ function renderUnilateralMatchCard(event, peers) {
|
||||
}),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
@@ -4131,7 +4229,7 @@ function initNotifications() {
|
||||
|
||||
async function loadReminders() {
|
||||
const response = await fetch("/api/company/reminders").catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
if (!response?.ok) return;
|
||||
const items = result.reminders || [];
|
||||
@@ -4184,7 +4282,7 @@ function initNotifications() {
|
||||
if (!id) return;
|
||||
const action = readBtn ? "acknowledge" : "resolve";
|
||||
const response = await fetch(`/api/company/reminders/${id}/${action}`, { method: "POST" }).catch(() => null);
|
||||
if (response?.status === 401) { window.location.href = "index.html"; return; }
|
||||
if (response?.status === 401) { window.location.href = window.PORTAL_HOME || "index.html"; return; }
|
||||
if (!response?.ok) return;
|
||||
await loadReminders();
|
||||
});
|
||||
@@ -4340,7 +4438,7 @@ async function loadTransfersSummary({ asOf } = {}) {
|
||||
const qs = params.toString();
|
||||
const response = await fetch(`/api/company/intercompany/summary${qs ? `?${qs}` : ""}`).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return null;
|
||||
}
|
||||
const result = await response?.json().catch(() => null);
|
||||
@@ -4570,7 +4668,7 @@ async function loadTransfersEvents({ reset = false } = {}) {
|
||||
// Always need a distinguishing filter so HEL-176 path is used (counterparty_id is enough)
|
||||
const response = await fetch(`/api/company/intercompany/events?${params}`).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => null);
|
||||
@@ -4641,7 +4739,7 @@ async function openTransferEvidence(eventId) {
|
||||
drawer.setAttribute("aria-hidden", "false");
|
||||
const response = await fetch(`/api/company/transfer-events/${eventId}`).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => null);
|
||||
@@ -4709,7 +4807,7 @@ function buildTransfersExportUrl() {
|
||||
if (summary.window.end) params.set("to", summary.window.end);
|
||||
}
|
||||
const qs = params.toString();
|
||||
return `/api/company/intercompany/export.csv${qs ? `?${qs}` : ""}`;
|
||||
return scopedDownload(`/api/company/intercompany/export.csv${qs ? `?${qs}` : ""}`);
|
||||
}
|
||||
|
||||
function initTransfers() {
|
||||
@@ -4974,7 +5072,7 @@ function initCompany() {
|
||||
}),
|
||||
}).catch(() => null);
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
window.location.href = "index.html";
|
||||
window.location.href = window.PORTAL_HOME || "index.html";
|
||||
return;
|
||||
}
|
||||
const result = await response?.json().catch(() => ({}));
|
||||
|
||||
+13
-30
@@ -72,7 +72,7 @@
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>工作台</h1>
|
||||
<p class="page-sub"><span class="company-identity">河南金牛煤业有限公司</span> · 2026 年 7 月账期。本月 18 项账期任务已完成 13 项,剩余 4 项待办,其中 3 项阻断结账。</p>
|
||||
<p class="page-sub"><span class="company-identity">当前公司</span> · 下方仅显示当前所选公司的待办与业务信息。</p>
|
||||
</div>
|
||||
<div class="page-actions">
|
||||
<button class="btn" data-open-upload>上传流水</button>
|
||||
@@ -82,19 +82,18 @@
|
||||
|
||||
<div class="card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">账期流程 · 2026-07<span class="sub" id="workspaceFlowSub">当前停在第 3 步「往来确认」,完成后即可等待集团结账</span></span>
|
||||
<span class="pill pill-warn">结账日顺延至 08-29</span>
|
||||
<span class="card-title">业务流程<span class="sub" id="workspaceFlowSub">正在读取待确认往来</span></span>
|
||||
</div>
|
||||
<div class="flow">
|
||||
<a class="flow-step part" data-view-link="upload" href="#upload">
|
||||
<a class="flow-step" data-view-link="upload" href="#upload">
|
||||
<div class="fs-top"><span class="fs-idx">01</span><span class="fs-dot"></span><span class="fs-name">流水导入</span></div>
|
||||
<div class="fs-state">部分完成</div>
|
||||
<div class="fs-meta">2/3 账户已覆盖 · 交行 7710 待审核</div>
|
||||
<div class="fs-state">查看流水</div>
|
||||
<div class="fs-meta">选择本公司已审核银行账户上传</div>
|
||||
</a>
|
||||
<a class="flow-step done" data-view-link="manual" href="#manual">
|
||||
<a class="flow-step" data-view-link="manual" href="#manual">
|
||||
<div class="fs-top"><span class="fs-idx">02</span><span class="fs-dot"></span><span class="fs-name">手工补录</span></div>
|
||||
<div class="fs-state">已完成</div>
|
||||
<div class="fs-meta">7 月手工记录 5 笔已提交</div>
|
||||
<div class="fs-state">按需登记</div>
|
||||
<div class="fs-meta">手工记录需经管理端审核</div>
|
||||
</a>
|
||||
<a class="flow-step doing" data-view-link="reconcile" href="#reconcile">
|
||||
<div class="fs-top"><span class="fs-idx">03</span><span class="fs-dot"></span><span class="fs-name">往来确认</span></div>
|
||||
@@ -104,12 +103,12 @@
|
||||
<div class="flow-step wait">
|
||||
<div class="fs-top"><span class="fs-idx">04</span><span class="fs-dot"></span><span class="fs-name">管理复核</span></div>
|
||||
<div class="fs-state">等待集团</div>
|
||||
<div class="fs-meta">2 笔复核在途 · 无需本公司操作</div>
|
||||
<div class="fs-meta">由集团管理端处理审核事项</div>
|
||||
</div>
|
||||
<div class="flow-step wait">
|
||||
<div class="fs-top"><span class="fs-idx">05</span><span class="fs-dot"></span><span class="fs-name">账期结账</span></div>
|
||||
<div class="fs-state">08-29</div>
|
||||
<div class="fs-meta">需先完成上方前 3 步</div>
|
||||
<div class="fs-state">以集团通知为准</div>
|
||||
<div class="fs-meta">由管理端执行结账检查</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -148,23 +147,7 @@
|
||||
<thead>
|
||||
<tr><th>银行账户</th><th>流水覆盖区间</th><th>状态</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="cell-main">工商银行<span class="cell-sub">尾号 3305 · 基本户</span></td>
|
||||
<td class="meta">2026-01-01 ~ 2026-08-20</td>
|
||||
<td><span class="pill pill-success">已覆盖</span></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="cell-main">中国银行<span class="cell-sub">尾号 9916 · 一般户</span></td>
|
||||
<td class="meta">2026-01-01 ~ 2026-08-12</td>
|
||||
<td><span class="pill pill-warn">部分覆盖</span></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="cell-main">交通银行<span class="cell-sub">尾号 7710 · 一般户</span></td>
|
||||
<td class="meta">未上传</td>
|
||||
<td><span class="pill pill-info">待审核</span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tbody><tr><td colspan="3">请通过“管理账户”查看本公司的真实银行账户;流水断档以系统校验结果为准。</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
@@ -229,7 +212,7 @@
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>流水导入</h1>
|
||||
<p class="page-sub">上传银行导出的 Excel 流水文件,系统按表头识别银行模板、解析期间与明细并做覆盖校验。当前账期 2026-07,仅已审核通过的账户可导入。</p>
|
||||
<p class="page-sub">上传银行导出的 Excel 流水文件,系统按表头识别银行模板、解析期间与明细并做覆盖校验。仅当前所选公司已审核通过的账户可导入。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/* Shared portal navigation: same geometry in all four applications. */
|
||||
.jn-portal-bar { position: relative; min-height: 56px; box-sizing: border-box; padding-right: 160px !important; }
|
||||
a.jn-portal-return, a.jn-portal-return:link, a.jn-portal-return:visited {
|
||||
position: absolute; top: 10px; right: 16px; z-index: 2;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
|
||||
box-sizing: border-box; height: 36px; min-width: 124px; padding: 0 12px;
|
||||
border: 1px solid #e7c7c3; border-radius: 10px; margin: 0;
|
||||
background: #fff7f5; color: #a92e24; box-shadow: 0 1px 2px rgba(64,25,20,.04);
|
||||
font: 600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;
|
||||
text-decoration: none; white-space: nowrap; cursor: pointer;
|
||||
}
|
||||
a.jn-portal-return svg { width: 18px; height: 18px; flex: none; }
|
||||
a.jn-portal-return span { color: inherit !important; font: inherit; }
|
||||
a.jn-portal-return:hover { background: #faeae6; color: #92251d; border-color: #d99c94; text-decoration: none; }
|
||||
a.jn-portal-return:focus-visible { outline: 3px solid #b83a2d; outline-offset: 3px; }
|
||||
[data-theme="night"] a.jn-portal-return { background: #382927; border-color: #70504b; color: #ffb4a8; }
|
||||
[data-theme="night"] a.jn-portal-return:hover { background: #4a312c; color: #ffd0c7; }
|
||||
@media (max-width: 600px) {
|
||||
.jn-portal-bar { padding-right: 124px !important; }
|
||||
a.jn-portal-return, a.jn-portal-return:link, a.jn-portal-return:visited { right: 12px; min-width: 102px; gap: 6px; padding: 0 9px; }
|
||||
}
|
||||
@media print { a.jn-portal-return { display: none !important; } }
|
||||
+24
-1
@@ -43,7 +43,30 @@
|
||||
apply(next, true);
|
||||
}
|
||||
|
||||
apply(read(), false);
|
||||
var incoming = new URLSearchParams(location.search).get("theme");
|
||||
if (incoming === "day" || incoming === "night") {
|
||||
try { localStorage.setItem(KEY, incoming); } catch (e) {}
|
||||
}
|
||||
apply(incoming === "day" || incoming === "night" ? incoming : read(), false);
|
||||
document.addEventListener("click", function(event) {
|
||||
var link = event.target.closest("[data-return-portal]");
|
||||
if (link) { var url = new URL(link.href); url.searchParams.set("theme", read()); link.href = url.toString(); }
|
||||
});
|
||||
document.addEventListener("DOMContentLoaded", function() {
|
||||
if (!global.PORTAL_HOME) return;
|
||||
var checkbox = document.querySelector('[name="createUser"]');
|
||||
if (checkbox) { checkbox.checked = false; checkbox.disabled = true; checkbox.parentElement.classList.add("portal-native-account"); }
|
||||
var login = document.querySelector('[name="loginName"]');
|
||||
if (login) { login.required = false; login.closest(".field").classList.add("portal-native-account"); }
|
||||
var reset = document.querySelector('#btn-reset-pwd');
|
||||
if (reset) reset.classList.add("portal-native-account");
|
||||
var sub = document.querySelector('#companyDialog .modal-sub');
|
||||
if (sub) sub.textContent = "选择已获财务公司端权限的员工。保存后生效;移除员工会收回其对本公司的操作权限,历史记录保留。";
|
||||
var hint = document.querySelector('#companyForm .hint');
|
||||
if (hint) hint.textContent = "可选择多名出纳,也可暂不分配。员工可操作的公司由这里的分配决定。";
|
||||
var submit = document.querySelector('#companyForm button[type="submit"]');
|
||||
if (submit) submit.textContent = "保存公司与分配";
|
||||
});
|
||||
document.addEventListener("click", function (event) {
|
||||
var btn = event.target.closest("[data-theme-set]");
|
||||
if (!btn) return;
|
||||
|
||||
Reference in New Issue
Block a user