封装清洗过程
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
"""公司业务服务:查找或创建公司基础记录,上传 Logo。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import insert, text
|
||||
|
||||
from app.core.database import MysqlSession
|
||||
from app.core.id_gen import next_id
|
||||
from app.core.logger import log
|
||||
from app.core.oss import upload_image_url
|
||||
from app.models.company import Company
|
||||
|
||||
# 公司创建锁(防止并发重复插入同一公司)
|
||||
_company_lock = threading.Lock()
|
||||
|
||||
|
||||
def find_or_create_company(company_name: str, logo_url: str | None = None) -> int:
|
||||
"""查找或创建公司,上传 Logo 并回填地址。
|
||||
|
||||
Args:
|
||||
company_name: 公司名称(用于查重和创建)。
|
||||
logo_url: Logo 图片原始地址,非空时下载并上传 OSS。
|
||||
|
||||
Returns:
|
||||
公司 ID。
|
||||
"""
|
||||
if not company_name:
|
||||
company_name = "未知公司"
|
||||
|
||||
with _company_lock:
|
||||
with MysqlSession() as session:
|
||||
row = session.execute(
|
||||
text("SELECT id FROM bg_company WHERE short_name = :name LIMIT 1"),
|
||||
{"name": company_name},
|
||||
)
|
||||
existing = row.scalar()
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
company_id = next_id()
|
||||
now = datetime.now()
|
||||
session.execute(
|
||||
insert(Company).values(
|
||||
id=company_id,
|
||||
name=company_name,
|
||||
short_name=company_name,
|
||||
status=0,
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
log.info("公司创建成功 [id={}]: {}", company_id, company_name)
|
||||
|
||||
# 锁外处理 Logo 上传
|
||||
if logo_url:
|
||||
try:
|
||||
oss_url = upload_image_url(logo_url)
|
||||
if oss_url:
|
||||
with MysqlSession() as session:
|
||||
session.execute(
|
||||
text("UPDATE bg_company SET logo_url = :url, update_time = :t WHERE id = :id"),
|
||||
{"url": oss_url, "t": datetime.now(), "id": company_id},
|
||||
)
|
||||
session.commit()
|
||||
log.info("公司 Logo 上传成功 [id={}]: {}", company_id, oss_url)
|
||||
except Exception as exc:
|
||||
log.warning("公司 Logo 上传失败 [id={}]: {}", company_id, exc)
|
||||
|
||||
return company_id
|
||||
Reference in New Issue
Block a user