智慧教务系统
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.
 
 
 
 
 
 

740 lines
26 KiB

<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址:https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------
namespace app\service\api\apiService;
use app\model\campus\Campus;
use app\model\campus_person_role\CampusPersonRole;
use app\model\chat_friends\ChatFriends;
use app\model\chat_messages\ChatMessages;
use app\model\dict\Dict;
use app\model\order_table\OrderTable;
use app\model\student\Student;
use core\base\BaseApiService;
use think\facade\Db;
/**
* 订单管理-控制器服务层
* Class MemberService
* @package app\service\api\member
*/
class OrderTableService extends BaseApiService
{
public function __construct()
{
parent::__construct();
}
//查询列表
public function getList(array $where)
{
$page_params = $this->getPageParam();//获取请求参数中的页码+分页数
$page = $page_params['page'];
$limit = $page_params['limit'];
$model = new OrderTable();
//员工表id
if (!empty($where['staff_id'])) {
$model = $model->where('staff_id', $where['staff_id']);
}
//客户资源表id
if (!empty($where['resource_id'])) {
$model = $model->where('resource_id', $where['resource_id']);
}
//学生表id
if (!empty($where['student_id'])) {
$model = $model->where('student_id', $where['student_id']);
}
$data = $model
->append([
'customerResources',
'course',
'classGrade',
'personnel',
'studentCourses' // 添加学员课程关联
])
->order('created_at','desc') // 使用created_at排序
->paginate([
'list_rows' => $limit,
'page' => $page,
])->toArray();
return $data;
}
//查询详情
public function getInfo(array $where)
{
$model = new OrderTable();
//判断用没有员工id
if (!empty($where['staff_id'])) {
$model = $model->where('staff_id', $where['staff_id']);
}
//判断用没有客户资源id
if (!empty($where['resource_id'])) {
$model = $model->where('resource_id', $where['resource_id']);
}
$data = $model
->append([
'customerResources',
'course',
'classGrade',
'personnel'
])
->find();
if ($data) {
$data = $data->toArray();
$res = [
'code' => 1,
'msg' => '操作成功',
'data' => $data
];
return $res;
} else {
$res = [
'code' => 0,
'msg' => '暂无数据',
'data' => []
];
return $res;
}
}
//创建订单
public function addData(array $data)
{
try {
// 如果选择了赠品,验证赠品是否可用
if (!empty($data['gift_id'])) {
$giftValidation = $this->validateGift($data['gift_id'], $data['resource_id']);
if (!$giftValidation['valid']) {
return [
'code' => 0,
'msg' => $giftValidation['message'],
'data' => []
];
}
}
$success = OrderTable::create($data);
// 如果订单创建成功且使用了赠品,更新赠品状态
if ($success && !empty($data['gift_id'])) {
$this->updateGiftStatus($data['gift_id'], $success->id);
}
$res = [
'code' => 1,
'msg' => '操作成功',
'data' => ['order_id' => $success->id ?? null]
];
if (!$success) {
$res = [
'code' => 0,
'msg' => '操作失败',
'data' => []
];
}
return $res;
} catch (\Exception $e) {
return [
'code' => 0,
'msg' => '创建订单异常: ' . $e->getMessage(),
'data' => []
];
}
}
//更新订单支付状态
public function updatePaymentStatus(array $data)
{
try {
$order = OrderTable::where('id', $data['order_id'])->find();
if (!$order) {
return [
'code' => 0,
'msg' => '订单不存在',
'data' => []
];
}
// 准备更新数据
$updateData = [
'order_status' => $data['order_status'],
'updated_at' => date('Y-m-d H:i:s')
];
// 如果提供了支付单号,则更新
if (!empty($data['payment_id'])) {
$updateData['payment_id'] = $data['payment_id'];
}
// 如果订单状态为已支付,记录支付时间
if ($data['order_status'] === 'paid') {
$updateData['payment_time'] = date('Y-m-d H:i:s');
}
$success = $order->save($updateData);
if ($success) {
// 如果订单状态变更为已支付,则执行完整的支付后处理流程
if ($data['order_status'] === 'paid') {
$orderArray = $order->toArray();
$this->handlePaymentSuccess($orderArray);
}
return [
'code' => 1,
'msg' => '订单状态更新成功',
'data' => $order->toArray()
];
} else {
return [
'code' => 0,
'msg' => '订单状态更新失败',
'data' => []
];
}
} catch (\Exception $e) {
return [
'code' => 0,
'msg' => '更新订单状态异常: ' . $e->getMessage(),
'data' => []
];
}
}
/**
* 处理支付成功后的业务
*/
public function handlePaymentSuccess(array $orderArray)
{
// 1. 为学员分配课程
$this->assignCourseToStudent($orderArray);
// 2. 创建合同签署记录
$this->createContractSign($orderArray);
// 3. 创建支付记录
$this->createPaymentRecord($orderArray);
// 4.处理赠品
$this->handleGift($orderArray);
}
/**
* 支付成功后为学员分配课程
* @param array $orderData 订单数据
* @return bool
*/
private function assignCourseToStudent(array $orderData)
{
try {
$student_id = $orderData['student_id'];
$course_id = $orderData['course_id'];
$resource_id = $orderData['resource_id'];
if (empty($student_id) || empty($course_id)) {
\think\facade\Log::warning('学员分配课程失败:缺少学员ID或课程ID', $orderData);
return false;
}
// 获取课程信息
$course = \app\model\course\Course::where('id', $course_id)->find();
if (!$course) {
\think\facade\Log::warning('学员分配课程失败:课程不存在', ['course_id' => $course_id]);
return false;
}
$course = $course->toArray();
Student::where('id', $student_id)->update(['status' => 1]);
// 检查学员是否已有该课程记录
$existingCourse = Db::table('school_student_courses')
->where('student_id', $student_id)
->where('course_id', $course_id)
->find();
$now = date('Y-m-d H:i:s');
$start_date = date('Y-m-d');
$end_date = date('Y-m-d', strtotime('+' . $course['duration'] . ' days'));
if ($existingCourse) {
// 如果已有课程记录,累加课时数量
$updateData = [
'total_hours' => $existingCourse['total_hours'] + $course['session_count'],
'gift_hours' => $existingCourse['gift_hours'] + $course['gift_session_count'],
'updated_at' => $now
];
// 如果原有课程已过期,更新有效期
if ($existingCourse['end_date'] < $start_date) {
$updateData['start_date'] = $start_date;
$updateData['end_date'] = $end_date;
} else {
// 延长有效期
$updateData['end_date'] = date('Y-m-d',
strtotime($existingCourse['end_date'] . ' +' . $course['duration'] . ' days')
);
}
$result = Db::table('school_student_courses')
->where('id', $existingCourse['id'])
->update($updateData);
\think\facade\Log::info('学员课程更新成功', [
'student_id' => $student_id,
'course_id' => $course_id,
'added_hours' => $course['session_count'],
'added_gift_hours' => $course['gift_session_count']
]);
} else {
// 创建新的课程记录
$insertData = [
'student_id' => $student_id,
'course_id' => $course_id,
'total_hours' => $course['session_count'],
'gift_hours' => $course['gift_session_count'],
'start_date' => $start_date,
'end_date' => $end_date,
'use_total_hours' => 0,
'use_gift_hours' => 0,
'single_session_count' => $course['single_session_count'],
'status' => 1, // 激活状态
'resource_id' => $resource_id,
'created_at' => $now,
'updated_at' => $now
];
$result = Db::table('school_student_courses')->insert($insertData);
\think\facade\Log::info('学员课程创建成功', [
'student_id' => $student_id,
'course_id' => $course_id,
'total_hours' => $course['session_count'],
'gift_hours' => $course['gift_session_count'],
'start_date' => $start_date,
'end_date' => $end_date
]);
}
return $result ? true : false;
} catch (\Exception $e) {
\think\facade\Log::error('学员分配课程异常', [
'order_data' => $orderData,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return false;
}
}
/**
* 支付成功后创建合同签署记录
* @param array $orderData 订单数据
* @return bool
*/
private function createContractSign(array $orderData)
{
try {
$student_id = $orderData['student_id'];
$course_id = $orderData['course_id'];
if (empty($student_id) || empty($course_id)) {
\think\facade\Log::warning('创建合同签署记录失败:缺少学员ID或课程ID', $orderData);
return false;
}
// 获取课程的合同模板ID
$course = \app\model\course\Course::where('id', $course_id)->find();
if (!$course || empty($course['contract_id'])) {
\think\facade\Log::warning('创建合同签署记录失败:课程无合同模板', ['course_id' => $course_id]);
return false;
}
// 获取学员的user_id
$student = \app\model\student\Student::where('id', $student_id)->find();
if (!$student || empty($student['user_id'])) {
\think\facade\Log::warning('创建合同签署记录失败:学员无user_id', ['student_id' => $student_id]);
return false;
}
$now = date('Y-m-d H:i:s');
$insertData = [
'contract_id' => $course['contract_id'],
'personnel_id' => $student['user_id'], // 用户合同场景下存储学员的user_id
'student_id' => $student_id,
'status' => 1, // 默认状态
'source_type' => 'auto_course', // 来源类型:自动课程购买
'source_id' => $orderData['id'], // 订单ID
'type' => 2, // 标识为用户购买课程合同
'created_at' => $now,
'updated_at' => $now,
'deleted_at' => 0
];
$result = Db::table('school_contract_sign')->insert($insertData);
if ($result) {
// 创建签署记录成功后,为甲乙双方生成数据源配置记录
$this->createDocumentDataSourceConfig($course['contract_id'], $orderData);
\think\facade\Log::info('合同签署记录创建成功', [
'student_id' => $student_id,
'contract_id' => $course['contract_id'],
'order_id' => $orderData['id']
]);
}
return $result ? true : false;
} catch (\Exception $e) {
\think\facade\Log::error('创建合同签署记录异常', [
'order_data' => $orderData,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return false;
}
}
/**
* 为甲乙双方创建文档数据源配置记录
* @param int $contract_id 合同ID
* @param array $orderData 订单数据
* @return bool
*/
private function createDocumentDataSourceConfig($contract_id, $orderData)
{
try {
// 获取合同模板的占位符配置
$contract = Db::table('school_contract')->where('id', $contract_id)->find();
if (!$contract || empty($contract['placeholder_config'])) {
\think\facade\Log::warning('合同模板无占位符配置', ['contract_id' => $contract_id]);
return false;
}
$placeholder_config = json_decode($contract['placeholder_config'], true);
if (!is_array($placeholder_config)) {
\think\facade\Log::warning('占位符配置格式错误', ['contract_id' => $contract_id]);
return false;
}
$insert_data = [];
$now = date('Y-m-d H:i:s');
// 为每个占位符配置创建数据源记录
foreach ($placeholder_config as $config) {
$data_source_record = [
'contract_id' => $contract_id,
'placeholder' => $config['placeholder'] ?? '',
'data_type' => $config['data_type'] ?? 'user_input',
'system_function' => $config['system_function'] ?? '',
'table_name' => $config['table_name'] ?? '',
'field_name' => $config['field_name'] ?? '',
'field_type' => $config['field_type'] ?? 'text',
'is_required' => $config['is_required'] ?? 0,
'default_value' => $config['default_value'] ?? '',
'sign_party' => $config['sign_party'] ?? '',
'validation_rule' => $config['validation_rule'] ?? '',
'created_at' => $now,
'updated_at' => $now
];
$insert_data[] = $data_source_record;
}
if (!empty($insert_data)) {
$result = Db::table('school_document_data_source_config')->insertAll($insert_data);
if ($result) {
\think\facade\Log::info('文档数据源配置创建成功', [
'contract_id' => $contract_id,
'order_id' => $orderData['id'],
'records_count' => count($insert_data)
]);
}
return $result ? true : false;
}
return true;
} catch (\Exception $e) {
\think\facade\Log::error('创建文档数据源配置异常', [
'contract_id' => $contract_id,
'order_data' => $orderData,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return false;
}
}
/**
* 支付成功后创建支付记录
* @param array $orderData 订单数据
* @return bool
*/
private function createPaymentRecord(array $orderData)
{
try {
$order_id = $orderData['id'];
$payment_id = $orderData['payment_id'] ?? '';
$payment_type = $orderData['payment_type'] ?? '';
$order_amount = $orderData['order_amount'] ?? 0;
if (empty($order_id) || empty($payment_id)) {
\think\facade\Log::warning('创建支付记录失败:缺少订单ID或支付单号', $orderData);
return false;
}
// 获取课程名称用于支付描述
$course_name = '未知课程';
if (!empty($orderData['course_id'])) {
$course = \app\model\course\Course::where('id', $orderData['course_id'])->find();
if ($course) {
$course_name = $course['course_name'];
}
}
$status = Db::table('school_pay')->where('out_trade_no', $payment_id)->find();
if ($status){
\think\facade\Log::warning('创建支付记录失败:支付单号已存在', ['order_id' => $order_id, 'payment_id' => $payment_id]);
return false;
}
$now = time();
$insertData = [
'main_id' => $order_id, // 订单ID
'from_main_id' => 0,
'out_trade_no' => $payment_id, // 支付单号
'trade_type' => 'order_payment', // 交易类型
'trade_id' => $order_id,
'trade_no' => $payment_id,
'body' => '课程购买-' . $course_name, // 支付描述
'money' => $order_amount, // 支付金额
'voucher' => '',
'status' => 1, // 支付状态:已支付
'json' => '',
'create_time' => $now, // 创建时间
'pay_time' => $now, // 支付时间
'cancel_time' => 0,
'type' => $payment_type, // 支付方式:cash, scan_code等
'mch_id' => '',
'main_type' => 'order', // 主类型
'channel' => '',
'fail_reason' => ''
];
$result = Db::table('school_pay')->insert($insertData);
if ($result) {
\think\facade\Log::info('支付记录创建成功', [
'order_id' => $order_id,
'payment_id' => $payment_id,
'amount' => $order_amount,
'type' => $payment_type
]);
}
return $result ? true : false;
} catch (\Exception $e) {
\think\facade\Log::error('创建支付记录异常', [
'order_data' => $orderData,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return false;
}
}
/**
* 处理赠品
*/
private function handleGift(array $orderData)
{
try {
// 如果订单没有使用赠品,跳过处理
if (empty($orderData['gift_id']) || empty($orderData['gift_type'])) {
return true;
}
$gift_id = $orderData['gift_id'];
$gift_type = $orderData['gift_type'];
$order_amount = $orderData['order_amount'];
// 验证赠品是否存在且可用
$gift = Db::table('shcool_resources_gift')
->where('id', $gift_id)
->where('gift_status', 1)
->where('order_id', $orderData['id']) // 必须是被当前订单绑定的赠品
->find();
if (!$gift) {
\think\facade\Log::warning('处理赠品失败:赠品不存在或不可用', [
'gift_id' => $gift_id,
'order_id' => $orderData['id']
]);
return false;
}
// 根据赠品类型进行处理
switch ($gift_type) {
case '1': // 减现
$this->handleGiftCash($orderData, $gift);
break;
case '2': // 赠课
$this->handleGiftCourse($orderData, $gift);
break;
default:
\think\facade\Log::warning('处理赠品失败:未知的赠品类型', [
'gift_type' => $gift_type,
'order_id' => $orderData['id']
]);
return false;
}
// 更新赠品状态为已使用
Db::table('shcool_resources_gift')
->where('id', $gift_id)
->update([
'gift_status' => 2, // 已使用
'use_time' => time(),
'update_time' => time()
]);
\think\facade\Log::info('赠品处理成功', [
'gift_id' => $gift_id,
'gift_type' => $gift_type,
'order_id' => $orderData['id']
]);
return true;
} catch (\Exception $e) {
\think\facade\Log::error('处理赠品异常', [
'order_data' => $orderData,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return false;
}
}
/**
* 验证赠品是否可用
*/
private function validateGift($gift_id, $resource_id)
{
try {
$gift = Db::table('shcool_resources_gift')
->where('id', $gift_id)
->where('resource_id', $resource_id)
->where('gift_status', 1)
->where('order_id', 0) // 必须是未使用的赠品
->find();
if (!$gift) {
return [
'valid' => false,
'message' => '赠品不存在或已被使用'
];
}
return [
'valid' => true,
'message' => '赠品验证通过'
];
} catch (\Exception $e) {
\think\facade\Log::error('验证赠品异常', [
'gift_id' => $gift_id,
'resource_id' => $resource_id,
'error' => $e->getMessage()
]);
return [
'valid' => false,
'message' => '赠品验证异常: ' . $e->getMessage()
];
}
}
/**
* 更新赠品状态,绑定到订单
*/
private function updateGiftStatus($gift_id, $order_id)
{
try {
$result = Db::table('shcool_resources_gift')
->where('id', $gift_id)
->where('gift_status', 1)
->where('order_id', 0)
->update([
'order_id' => $order_id,
'update_time' => time()
]);
if ($result) {
\think\facade\Log::info('赠品状态更新成功', [
'gift_id' => $gift_id,
'order_id' => $order_id
]);
} else {
\think\facade\Log::warning('赠品状态更新失败', [
'gift_id' => $gift_id,
'order_id' => $order_id
]);
}
return $result;
} catch (\Exception $e) {
\think\facade\Log::error('更新赠品状态异常', [
'gift_id' => $gift_id,
'order_id' => $order_id,
'error' => $e->getMessage()
]);
return false;
}
}
/**
* 处理减现赠品
*/
private function handleGiftCash($orderData, $gift)
{
// 减现赠品的具体逻辑可以根据业务需求实现
// 例如:修改订单金额、创建退款记录等
\think\facade\Log::info('处理减现赠品', [
'order_id' => $orderData['id'],
'gift_id' => $gift['id'],
'gift_name' => $gift['gift_name']
]);
// TODO: 具体的减现逻辑实现
return true;
}
/**
* 处理赠课赠品
*/
private function handleGiftCourse($orderData, $gift)
{
// 赠课赠品的具体逻辑可以根据业务需求实现
// 例如:增加学员课时、创建额外课程记录等
\think\facade\Log::info('处理赠课赠品', [
'order_id' => $orderData['id'],
'gift_id' => $gift['id'],
'gift_name' => $gift['gift_name']
]);
// TODO: 具体的赠课逻辑实现
return true;
}
}