request->action()); if ($action == 'save_quotation_link' || $action == 'test_save_quotation_link' || $action == 'test_amodela') { // 只执行必要的初始化,跳过可能导致错误的操作 return; } } catch (\Exception $e) { // 如果获取 action 失败,继续执行 } parent::_initialize(); $this->model = new \addons\antis\model\Business; $this->view->assign("typeList", $this->model->getTypeList()); } /** * 查看 */ public function index() { //设置过滤方法 $this->request->filter(['strip_tags', 'trim']); if ($this->request->isAjax()) { if ($this->request->request('keyField')) { //halt(111); return $this->selectpage(); } $filter = $this->request->get("filter", ''); $op=$this->request->get("op", '', 'trim'); $filter = (array)json_decode($filter, true); $op = (array)json_decode($op, true); $customer_name = null; if(isset($filter['customer.name'])){ $customer_name = $filter['customer.name']; unset($filter['customer.name']); unset($op['customer.name']); \think\Request::instance()->get(['filter'=>json_encode($filter)]); \think\Request::instance()->get(['op'=>json_encode($op)]); } // halt($customer_name); //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的 $type = input('type', 0); list($where, $sort, $order, $offset, $limit) = $this->buildparams(); // halt($type); switch ($type) { case 1: $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; case 2: $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId()); break; case 3: $start = date('Y-m-d 00:00:00'); $end = date('Y-m-d 23:59:59'); $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray(); $relationId = []; foreach ($record as $k => $v) { $whereRe['id'] = array('gt', $v['id']); $whereRe['relation_id'] = $v['relation_id']; $recordData = Record::where($whereRe)->count(); if ($recordData == 0) { $relationId[] = $v['relation_id']; } } $wheres['id'] = array('in', $relationId); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; case 4: $start = date('Y-m-d 00:00:00'); $end = date('Y-m-d 23:59:59'); $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray(); $relationId = []; foreach ($record as $k => $v) { $whereRe['id'] = array('gt', $v['id']); $whereRe['relation_id'] = $v['relation_id']; $recordData = Record::where($whereRe)->count(); if ($recordData >= 1) { $relationId[] = $v['relation_id']; } } $wheres['id'] = array('in', $relationId); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; case 5: $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray(); $wheres['id'] = array('not in', $record); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; default: $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds()); break; } $ids = []; $group_id = input('group_id'); $staff_id = input('staff_id'); if ($group_id) {//角色组 $ids = Staff::getGroupStaffIds($group_id); } if ($staff_id) { $ids = $staff_id; } if ($group_id || $staff_id) { $wheres['owner_staff_id'] = ['in', $ids]; } // halt($where); $list = $this->model->where($where) ->where($wheres) ->with([ 'customer'=>function($query)use($customer_name){ if(!empty($customer_name)){ // halt($customer_name); } }, 'ownerStaff', 'product' ])->order($sort, $order)->paginate($limit); foreach($list as $k=>$v){ $types = BusinessStatus::where(array('business_id'=>$v['id']))->order('id desc')->value('type'); $list[$k]['type'] = $types ? (int)$types : 0; } //halt($list->items()); $result = array("total" => $list->total(), "rows" => $list->items()); return json($result); } $field = FormField::getFields(FormField::BUSINESS_TYPE); $this->assignconfig('fields', $field); return $this->view->fetch(); } public function index2(){ $this->request->filter(['strip_tags', 'trim']); if ($this->request->isAjax()) { if ($this->request->request('keyField')) { return $this->selectpage2(2); } } } public function get_business_bill(){ $param = $this->request->param(); list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $AmodelaModel = new Amodela(); // 查询该项目的所有报价单(包括用友集成和PHP项目的) // 简单查询:只要 business_id 匹配即可 $business_id = $param['business_id']; // 调试:记录查询参数 \think\Log::write('get_business_bill 查询参数: business_id=' . $business_id, 'info'); // 查询所有记录(包括 bill_id 为 0 的用友集成报价单) $list = $AmodelaModel->where('business_id', $business_id)->order('id desc')->paginate($limit); // 调试:记录查询结果 \think\Log::write('get_business_bill 查询结果数量: ' . $list->total(), 'info'); if ($list->total() > 0) { foreach ($list->items() as $item) { \think\Log::write('get_business_bill 记录详情: id=' . $item['id'] . ', name=' . ($item['name'] ?? '') . ', bill_id=' . ($item['bill_id'] ?? 'null'), 'info'); } } else { // 如果没有查询到结果,尝试查询所有 business_id 的记录(用于调试) $allRecords = $AmodelaModel->where('business_id', $business_id)->select(); \think\Log::write('get_business_bill 未查询到分页结果,但直接查询找到 ' . count($allRecords) . ' 条记录', 'warning'); } // items() 可能是 Model 对象,不能直接传入声明为 array 的 enrich(PHP8+ 会 TypeError 500) $rows = []; foreach ($list->items() as $row) { $item = is_array($row) ? $row : (is_object($row) && method_exists($row, 'toArray') ? $row->toArray() : (array)$row); self::enrichQuotationListRow($item, $AmodelaModel); $rows[] = $item; } $result = ['total' => $list->total(), 'rows' => $rows]; return json($result); } /** * 测试接口 - 用于排查问题 * @return \think\response\Json */ public function test_save_quotation_link() { header('Content-Type: application/json; charset=utf-8'); try { return json(['code' => 1, 'msg' => '测试接口正常', 'data' => ['time' => date('Y-m-d H:i:s')]]); } catch (\Exception $e) { return json(['code' => 0, 'msg' => '测试接口异常:' . $e->getMessage()]); } } /** * 测试接口2 - 测试 Amodela 模型 * @return \think\response\Json */ public function test_amodela() { header('Content-Type: application/json; charset=utf-8'); try { $amodelaModel = new Amodela(); $count = $amodelaModel->count(); return json(['code' => 1, 'msg' => 'Amodela模型正常', 'data' => ['count' => $count]]); } catch (\Exception $e) { return json(['code' => 0, 'msg' => 'Amodela模型异常:' . $e->getMessage()]); } } /** * 保存报价单关联(用于关联用友集成的报价单) * @return \think\response\Json */ public function save_quotation_link() { // 立即设置响应头为 JSON,避免 ThinkPHP 输出 HTML 错误页面 header('Content-Type: application/json; charset=utf-8'); // 处理 CORS 跨域请求 if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); } // 处理 OPTIONS 预检请求 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit; } // 使用 ob_start 捕获所有输出,确保只返回 JSON ob_start(); try { \think\Log::write('save_quotation_link 开始执行', 'info'); // 获取参数 - 使用 $_POST 或 $_REQUEST 直接获取,避免依赖 $this->request $business_id = isset($_POST['business_id']) ? $_POST['business_id'] : (isset($_REQUEST['business_id']) ? $_REQUEST['business_id'] : ''); $quotation_id = isset($_POST['quotation_id']) ? $_POST['quotation_id'] : (isset($_REQUEST['quotation_id']) ? $_REQUEST['quotation_id'] : ''); $quotation_number = isset($_POST['quotation_number']) ? $_POST['quotation_number'] : (isset($_REQUEST['quotation_number']) ? $_REQUEST['quotation_number'] : ''); $quotation_name = isset($_POST['quotation_name']) ? $_POST['quotation_name'] : (isset($_REQUEST['quotation_name']) ? $_REQUEST['quotation_name'] : ''); $total_amount = isset($_POST['total_amount']) ? floatval($_POST['total_amount']) : (isset($_REQUEST['total_amount']) ? floatval($_REQUEST['total_amount']) : 0); $lrl = isset($_POST['lrl']) ? floatval($_POST['lrl']) : (isset($_REQUEST['lrl']) ? floatval($_REQUEST['lrl']) : 0); $initiator_staff_id = isset($_POST['initiator_staff_id']) ? intval($_POST['initiator_staff_id']) : (isset($_REQUEST['initiator_staff_id']) ? intval($_REQUEST['initiator_staff_id']) : 0); // JSON 请求体:补全/覆盖参数(与用友前端 axios JSON 一致) $rawInput = file_get_contents('php://input'); if (!empty($rawInput)) { $jsonInput = json_decode($rawInput, true); if ($jsonInput && is_array($jsonInput)) { if (isset($jsonInput['business_id']) && $jsonInput['business_id'] !== '') { $business_id = trim($jsonInput['business_id']); } if (isset($jsonInput['quotation_id']) && $jsonInput['quotation_id'] !== '') { $quotation_id = trim($jsonInput['quotation_id']); } if (isset($jsonInput['quotation_number'])) { $quotation_number = trim($jsonInput['quotation_number']); } if (isset($jsonInput['quotation_name'])) { $quotation_name = trim($jsonInput['quotation_name']); } if (isset($jsonInput['total_amount'])) { $total_amount = floatval($jsonInput['total_amount']); } if (isset($jsonInput['lrl'])) { $lrl = floatval($jsonInput['lrl']); } if (isset($jsonInput['initiator_staff_id'])) { $initiator_staff_id = intval($jsonInput['initiator_staff_id']); } } } // 类型转换 $business_id = intval($business_id); $quotation_id = intval($quotation_id); \think\Log::write('save_quotation_link 收到请求: business_id=' . $business_id . ', quotation_id=' . $quotation_id, 'info'); if (empty($business_id) || empty($quotation_id)) { \think\Log::write('save_quotation_link 参数不完整', 'warning'); ob_clean(); echo json_encode(['code' => 0, 'msg' => '参数不完整:business_id 和 quotation_id 必填', 'data' => null], JSON_UNESCAPED_UNICODE); exit; } \think\Log::write('save_quotation_link 开始查询项目', 'info'); // 直接创建 Business 模型实例,避免依赖 _initialize() 中的初始化 $businessModel = new \addons\antis\model\Business(); // 检查项目是否存在 $business = $businessModel->where('id', $business_id)->find(); if (!$business) { \think\Log::write('save_quotation_link 项目不存在: business_id=' . $business_id, 'warning'); ob_clean(); echo json_encode(['code' => 0, 'msg' => '项目不存在', 'data' => null], JSON_UNESCAPED_UNICODE); exit; } \think\Log::write('save_quotation_link 项目查询成功', 'info'); // 获取客户信息 $customer_id = null; $customer_name = ''; try { // $business 可能是对象或数组,需要兼容处理 if (is_object($business)) { $customer_id = isset($business->customer_id) ? $business->customer_id : null; } else { $customer_id = isset($business['customer_id']) ? $business['customer_id'] : null; } if ($customer_id) { $customerModel = new \addons\antis\model\Customer(); $customer = $customerModel->where('id', $customer_id)->find(); $customer_name = $customer ? (is_object($customer) ? ($customer->name ?? '') : ($customer['name'] ?? '')) : ''; } } catch (\Exception $e) { \think\Log::write('save_quotation_link 获取客户信息失败: ' . $e->getMessage(), 'warning'); // 客户信息获取失败不影响主流程 } \think\Log::write('save_quotation_link 开始创建 Amodela 记录', 'info'); // 在 Amodela 表中创建关联记录 // 由于 Amodela 表可能没有 quotation_id 字段,我们在 name 字段中包含 quotation_id 信息 // name 格式:{客户名称}_{项目名称}_{yyyyMMdd}(quotation_{quotation_id}) $amodelaModel = new Amodela(); // 检查是否已存在关联记录(通过 business_id 和 name 中的 quotation_id) $existing = $amodelaModel->where('business_id', $business_id) ->where('name', 'like', '%(quotation_' . $quotation_id . ')%') ->find(); // 确保 name 字段始终包含 quotation_id 标记,格式:{名称}(quotation_{quotation_id}) // 如果 quotation_name 已经包含标记,直接使用;否则追加标记 $quotationMarker = '(quotation_' . $quotation_id . ')'; if ($quotation_name) { // 如果 quotation_name 中已经包含标记,直接使用;否则追加标记 if (strpos($quotation_name, $quotationMarker) === false) { $quotationName = $quotation_name . $quotationMarker; } else { $quotationName = $quotation_name; } } else { // 未传 quotation_name:客户名称_项目名称_日期 $businessName = ''; if (is_object($business)) { $businessName = isset($business->name) ? trim((string)$business->name) : ''; } else { $businessName = isset($business['name']) ? trim((string)$business['name']) : ''; } $dateStr = date('Ymd'); $segments = array_values(array_filter([trim($customer_name), $businessName, $dateStr], function ($v) { return $v !== ''; })); $baseName = implode('_', $segments); $quotationName = $baseName !== '' ? ($baseName . $quotationMarker) : ('用友报价单-' . $quotation_number . $quotationMarker); } if ($existing) { // 更新现有记录 $existing->name = $quotationName; // 不更新 status,因为可能字段不存在 $result = $existing->save(); $amodelaModel = $existing; } else { // 创建新的关联记录 // 构建保存数据 // Amodela(amodel_a) 在现有系统里通常包含较多字段(Billczgprz 写入了 customer_id/business_name/type/json/amodel_id/status 等) // 为避免生产库字段存在 NOT NULL / 无默认值导致 500(System Error),这里补齐一套“安全默认值” $amodelaModel->business_id = $business_id; $amodelaModel->bill_id = 0; // 用友集成报价单:不对应 PHP 流程单据 $amodelaModel->name = $quotationName; $amodelaModel->status = '1'; // 直接标记为已关联 $amodelaModel->amodel_id = 0; $amodelaModel->type = 'goods'; $amodelaModel->goods_id = ''; $amodelaModel->json = json_encode([], JSON_UNESCAPED_UNICODE); $amodelaModel->lr = 1; $amodelaModel->file = ''; // 补齐客户信息/项目名称(如果字段存在) // $business 可能是对象或数组,需要兼容处理 $customerId = 0; $businessName = ''; if (is_object($business)) { $customerId = isset($business->customer_id) ? $business->customer_id : 0; $businessName = isset($business->name) ? $business->name : ''; } else { $customerId = isset($business['customer_id']) ? $business['customer_id'] : 0; $businessName = isset($business['name']) ? $business['name'] : ''; } $amodelaModel->customer_id = $customerId; $amodelaModel->business_name = $businessName; if ($customerId) { try { $amodelaModel->customer_name = \addons\antis\model\Customer::where('id', $customerId)->value('name') ?: ''; } catch (\Exception $e) { // customer_name 非关键字段,异常时置空即可 $amodelaModel->customer_name = ''; } } else { $amodelaModel->customer_name = ''; } // 调试:记录保存前的数据 \think\Log::write('save_quotation_link 准备保存数据: business_id=' . $business_id . ', customer_id=' . $customerId . ', name=' . $quotationName . ', bill_id=0, type=goods, status=1, amodel_id=0', 'info'); // 尝试保存 try { // 使用 allowField(true) 以数据库真实字段为准,避免“字段不存在”导致 SQL 报错 $result = $amodelaModel->allowField(true)->save(); // 调试:记录保存结果 if ($result) { $savedId = $amodelaModel->id; \think\Log::write('save_quotation_link 保存成功: id=' . $savedId, 'info'); // 立即验证保存是否成功 $verifyRecord = $amodelaModel->where('id', $savedId)->find(); if ($verifyRecord) { \think\Log::write('save_quotation_link 验证成功: id=' . $savedId . ', name=' . $verifyRecord['name'], 'info'); } else { \think\Log::write('save_quotation_link 警告: save()返回true但查询不到记录 id=' . $savedId, 'warning'); } } else { $errorMsg = $amodelaModel->getError() ?: '未知错误'; \think\Log::write('save_quotation_link 保存失败: ' . $errorMsg, 'error'); \think\Log::write('save_quotation_link 模型数据: ' . json_encode($amodelaModel->getData(), JSON_UNESCAPED_UNICODE), 'error'); } } catch (\Exception $e) { \think\Log::write('save_quotation_link 保存异常: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error'); \think\Log::write('save_quotation_link 异常堆栈: ' . $e->getTraceAsString(), 'error'); throw $e; } } if ($result && isset($amodelaModel->id) && $amodelaModel->id > 0) { $fastflowInfo = ['bill_id' => null, 'flow_started' => false, 'msg' => '']; try { $fastflowInfo = self::syncYongyouBaojiadanAfterQuotationLink( $amodelaModel, $business, (string)$quotation_number, $quotation_id, $total_amount, $lrl, $initiator_staff_id ); } catch (\Throwable $e) { $fastflowInfo['msg'] = $e->getMessage(); \think\Log::write('save_quotation_link FastFlow 同步异常: ' . $e->getMessage(), 'error'); } // 返回成功信息,包含保存的ID和name用于调试 ob_clean(); echo json_encode([ 'code' => 1, 'msg' => '报价单关联成功', 'data' => [ 'id' => $amodelaModel->id, 'name' => $amodelaModel->name, 'business_id' => $business_id, 'quotation_id' => $quotation_id, 'fastflow' => $fastflowInfo, ] ], JSON_UNESCAPED_UNICODE); exit; } else { $errorMsg = '报价单关联失败:保存返回false或未获取到ID'; if ($amodelaModel->getError()) { $errorMsg .= ',错误:' . $amodelaModel->getError(); } if (isset($amodelaModel->id)) { $errorMsg .= ',ID:' . $amodelaModel->id; } else { $errorMsg .= ',未获取到ID'; } // 记录详细的错误信息 \think\Log::write('save_quotation_link 保存失败详情: ' . $errorMsg, 'error'); \think\Log::write('save_quotation_link 模型数据: ' . json_encode($amodelaModel->getData(), JSON_UNESCAPED_UNICODE), 'error'); ob_clean(); echo json_encode(['code' => 0, 'msg' => $errorMsg, 'data' => null], JSON_UNESCAPED_UNICODE); exit; } } catch (\Exception $e) { // 记录详细的错误信息 $errorMsg = '保存关联关系失败:' . $e->getMessage(); $errorMsg .= ' | 文件:' . $e->getFile(); $errorMsg .= ' | 行号:' . $e->getLine(); $errorMsg .= ' | 堆栈:' . $e->getTraceAsString(); \think\Log::write('save_quotation_link 异常: ' . $errorMsg, 'error'); // 确保返回 JSON 格式,而不是 HTML ob_clean(); header('Content-Type: application/json; charset=utf-8'); http_response_code(200); echo json_encode(['code' => 0, 'msg' => '保存关联关系失败:' . $e->getMessage(), 'data' => null], JSON_UNESCAPED_UNICODE); exit; } catch (\Throwable $e) { // 捕获所有可捕获的错误(包括致命错误) $errorMsg = '保存关联关系失败(致命错误):' . $e->getMessage(); $errorMsg .= ' | 文件:' . $e->getFile(); $errorMsg .= ' | 行号:' . $e->getLine(); \think\Log::write('save_quotation_link 致命错误: ' . $errorMsg, 'error'); ob_clean(); header('Content-Type: application/json; charset=utf-8'); http_response_code(200); echo json_encode(['code' => 0, 'msg' => '保存关联关系失败:' . $e->getMessage(), 'data' => null], JSON_UNESCAPED_UNICODE); exit; } finally { // 清理输出缓冲区 if (ob_get_level() > 0) { ob_end_flush(); } } } /** * 添加 */ public function add() { if ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params = $this->preExcludeFields($params); $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params); if ($result !== true) { $this->error($result); } $result = false; Db::startTrans(); try { $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params); if ($params['product']) { $params['product'] = json_decode($params['product'], true); } $result = $this->model::createBusiness($params); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result !== false) { $this->success(); } else { $this->error(__('No rows were inserted')); } } $this->error(__('Parameter %s can not be empty', '')); } $customer_id = input('customer_id'); $this->assign('customer_id', $customer_id); //halt($customer_id); $this->assign('customer', Customer::get($customer_id)); $this->assign('staffs', Staff::allList()); $this->assign('form_data', Form::getDataValue('business')); return $this->view->fetch(); } /** * 修改 */ public function edit($ids = null) { $map['id'] = $ids; if ($this->request->isAjax()) { $params = $this->request->post('row/a'); $params = $this->preExcludeFields($params); $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params,$ids); if ($result !== true) { $this->error($result); } Db::startTrans(); try { $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params); $params['id'] = $ids; $result = $this->model::updateBusiness($params); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result !== false) { $this->success(); } else { $this->error(__('No rows were inserted')); } } $row = $this->model->where($map)->with(['customer'])->find(); $product=BusinessProduct::where(['business_id'=>$ids])->with(['productinfo'])->select(); foreach ($product as $k=>$v){ if($v['productinfo']){ $v['product_name']=$v['productinfo']['name']; $v['cost_price']=$v['productinfo']['cost_price']; $v['type']=$v['productinfo']['type']; if($v['productinfo']['goods']){ $v['goods_name']=$v['productinfo']['goods']['name']; } } $product[$k]=$v; } $row['product']=json_encode($product); $row = $row->toArray(); $row = BusinessOther::getOther($row); $this->view->assign("row", $row); $this->assign('customers', Customer::getList()); $this->assign('form_data', Form::getDataValue('business', $row)); return $this->view->fetch(); } /** * 详情 */ public function detail($ids = null) { $row = $this->model->where(['id' => $ids])->with([ 'customer', 'ownerStaff' ])->find(); if (empty($row)) { $this->error(__('No Results were found')); } $row = $row->toArray(); $row = BusinessOther::getOther($row); //跟进记录 $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids)); $type = BusinessStatus::where(array('business_id'=>$ids))->order('id desc')->value('type'); $row['type'] = $type ? (int)$type : 0; $this->assign('row', $row); $this->assign('ids', $ids); $this->assign('form_data', Form::getDataValue('business', $row)); $customerName = ''; if (!empty($row['customer']) && is_array($row['customer']) && !empty($row['customer']['name'])) { $customerName = $row['customer']['name']; } $this->assignconfig("idinfo", [ 'id' => $ids, 'name' => $row['name'] ?? '', 'customer_id' => $row['customer_id'] ?? '', 'customer_name' => $customerName, ]); return $this->view->fetch(); } /** * 添加跟进 */ public function record($ids = null) { if ($this->request->isPost()) { $params = $this->request->post('row/a'); $params['relation_type'] = 5; $params['relation_id'] = $ids; if(!empty($params['files'])){ $params['files']=File::getId($params['files']); } Db::startTrans(); try { $result = Record::createRecord($params); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result) { $this->success('创建跟进记录成功'); } $this->error('创建失败'); } $staff=Staff::where([])->column('name','id'); $follow= Field::getField('项目状态'); $this->assign('follow', $follow); $this->assign('ids', $ids); $this->assign('staff', $staff); return $this->view->fetch(); } /** * 批量转移项目 */ public function batch_change($ids = null) { $ids = json_decode($ids, true); $ids = $this->model->where([ 'id' => ['in', $ids] ])->column('id'); if (empty($ids)) { $this->error(__('No Results were found')); } if ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params = $this->preExcludeFields($params); $result = false; Db::startTrans(); try { $result = $this->model::batchTransfer($ids, $params['owner_staff_id']); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result !== false) { $this->success(); } else { $this->error(__('No rows were inserted')); } } $this->error(__('Parameter %s can not be empty', '')); } $staffs = Staff::getList(); $this->assign('staffs', $staffs); $this->assign('ids', json_encode($ids)); return $this->view->fetch(); } /** * 产品信息 */ public function product() { $this->request->filter(['strip_tags']); if ($this->request->isAjax()) { list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $business_id = input('business_id'); $wheres['business_product.business_id'] =$business_id; $list = BusinessProduct::where($where)->where($wheres)->with(['product'])->order($sort, $order)->paginate($limit); foreach($list as $k=>$v){ if(!$v['product']['id']){ unset($list[$k]); } } $row = $list->items(); $result = array("total" => $list->total(), "rows" => $row); return json($result); } return $this->view->fetch(); } /** * 获取相关合同 */ public function get_contract() { list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $business_id = input('business_id'); $wheres['business_id'] =$business_id; $list = Contract::where([ 'business_id' => $business_id, ])->with('customer')->order('id desc')->paginate($limit); $result = array("total" => $list->total(), "rows" => $list->items()); return json($result); } /** * 删除项目 */ public function delete($ids = null) { if(!$ids){ $this->error('参数不正确'); } $data = $this->model->where([ 'id' => $ids ])->column('id'); if (empty($data)) { $this->error('项目不存在'); } $result = $this->model->where(array('id'=>$ids))->update(array('updatetime'=>time(),'deletetime'=>time())); if(!$result){ $this->error('删除失败'); } $this->success('删除成功'); } /** * 推进项目 */ public function batch_status($ids = null) { $ids = $this->model->where([ 'id' => $ids ])->value('id'); if (empty($ids)) { $this->error('项目不存在'); } if ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params = $this->preExcludeFields($params); if(!empty($params['file'])){ $params['file']=File::getId($params['file']); } $result = false; Db::startTrans(); try { $params['id'] = $ids; $result = $this->model::batchStatus($params); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result !== false) { $this->success(); } else { $this->error('推进失败'); } } $this->error('推进失败'); } return $this->view->fetch(); } /** * 获取推进项目 */ public function get_business_status() { list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $business_id = input('business_id'); $wheres['business_id'] =$business_id; $list = BusinessStatus::where([ 'business_id' => $business_id, ])->order('id desc')->paginate($limit); foreach($list as $k=>$v){ if($v['file']){ $list[$k]['file'] = File::where(array('id'=>['in',$v['file']]))->select(); } } $result = array("total" => $list->total(), "rows" => $list->items()); return json($result); } /** * 导入客户 * @return string|void */ public function import() { set_time_limit(0); if ($this->request->isPost()) { $file = $this->request->request('file'); $staff_id = $this->request->request('staff_id', 0); if (!$file) { $this->error(__('Parameter %s can not be empty', 'file')); } $filePath = ROOT_PATH . 'public' . $file; if (!is_file($filePath)) { $this->error(__('No results were found')); } //实例化reader $ext = pathinfo($filePath, PATHINFO_EXTENSION); if (!in_array($ext, ['csv', 'xls', 'xlsx'])) { $this->error(__('Unknown data format')); } if ($ext === 'csv') { $file = fopen($filePath, 'r'); $filePath = tempnam(sys_get_temp_dir(), 'import_csv'); $fp = fopen($filePath, "w"); $n = 0; while ($line = fgets($file)) { $line = rtrim($line, "\n\r\0"); $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']); if ($encoding != 'utf-8') { $line = mb_convert_encoding($line, 'utf-8', $encoding); } if ($n == 0 || preg_match('/^".*"$/', $line)) { fwrite($fp, $line . "\n"); } else { fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n"); } $n++; } fclose($file) || fclose($fp); $reader = new Csv(); } elseif ($ext === 'xls') { $reader = new Xls(); } else { $reader = new Xlsx(); } if (!$PHPExcel = $reader->load($filePath)) { $this->error(__('Unknown data format')); } $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表 $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号 $allRow = $currentSheet->getHighestRow(); //取得一共有多少行 $maxColumnNumber = Coordinate::columnIndexFromString($allColumn); //开始读取数据 $fields = []; for ($currentRow = 1; $currentRow <= 1; $currentRow++) { for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); $fields[$currentRow][] = $val; if ($val instanceof RichText) {//富文本转换字符串 $val = $val->__toString(); } $values[] = is_null($val) ? '' : trim($val); } } if (!isset($fields[1])) { $this->error('导入文件第一行没有数据'); } $lastid = $this->model->withTrashed()->order('id desc')->value('id'); $lastid = $lastid + 5;//防止重复 $customerRow = []; $errorInfo = []; $customerNames=Customer::where([])->column('id,owner_staff_id','name'); $fieldnames = FormField::where(['types' => FormField::BUSINESS_TYPE])->column('field', 'name'); if(!$fieldnames){ $this->error('请在系统管理->字段管理中保存项目管理表单生成项目导入字段'); } $fn = []; for ($currentRow = 1; $currentRow <= 1; $currentRow++) { $values = []; for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); $values[] = is_null($val) ? '' : $val; } foreach ($values as $l) { $fn[] = $fieldnames[$l] ?? ''; } } for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) { $values = []; for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); if ($val instanceof RichText) {//富文本转换字符串 $val = $val->__toString(); } $values[] = is_null($val) ? NULL : trim($val); } $lastid++; $addBusiness = ['id' => $lastid]; $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0; if(empty($customer)){ $errorInfo[] = "第{$currentRow}行,客户名称不存在;"; continue; } $addBusiness['customer_id']=$customer['id']; $addBusiness['owner_staff_id']=$customer['owner_staff_id']; foreach ($values as $kv => $value) { if (!isset($fn[$kv]) || empty($fn[$kv])) { continue; } $addBusiness[$fn[$kv]] = $value; } if (empty($addBusiness['name'])) { $errorInfo[] = "第{$currentRow}行,项目名称不能为空;"; continue; } $customerRow[] = $addBusiness; } if (!empty($errorInfo)) { $this->error(implode(',', $errorInfo)); } Db::startTrans(); try { $this->model::importBusiness($customerRow); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } $this->success('导入成功'); } $this->assign('staffs', Staff::getList()); return $this->view->fetch(); } /** * 模板 */ public function template() { $title = ['客户名称']; $dataValue = Form::getDataValue(Form::BUSINESS_TYPE); foreach ($dataValue as $val) { $title[] = $val['config']['label']; } $file = export_excel($title, [], '项目'); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename=' . $file['fileName']); header('Cache-Control: max-age=0'); $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); // 以下内容是excel文件的信息描述信息 $obj->getProperties()->setTitle('导出文件'); //设置标题 $obj->setActiveSheetIndex(0); $obj->getActiveSheet()->setTitle('导出文件'); /* 循环读取每个单元格的数据 */ $a = 'A'; $currentSheet = $obj->getActiveSheet(); foreach ($title as $key => $value) { //读取工作表1 // 设置第一行加粗 $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true); //这里是设置单元格的内容 $currentSheet->getCell($a . '1')->setValue($value); $a++; } $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj); $PHPWriter->save('php://output'); } /** * 导出信息 */ public function export() { $this->request->filter(['strip_tags', 'trim']); $ids = input('ids'); $isall = input('isall',1); $wheres = array(); //导出其中几条 if (isset($ids) && $ids) { $wheres['id'] = array('in', $ids); } //导出全部 if ($isall == 3) { unset($wheres['id']); } //0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的 $type = input('type', 0); list($where, $sort, $order, $offset, $limit) = $this->buildparams(); $staff = Staff::info(); $staff_id = $staff->id; switch ($type) { case 1: $wheres['owner_staff_id'] = $staff_id; break; case 2: $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId()); break; case 3: $start = date('Y-m-d 00:00:00'); $end = date('Y-m-d 23:59:59'); $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray(); $relationId = []; foreach ($record as $k => $v) { $whereRe['id'] = array('gt', $v['id']); $whereRe['relation_id'] = $v['relation_id']; $recordData = Record::where($whereRe)->count(); if ($recordData == 0) { $relationId[] = $v['relation_id']; } } $wheres['id'] = array('in', $relationId); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; case 4: $start = date('Y-m-d 00:00:00'); $end = date('Y-m-d 23:59:59'); $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray(); $relationId = []; foreach ($record as $k => $v) { $whereRe['id'] = array('gt', $v['id']); $whereRe['relation_id'] = $v['relation_id']; $recordData = Record::where($whereRe)->count(); if ($recordData >= 1) { $relationId[] = $v['relation_id']; } } $wheres['id'] = array('in', $relationId); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; case 5: $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray(); $wheres['id'] = array('not in', $record); $staff = Staff::info(); $wheres['owner_staff_id'] = $staff->id; break; default: $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds()); break; } $list = $this->model->with([ 'ownerStaff','businessOther','customer' ])->where($where)->where($wheres)->order($sort, $order)->select(); $list = collection($list)->toArray(); if (!$list) { $this->error('无导出数据'); } $title = [ '序号', '客户名称', '负责人', '创建时间', '下次联系时间', ]; $dataValue = Form::getDataValue(Form::BUSINESS_TYPE); foreach ($dataValue as $val) { $title[] = $val['config']['label']; } foreach ($list as $k => $v) { if($v['business_other']){//其他客户 $other=$v['business_other']['otherdata']; $other=json_decode($other,true); $v = array_merge($v, $other); } $field = array( $v['id'], $v['customer']['name'], $v['owner_staff']['name'], date('Y-m-d H:i:s',$v['createtime']), $v['next_time'], ); foreach ($dataValue as $val) { if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') { $field[] = $v[$val['id'] . '_str'] ?? ''; } else { $field[] = ($v[$val['id']] ?? ''); } } $data[] = $field; } $file = export_excel($title, $data, '项目'); if ($file['filePath']) { $this->success('导出成功', '', $file); } $this->error('导出失败'); } /** * 导入产品明细 * @return string|void */ public function import_product() { set_time_limit(0); if ($this->request->isPost()) { $file = $this->request->request('file'); if (!$file) { $this->error(__('Parameter %s can not be empty', 'file')); } $filePath = ROOT_PATH . 'public' . $file; if (!is_file($filePath)) { $this->error(__('No results were found')); } //实例化reader $ext = pathinfo($filePath, PATHINFO_EXTENSION); if (!in_array($ext, ['csv', 'xls', 'xlsx'])) { $this->error(__('Unknown data format')); } if ($ext === 'csv') { $file = fopen($filePath, 'r'); $filePath = tempnam(sys_get_temp_dir(), 'import_csv'); $fp = fopen($filePath, "w"); $n = 0; while ($line = fgets($file)) { $line = rtrim($line, "\n\r\0"); $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']); if ($encoding != 'utf-8') { $line = mb_convert_encoding($line, 'utf-8', $encoding); } if ($n == 0 || preg_match('/^".*"$/', $line)) { fwrite($fp, $line . "\n"); } else { fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n"); } $n++; } fclose($file) || fclose($fp); $reader = new Csv(); } elseif ($ext === 'xls') { $reader = new Xls(); } else { $reader = new Xlsx(); } if (!$PHPExcel = $reader->load($filePath)) { $this->error(__('Unknown data format')); } $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表 $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号 $allRow = $currentSheet->getHighestRow(); //取得一共有多少行 $maxColumnNumber = Coordinate::columnIndexFromString($allColumn); //开始读取数据 $fields = []; for ($currentRow = 1; $currentRow <= 1; $currentRow++) { for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); $fields[$currentRow][] = $val; if ($val instanceof RichText) {//富文本转换字符串 $val = $val->__toString(); } $values[] = is_null($val) ? '' : trim($val); } } if (!isset($fields[1])) { $this->error('导入文件第一行没有数据'); } $lastid = BusinessProduct::order('id desc')->value('id'); $lastid = $lastid + 5;//防止重复 $businessProductRow = []; $errorInfo = []; $businessName=$this->model::where([])->column('id,name,money','name'); $productName=Product::where([])->column('id,price','name'); for ($currentRow = 1; $currentRow <= 1; $currentRow++) { $values = []; for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); $values[] = is_null($val) ? '' : $val; } } for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) { $values = []; for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue(); if ($val instanceof RichText) {//富文本转换字符串 $val = $val->__toString(); } $values[] = is_null($val) ? NULL : trim($val); } $lastid++; $addContractProduct = ['id' => $lastid]; $business = isset($businessName[$values[0]]) ? $businessName[$values[0]] : 0; if (empty($business)) { $errorInfo[] = "第{$currentRow}行,项目名称不存在;"; continue; } $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0; if (empty($product)) { $errorInfo[] = "第{$currentRow}行,产品名称不存在;"; continue; } if (empty($values[2])) { $errorInfo[] = "第{$currentRow}行,产品数量不能为空;"; continue; } if (empty($values[3])) { $errorInfo[] = "第{$currentRow}行,产品售价不能为空;"; continue; } $addContractProduct['business_id'] = $business['id']; $addContractProduct['product_id'] = $product['id']; $addContractProduct['number'] = $values[2]; $addContractProduct['price'] = $values[3]; $businessProductRow[]=$addContractProduct; } if (!empty($errorInfo)) { $this->error(implode(',', $errorInfo)); } Db::startTrans(); try { BusinessProduct::importProduct($businessProductRow); Db::commit(); } catch (Exception $e) { Db::rollback(); $this->error($e->getMessage()); } $this->success('导入成功'); } $this->assign('staffs', Staff::getList()); return $this->view->fetch(); } /** * 模板 */ public function template_product() { $title = [ '项目名称', '商品名称', '数量', '售价', ]; $file = export_excel($title, [], '产品明细'); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename=' . $file['fileName']); header('Cache-Control: max-age=0'); $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); // 以下内容是excel文件的信息描述信息 $obj->getProperties()->setTitle('导出文件'); //设置标题 $obj->setActiveSheetIndex(0); $obj->getActiveSheet()->setTitle('导出文件'); /* 循环读取每个单元格的数据 */ $a = 'A'; $currentSheet = $obj->getActiveSheet(); foreach ($title as $key => $value) { //读取工作表1 // 设置第一行加粗 $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true); //这里是设置单元格的内容 $currentSheet->getCell($a . '1')->setValue($value); $a++; } $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj); $PHPWriter->save('php://output'); } /** * 导出信息 */ public function export_product() { $this->request->filter(['strip_tags', 'trim']); $ids = input('ids'); $type = input('type'); $wheres = array(); //导出其中几条 if (isset($ids)) { $wheres['business_id'] = array('in', $ids); } //导出全部 if (isset($type)) { if ($type == 3) { unset($wheres['business_id']); } } $list=BusinessProduct::where($wheres)->with(['business','productinfo'])->select(); $list = collection($list)->toArray(); if (!$list) { $this->error('无导出数据'); } $title = [ '序号', '项目名称', '商品名称', '售价', '批发价', '产品', '规格', '数量', ]; foreach ($list as $k => $v) { $field = array( $v['id'], $v['business']['name'], $v['productinfo']['name']??'', $v['price']??'', $v['productinfo']['cost_price']??'', $v['productinfo']['goods']['name']??'', $v['productinfo']['unit']??'', $v['number']??'', ); $data[] = $field; } $file = export_excel($title, $data, '产品明细'); if ($file['filePath']) { $this->success('导出成功', '', $file); } $this->error('导出失败'); } /** * 项目详情报价单列表:统一补充 is_yongyou、external_url、流程状态文案(与 fastflow/bill/yongyouy_baojiadan 一致)。 * * @param array $item amodel_a 一行(须为数组,调用方请先把 Model 转成 toArray) * @param Amodela|null $AmodelaModel 非空时保留原 PHP 报价单 status 回写逻辑 */ public static function enrichQuotationListRow(&$item, $AmodelaModel = null) { if (!is_array($item)) { $item = is_object($item) && method_exists($item, 'toArray') ? $item->toArray() : (array)$item; } $labels = ['0' => '待发起', '1' => '流程中', '2' => '通过', '3' => '终止']; $cModle = new Czgprz(); if (isset($item['name']) && strpos($item['name'], '(quotation_') !== false) { $item['is_yongyou'] = true; if (preg_match('/\(quotation_(\d+)\)/', $item['name'], $matches)) { $item['quotation_id'] = $matches[1]; } else { $item['quotation_id'] = null; } $item['external_url'] = get_yongyou_integration_full_url('quotation', [ 'id' => $item['quotation_id'], 'mode' => 'view', ]); $bid = isset($item['bill_id']) ? (int)$item['bill_id'] : 0; if ($bid > 0) { $st = null; try { $st = Db::name('yongyouy_baojiadan')->where('id', $bid)->value('status'); } catch (\Throwable $e) { \think\Log::write('enrichQuotationListRow 读取 yongyouy_baojiadan 失败: ' . $e->getMessage(), 'warning'); } if ($st === null || $st === '') { $item['status'] = '0'; $item['status_text'] = $labels['0']; } else { $k = (string)$st; $item['status'] = $k; $item['status_text'] = isset($labels[$k]) ? $labels[$k] : $k; } } else { $item['status'] = '0'; $item['status_text'] = '待发起流程'; } return; } $item['is_yongyou'] = false; if (!empty($item['bill_id'])) { $status = $cModle->where('id', $item['bill_id'])->value('status'); if ($status == '2' && $AmodelaModel) { $AmodelaModel->where('id', $item['id'])->update(['status' => '1']); } $item['status'] = $status; $k = (string)$status; $item['status_text'] = isset($labels[$k]) ? $labels[$k] : (string)$status; } else { $item['status_text'] = isset($item['status']) ? (string)$item['status'] : ''; } } /** * 用友报价单写入项目后:创建/更新「报价单2026」表 (yongyouy_baojiadan),并尝试发起 FastFlow。 * amodel_a.bill_id 存 yongyouy_baojiadan.id(与 PHP 报价单走 Czgprz 互斥:用友行靠 name 中 quotation_ 识别)。 * * @return array{bill_id:int|null, flow_started:bool, msg:string} */ protected static function syncYongyouBaojiadanAfterQuotationLink($amodelaModel, $business, $quotationNumber, $quotationId, $totalAmount, $lrl, $initiatorStaffId) { $ret = ['bill_id' => null, 'flow_started' => false, 'msg' => '']; $prefix = config('database.prefix'); $billTable = $prefix . 'yongyouy_baojiadan'; $flowId = Db::name('fastflow_flow')->where('bill', $billTable)->where('status', 1)->order('id', 'asc')->value('id'); // 流程里「报价单编号」存集成报价单主键 id,便于跳转 /quotation?id=;业务单号在 amodel_a.name 中仍有体现 $bjdbh = $quotationId > 0 ? (string)(int)$quotationId : ($quotationNumber !== '' ? (string)$quotationNumber : ''); $bjdje = $totalAmount; $lrlVal = $lrl !== null ? floatval($lrl) : 0; $ownerStaffId = 0; if (is_object($business)) { $ownerStaffId = (int)($business->owner_staff_id ?? 0); } elseif (is_array($business)) { $ownerStaffId = (int)($business['owner_staff_id'] ?? 0); } $staffIdForFlow = $initiatorStaffId > 0 ? (int)$initiatorStaffId : $ownerStaffId; $adminId = 1; if ($staffIdForFlow > 0) { $aid = Staff::where('id', $staffIdForFlow)->value('admin_id'); if ($aid) { $adminId = (int)$aid; } } $ffId = (int)($amodelaModel->bill_id ?? 0); $now = time(); if ($ffId > 0) { Db::name('yongyouy_baojiadan')->where('id', $ffId)->update([ 'bjdbh' => $bjdbh, 'bjdje' => $bjdje, 'lrl' => $lrlVal, 'updatetime' => $now, ]); $ret['bill_id'] = $ffId; $ret['flow_started'] = true; $ret['msg'] = '已更新流程单据字段'; return $ret; } $ffId = (int)Db::name('yongyouy_baojiadan')->insertGetId([ 'bjdbh' => $bjdbh, 'bjdje' => $bjdje, 'lrl' => $lrlVal, 'initiator_id' => $adminId, 'status' => 0, 'createtime' => $now, 'updatetime' => $now, ]); if ($ffId <= 0) { $ret['msg'] = '创建报价单2026单据失败'; return $ret; } Db::name('amodel_a')->where('id', $amodelaModel->id)->update(['bill_id' => $ffId]); $amodelaModel->bill_id = $ffId; $ret['bill_id'] = $ffId; if (!$flowId) { $ret['msg'] = '未配置 fastflow_flow(bill=' . $billTable . '),已建单未发起流程'; return $ret; } $staffAuth = StaffAuth::instance(['type' => 'Mysqlstaff']); $didDirect = false; if ($staffIdForFlow > 0) { $didDirect = (bool)$staffAuth->direct($staffIdForFlow); } try { $api = new \addons\fastflow\model\api(new \app\admin\controller\fastflow\flow\CustomMessage(), null); $res = $api->startFlow([ 'flow_id' => $flowId, 'bill' => $billTable, 'bill_id' => $ffId, 'ebill_id' => '', ]); if (is_array($res) && array_key_exists('code', $res)) { $ret['flow_started'] = ((int)$res['code'] === 1); $ret['msg'] = isset($res['msg']) ? (string)$res['msg'] : ''; } else { $ret['msg'] = '流程返回异常'; } } catch (\Throwable $e) { $ret['msg'] = $e->getMessage(); \think\Log::write('syncYongyouBaojiadan startFlow: ' . $e->getMessage(), 'error'); } finally { if ($didDirect) { try { $staffAuth->logout(); } catch (\Throwable $e) { } } } return $ret; } }