Files
zyt/server/app/adminapi/logic/tcm/PrescriptionLibraryLogic.php
T
2026-05-11 17:49:38 +08:00

141 lines
4.0 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace app\adminapi\logic\tcm;
use app\common\logic\BaseLogic;
use app\common\model\auth\AdminRole;
use app\common\model\tcm\PrescriptionLibrary;
use think\facade\Config;
/**
* 处方库逻辑层
*/
class PrescriptionLibraryLogic extends BaseLogic
{
/**
* @notes 是否可管理全部处方(超级管理员 或 配置中的管理员角色)
*/
public static function canManageAllPrescriptions(int $adminId, array $adminInfo): bool
{
if (!empty($adminInfo['root']) && (int) $adminInfo['root'] === 1) {
return true;
}
$allowRoles = Config::get('project.prescription_library_manage_all_roles', []);
if ($allowRoles === [] || $allowRoles === null) {
$allowRoles = Config::get('project.order_edit_all_roles', [0, 3]);
}
$myRoles = AdminRole::where('admin_id', $adminId)->column('role_id');
return count(array_intersect($myRoles, $allowRoles)) > 0;
}
/**
* @notes 添加处方库
*/
public static function add(array $params): ?int
{
try {
// 处理药材数据
if (isset($params['herbs']) && is_array($params['herbs'])) {
$params['herbs'] = json_encode($params['herbs'], JSON_UNESCAPED_UNICODE);
}
$model = PrescriptionLibrary::create($params);
return (int) $model->id;
} catch (\Exception $e) {
self::setError($e->getMessage());
return null;
}
}
/**
* @notes 编辑处方库
*/
public static function edit(array $params, int $adminId, bool $canManageAll = false): bool
{
try {
$model = PrescriptionLibrary::findOrEmpty($params['id']);
if ($model->isEmpty()) {
self::setError('处方不存在');
return false;
}
if (!$canManageAll && (int) $model->creator_id !== $adminId) {
self::setError('无权限编辑此处方');
return false;
}
// 处理药材数据
if (isset($params['herbs']) && is_array($params['herbs'])) {
$params['herbs'] = json_encode($params['herbs'], JSON_UNESCAPED_UNICODE);
}
$model->save($params);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 删除处方库
*/
public static function delete(int $id, int $adminId, bool $canManageAll = false): bool
{
try {
$model = PrescriptionLibrary::findOrEmpty($id);
if ($model->isEmpty()) {
self::setError('处方不存在');
return false;
}
if (!$canManageAll && (int) $model->creator_id !== $adminId) {
self::setError('无权限删除此处方');
return false;
}
$model->delete();
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 处方库详情
*/
public static function detail(int $id, int $adminId, bool $canManageAll = false): ?array
{
try {
$model = PrescriptionLibrary::findOrEmpty($id);
if ($model->isEmpty()) {
return null;
}
if (!$canManageAll && (int) $model->creator_id !== $adminId && (int) $model->is_public !== 1) {
return null;
}
$data = $model->toArray();
// 解析药材JSON
if (!empty($data['herbs'])) {
$data['herbs'] = json_decode($data['herbs'], true);
} else {
$data['herbs'] = [];
}
return $data;
} catch (\Exception $e) {
self::setError($e->getMessage());
return null;
}
}
}