智慧教务系统
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

114 lines
3.4 KiB

<?php
namespace app\service\admin\contract;
use app\model\contract\Contract;
use app\model\contract\ContractSign;
use core\base\BaseAdminService;
/**
* 合同分发服务类
*/
class ContractDistributionServiceBasic extends BaseAdminService
{
/**
* 手动分发合同
* @param int $contractId 合同ID
* @param array $personnelIds 人员ID数组
* @param int $type 人员类型:1内部员工,2外部会员
* @return bool
* @throws \Exception
*/
public function manualDistribute(int $contractId, array $personnelIds, int $type = 1): bool
{
// 1. 验证合同是否存在
$contract = (new Contract())->find($contractId);
if (!$contract) {
throw new \Exception('合同不存在');
}
// 2. 验证人员ID数组
if (empty($personnelIds) || !is_array($personnelIds)) {
throw new \Exception('人员列表不能为空');
}
// 3. 验证人员类型
if (!in_array($type, [1, 2])) {
throw new \Exception('人员类型错误');
}
// 4. 验证人员是否存在
$this->validatePersonnel($personnelIds, $type);
// 5. 开启事务
\think\facade\Db::startTrans();
try {
$successCount = 0;
foreach ($personnelIds as $personnelId) {
// 检查是否已经分发过
$exists = (new ContractSign())->where([
['contract_id', '=', $contractId],
['personnel_id', '=', $personnelId],
['type', '=', $type]
])->findOrEmpty();
if (!$exists->isEmpty()) {
continue; // 跳过已分发的
}
$data = [
'contract_id' => $contractId,
'personnel_id' => $personnelId,
'type' => $type,
'status' => 'pending',
'source_type' => 'manual',
'source_id' => null,
'created_at' => time()
];
$result = (new ContractSign())->create($data);
if ($result) {
$successCount++;
}
}
// 6. 提交事务
\think\facade\Db::commit();
if ($successCount === 0) {
throw new \Exception('所有人员都已分发过该合同');
}
return true;
} catch (\Exception $e) {
// 7. 回滚事务
\think\facade\Db::rollback();
throw $e;
}
}
/**
* 验证人员是否存在
* @param array $personnelIds 人员ID数组
* @param int $type 人员类型
* @throws \Exception
*/
private function validatePersonnel(array $personnelIds, int $type): void
{
if ($type === 1) {
// 内部员工
$count = \app\model\personnel\Personnel::whereIn('id', $personnelIds)
->where('status', 1)
->count();
} else {
// 外部会员
$count = \app\model\member\Member::whereIn('id', $personnelIds)
->where('status', 1)
->count();
}
if ($count !== count($personnelIds)) {
throw new \Exception('部分人员不存在或状态异常');
}
}
}