Compare commits

..

52 Commits

Author SHA1 Message Date
李琦
50bea95440 1. erp暂时西药使用统一的订单 2026-08-07 16:57:54 +08:00
李琦
37cf4cfb7d 1. 挂号的时候校验挂号类型、绑定诊所 2026-08-07 15:17:01 +08:00
李琦
488adc1289 1. 调试erp 2026-07-30 13:36:55 +08:00
李琦
fca11a4efd 1. 调试erp 2026-07-24 09:27:35 +08:00
李琦
83a986f1b1 1. 调试erp 2026-07-24 09:19:55 +08:00
李琦
fcb3ae1ffc 1. 调试erp 2026-07-20 16:19:59 +08:00
李琦
3b0a2a5b81 1. 调试erp 2026-07-20 16:18:43 +08:00
李琦
74b3b44c19 1. 调试erp 2026-07-20 16:17:24 +08:00
李琦
021e33a900 1. 调试支付配置 2026-07-20 16:15:34 +08:00
李琦
5be1ae3f1b 1. 调试支付配置 2026-07-20 16:12:48 +08:00
李琦
ec6ecfc0c2 1. 新增药品的ERP抓取数量倍数 2026-07-20 15:54:57 +08:00
李琦
70c6d498aa 1. 新增药品的ERP抓取数量倍数 2026-07-20 15:50:53 +08:00
李琦
c722b0a9cf 1. 新增药品的ERP抓取数量倍数 2026-07-20 14:44:13 +08:00
李琦
686c188829 1. 新增药品的ERP抓取数量倍数 2026-07-20 14:38:40 +08:00
李琦
9fafba95cc 1. 新增药品的ERP抓取数量倍数 2026-07-20 14:30:36 +08:00
李琦
fe54ece815 1. 新增药品的ERP抓取数量倍数 2026-07-20 13:16:51 +08:00
李琦
c9bcd77d82 1. 新增药品的ERP抓取数量倍数 2026-07-14 08:24:27 +08:00
李琦
9ed40a41c0 1. 医生新增测试医生
2. 回调分账链路的注释
3. 减少首页访问的时候数据返回量
2026-07-13 14:34:04 +08:00
李琦
40aa024a5f 1. 更改支付回调 2026-07-06 16:26:43 +08:00
李琦
c77c7501e0 1. 推广员用户挂号 2026-07-03 09:38:52 +08:00
李琦
e4854647c8 1. 推广员用户挂号 2026-07-03 09:38:31 +08:00
李琦
da00506088 1. 推广员用户挂号 2026-07-03 09:35:12 +08:00
李琦
5f5ef87b44 1. 推广员用户挂号 2026-06-15 16:20:02 +08:00
李琦
bede28aced 1. 协议查询 2026-06-15 16:07:18 +08:00
李琦
e3205fbeb1 1. 协议查询 2026-06-15 14:01:04 +08:00
李琦
8cafa68399 1. 协议查询 2026-06-15 14:01:00 +08:00
李琦
3d25bc0a88 1. 协议查询 2026-06-05 15:31:43 +08:00
李琦
34827ed1cd 1. 协议查询 2026-06-05 15:24:00 +08:00
李琦
6b7f9e8971 1. 分账资金变动功能 2026-06-02 08:15:42 +08:00
李琦
6a8c4dcdf6 1. 处方详情 2026-06-01 14:14:02 +08:00
李琦
9a95c14554 1. 处方详情 2026-05-27 13:06:34 +08:00
李琦
e6b23758f8 1. 处方详情 2026-05-22 10:24:51 +08:00
李琦
e033bd787f 1. 挂号绑定挂号id 2026-05-22 10:24:28 +08:00
李琦
a60a3f9255 1. 解决了切换诊所导致用户无法访问首页的问题 2026-05-16 15:56:52 +08:00
李琦
49e98f7641 登陆默认绑定俊良诊所,因为后续的在线复诊如果没有绑定会出问题 2026-05-14 08:13:27 +08:00
李琦
35a4a72802 登陆默认绑定俊良诊所,因为后续的在线复诊如果没有绑定会出问题 2026-05-14 08:09:36 +08:00
李琦
96224aa268 分账的诊疗费 2026-05-12 17:03:37 +08:00
李琦
aae644720f 门店绑定优化 2026-05-12 16:59:58 +08:00
李琦
cd66e2c159 门店绑定优化 2026-05-08 16:49:01 +08:00
李琦
313e9ff79e 回滚门店绑定 2026-05-08 15:54:18 +08:00
李琦
857fd0730e 分账剂数还原 2026-05-08 15:37:52 +08:00
李琦
4e5507187d 分账剂数还原 2026-04-30 13:08:20 +08:00
李琦
dcfbb830db 分账剂数还原 2026-04-30 13:05:16 +08:00
李琦
cff74a74b6 分账剂数 2026-04-30 13:04:58 +08:00
李琦
d2fe8f5a58 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	common/forms/LedgerForm.php
2026-04-30 13:02:48 +08:00
李琦
ec5e919803 修复因为订单计数0导致的分账问题 2026-04-30 09:19:47 +08:00
李琦
9852b8534b 默认剂数 2026-04-29 16:52:58 +08:00
李琦
1d81f31135 默认剂数 2026-04-27 16:21:48 +08:00
李琦
c71ab2cb10 订单详情关联 2026-03-24 12:31:19 +08:00
李琦
a3befd977b 订单详情关联 2026-02-07 16:55:06 +08:00
李琦
908b00db83 订单详情关联 2026-02-07 16:52:55 +08:00
李琦
0297899367 转接方分账 2026-02-07 16:32:21 +08:00
27 changed files with 1445 additions and 219 deletions

View File

@@ -12,6 +12,7 @@ use common\jobs\ProductOrderSyncJob;
use common\jobs\Sms\WaitApprovalMessageJob; use common\jobs\Sms\WaitApprovalMessageJob;
use common\jobs\templateMessage\PrescriptionCreated; use common\jobs\templateMessage\PrescriptionCreated;
use common\models\oldDb\Prescription; use common\models\oldDb\Prescription;
use common\models\oldDb\PrescriptionLog;
use common\models\oldDb\ProductOrder; use common\models\oldDb\ProductOrder;
use common\models\oldDb\ProductOrderLog; use common\models\oldDb\ProductOrderLog;
use common\models\oldDb\Reconciliation; use common\models\oldDb\Reconciliation;
@@ -20,6 +21,7 @@ use common\models\oldDb\Store;
use common\models\oldDb\User; use common\models\oldDb\User;
use common\services\JacErpService; use common\services\JacErpService;
use common\services\WeappService; use common\services\WeappService;
use common\services\WechatService;
use yii\db\ActiveRecord; use yii\db\ActiveRecord;
use yii\db\Exception; use yii\db\Exception;
use yii\helpers\Json; use yii\helpers\Json;
@@ -39,18 +41,91 @@ class OpenApiController extends BaseAdminController
$prescription = \Yii::$app->request->post('prescription'); $prescription = \Yii::$app->request->post('prescription');
//处方开具待支付订阅消息通知 //处方开具待支付订阅消息通知
\Yii::$app->queue->push(new PrescriptionCreated([ $this->sendUserNote($prescription);
'orderId' => $prescription, // //处方开具待支付订阅消息通知
])); // \Yii::$app->queue->push(new PrescriptionCreated([
// 'orderId' => $prescription,
// ]));
//处方生成短信通知药师审方 //处方生成短信通知药师审方
\Yii::$app->queue->push(new WaitApprovalMessageJob([ // \Yii::$app->queue->push(new WaitApprovalMessageJob([
'orderId' => $prescription, // 'orderId' => $prescription,
])); // ]));
return ['ok']; return ['ok'];
} }
public function sendUserNote($orderId)
{
PrescriptionLog::saveLog($orderId,'处方订单生成通知用户支付订阅消息发送队列 start');
$t = \Yii::$app->db->beginTransaction();
try {
$this->setRequest();
$Prescription = Prescription::find()->where([
'id' => $orderId
])->with(['user','doctorInfo','userPatient'])->one();
if (!$Prescription||!$Prescription->user||!$Prescription->doctorInfo) {
throw new \yii\base\Exception('处方不存在或已取消');
}
PrescriptionLog::saveLog($orderId,'处方订单生成通知用户支付订阅消息发送队列 load');
PrescriptionLog::saveLog($orderId,json_encode([
'touser' => $Prescription->user->openid,
'template_id' => \Yii::$app->params['template']['user']['prescription_created'],
'page' => 'subPackages/my/myrecord-detail?id='.$Prescription->id.'&no='.$Prescription->prescription_no,
'data' => [
'name1' => [
'value' => $Prescription->userPatient->name,
],
'thing2' => [
'value' => $Prescription->clinical_diagnose,
],
'name4' => [
'value' => $Prescription->doctorInfo->name,
],
'time9' => [
'value' => date('Y-m-d H:i:s',$Prescription->created_at),
],
'thing11' => [
'value' => '医生已为您开具处方,请尽快前往支付!',
]
]
]));
PrescriptionLog::saveLog($orderId,'处方订单生成通知用户支付订阅消息发送队列 load end');
$result = WechatService::getInstance()->app->subscribe_message->send([
'touser' => $Prescription->user->openid,
'template_id' => \Yii::$app->params['template']['user']['prescription_created'],
'page' => 'subPackages/my/myrecord-detail?id='.$Prescription->id.'&no='.$Prescription->prescription_no,
'data' => [
'name1' => [
'value' => $Prescription->userPatient->name,
],
'thing2' => [
'value' => $Prescription->clinical_diagnose,
],
'name4' => [
'value' => $Prescription->doctorInfo->name,
],
'time9' => [
'value' => date('Y-m-d H:i:s',$Prescription->created_at),
],
'thing11' => [
'value' => '医生已为您开具处方,请尽快前往支付!',
]
]
]);
if(isset($result['errcode']) && $result['errcode']){
throw new Exception('发送失败,失败原因:'.$result['errmsg']);
}
PrescriptionLog::saveLog($orderId,'处方订单生成通知用户支付订阅消息发送队列 end');
} catch (\Exception $exception) {
$t->rollBack();
PrescriptionLog::saveLog($orderId,'处方订单生成通知用户支付订阅消息发送队列异常:'.$exception->getMessage());
return;
}
}
/** /**
* 处理处方过期 * 处理处方过期
* @return string[] * @return string[]

View File

@@ -119,7 +119,8 @@ JJvBfLfudYNUjUCyW3gAcOIJ
'rsaPrivateKeyFilePath' => '/www/certs/user-rsa.pfx', //私钥文件路径 'rsaPrivateKeyFilePath' => '/www/certs/user-rsa.pfx', //私钥文件路径
'publicKeyFilePath' => '/www/certs/efps.cer', //公钥 'publicKeyFilePath' => '/www/certs/efps.cer', //公钥
'signType' => 'RSA2', 'signType' => 'RSA2',
'pay_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/notify', // 'pay_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/notify',
'pay_notify_url' => env('PAY_NOTIFY_URL'),
'refund_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/refund-notify', 'refund_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/refund-notify',
'withdraw_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/withdraw-notify' 'withdraw_notify_url' => 'https://app.xiaokang88.com/member/v1/eplpay-callback/withdraw-notify'
], ],

View File

@@ -16,6 +16,7 @@ use common\models\oldDb\Reconciliation;
use common\models\oldDb\Register; use common\models\oldDb\Register;
use common\models\oldDb\RegisterLog; use common\models\oldDb\RegisterLog;
use common\models\oldDb\Store; use common\models\oldDb\Store;
use common\services\AccountAbleChangeLogService;
use yii\db\Exception; use yii\db\Exception;
@@ -53,7 +54,7 @@ class LedgerForm extends BaseModel
throw new Exception('门店不存在'); throw new Exception('门店不存在');
} }
$time = time(); $time = time();
$ledger[] = [ $ledger[] = [
@@ -84,7 +85,7 @@ class LedgerForm extends BaseModel
throw $e; throw $e;
} }
break; break;
default: //产品订单 default: //产品订单
ProductOrderLog::saveLog($this->order_id, '产品订单增加待结算记录开始'); ProductOrderLog::saveLog($this->order_id, '产品订单增加待结算记录开始');
$t = \Yii::$app->db->beginTransaction(); $t = \Yii::$app->db->beginTransaction();
@@ -316,45 +317,45 @@ class LedgerForm extends BaseModel
$transferPrescription = null; $transferPrescription = null;
$transferStoreId = null; $transferStoreId = null;
$delegateStoreId = null; $delegateStoreId = null;
if ($productOrder->prescription && $productOrder->prescription->is_from_transfer == 1 && $productOrder->prescription_type == '1') { if ($productOrder->prescription && $productOrder->prescription->is_from_transfer == 1 && $productOrder->prescription_type == '1') {
// 通过处方关联挂号,再通过挂号关联转诊记录 // 通过处方关联挂号,再通过挂号关联转诊记录
// 处方 -> 挂号(register_id) -> 转诊记录(transfer_prescription_id) // 处方 -> 挂号(register_id) -> 转诊记录(transfer_prescription_id)
if ($productOrder->prescription->register && $productOrder->prescription->register->transferPrescription) { if ($productOrder->prescription->register && $productOrder->prescription->register->transferPrescription) {
$transferPrescription = $productOrder->prescription->register->transferPrescription; $transferPrescription = $productOrder->prescription->register->transferPrescription;
$isTransferPrescription = true; $isTransferPrescription = true;
$transferStoreId = $transferPrescription->transfer_store_id; // 发起方(转诊诊所,西医诊所) $transferStoreId = $transferPrescription->transfer_store_id; // 发起方(转诊诊所,西医诊所)
$delegateStoreId = $transferPrescription->delegate_store_id; // 承接方(委托诊所,中医诊所) $delegateStoreId = $transferPrescription->delegate_store_id; // 承接方(委托诊所,中医诊所)
if (!$transferStoreId || !$delegateStoreId) { if (!$transferStoreId || !$delegateStoreId) {
// 如果转诊信息不完整,按普通处方处理 // 如果转诊信息不完整,按普通处方处理
$isTransferPrescription = false; $isTransferPrescription = false;
} }
} }
} }
// 如果是转诊处方,需要特殊处理分账逻辑 // 如果是转诊处方,需要特殊处理分账逻辑
if ($isTransferPrescription) { if ($isTransferPrescription) {
/* /*
* 转诊处方分账逻辑: * 转诊处方分账逻辑:
* 1. 承接方(委托诊所)分走15%发起方(转诊诊所)的利润 * 1. 发起方(转诊诊所)获得100%的利润
* 2. 发起方获得85%的利润 * 2. 承接方(委托诊所)不分账
* 3. 平台分账保持不变(成本价) * 3. 平台分账保持不变(成本价)
*/ */
// 第一遍遍历:计算所有药品的总利润 // 第一遍遍历:计算所有药品的总利润
$totalProfit = 0; $totalProfit = 0;
$itemProfits = []; $itemProfits = [];
$itemData = []; $itemData = [];
foreach($productOrderItems as $v) { foreach($productOrderItems as $v) {
$number = $v['number']; $number = $v['number'];
$dosage = $v['dosage'] ?? 1; $dosage = $v['dosage'] ?? 1;
$totalPrice = round($dosage * $number * $v['price'], 4); $totalPrice = round($dosage * $number * $v['price'], 4);
$totalBuyPrice = round($dosage * $number * $v['buy_price'], 4); $totalBuyPrice = round($dosage * $number * $v['buy_price'], 4);
$profit = $totalPrice - $totalBuyPrice; $profit = $totalPrice - $totalBuyPrice;
$totalProfit += $profit; $totalProfit += $profit;
$itemProfits[] = $profit; $itemProfits[] = $profit;
$itemData[] = [ $itemData[] = [
@@ -365,15 +366,15 @@ class LedgerForm extends BaseModel
'drug_id' => $v['drug_id'], 'drug_id' => $v['drug_id'],
]; ];
} }
// 计算分账金额:从总利润中分配 // 计算分账金额:从总利润中分配
$delegateProfit = round($totalProfit * 0.15, 2); // 承接方分得15%的总利润 // 转诊处方分账逻辑:全部利润(100%)分给发起方(转诊诊所),承接方不分账
$transferProfit = round($totalProfit * 0.85, 2); // 发起方分得85%的总利润 $transferProfit = round($totalProfit, 2); // 发起方分得100%的总利润(全部利润)
// 第二遍遍历:按每个药品的利润占比,分配承接方和发起方的分账金额 // 第二遍遍历:按每个药品的利润占比,分配发起方的分账金额
foreach($itemData as $index => $item) { foreach($itemData as $index => $item) {
$ledger = []; $ledger = [];
// 医保支付(走月付) // 医保支付(走月付)
if ($productOrder['prescription']['category'] == 2) { if ($productOrder['prescription']['category'] == 2) {
// 查询订单是否已生成月付 // 查询订单是否已生成月付
@@ -389,10 +390,9 @@ class LedgerForm extends BaseModel
} else { } else {
// 按该药品利润占比分配总利润 // 按该药品利润占比分配总利润
$itemProfitRatio = $totalProfit > 0 ? ($itemProfits[$index] / $totalProfit) : 0; $itemProfitRatio = $totalProfit > 0 ? ($itemProfits[$index] / $totalProfit) : 0;
$itemDelegateProfit = round($delegateProfit * $itemProfitRatio, 2); // 该药品承接方应分得的金额 $itemTransferProfit = round($transferProfit * $itemProfitRatio, 2); // 该药品发起方应分得的金额(100%利润)
$itemTransferProfit = round($transferProfit * $itemProfitRatio, 2); // 该药品发起方应分得的金额
// 创建分账记录:发起方(转诊诊所)分得100%利润
// 创建分账记录:发起方(转诊诊所)分得85%利润
$ledger[] = [ $ledger[] = [
'order_id' => $this->order_id, 'order_id' => $this->order_id,
'user_id' => $transferStoreId, // 发起方诊所ID 'user_id' => $transferStoreId, // 发起方诊所ID
@@ -404,30 +404,12 @@ class LedgerForm extends BaseModel
'drug_id' => $item['drug_id'], 'drug_id' => $item['drug_id'],
'xd_time' => $productOrder->created_at, 'xd_time' => $productOrder->created_at,
'number' => $item['number'], 'number' => $item['number'],
'money' => $itemTransferProfit, // 发起方获得85%利润 'money' => $itemTransferProfit, // 发起方获得100%利润
'status' => 0, 'status' => 0,
'created_at' => $time, 'created_at' => $time,
'updated_at' => $time 'updated_at' => $time
]; ];
// 创建分账记录:承接方(委托诊所)分得15%利润
$ledger[] = [
'order_id' => $this->order_id,
'user_id' => $delegateStoreId, // 承接方诊所ID
'user_type' => 1, //门店
'order_type' => 1,//产品订单
'fee_type' => 1,//药品费用
'su_id' => $productOrder->su_id,
'drugstore_id' => $productOrder->store_id,
'drug_id' => $item['drug_id'],
'xd_time' => $productOrder->created_at,
'number' => $item['number'],
'money' => $itemDelegateProfit, // 承接方获得15%利润
'status' => 0,
'created_at' => $time,
'updated_at' => $time
];
// 创建分账记录:平台分账保持不变(成本价) // 创建分账记录:平台分账保持不变(成本价)
$ledger[] = [ $ledger[] = [
'order_id' => $this->order_id, 'order_id' => $this->order_id,
@@ -445,7 +427,7 @@ class LedgerForm extends BaseModel
'created_at' => $time, 'created_at' => $time,
'updated_at' => $time 'updated_at' => $time
]; ];
\Yii::$app->db->createCommand()->batchInsert(Ledger::tableName(), [ \Yii::$app->db->createCommand()->batchInsert(Ledger::tableName(), [
'order_id', 'user_id', 'user_type', 'order_type', 'fee_type', 'su_id', 'drugstore_id', 'order_id', 'user_id', 'user_type', 'order_type', 'fee_type', 'su_id', 'drugstore_id',
'drug_id','xd_time', 'number', 'money', 'status', 'created_at', 'updated_at' 'drug_id','xd_time', 'number', 'money', 'status', 'created_at', 'updated_at'
@@ -678,26 +660,26 @@ class LedgerForm extends BaseModel
$store = Store::findOne(['id' => $Register->store_id]); $store = Store::findOne(['id' => $Register->store_id]);
if(!$store){ if(!$store){
throw new Exception('门店不存在'); throw new Exception('门店不存在');
} }
$time = time(); $time = time();
$t = \Yii::$app->db->beginTransaction(); $t = \Yii::$app->db->beginTransaction();
$model = new LedgerLog(); $model = new LedgerLog();
try { try {
switch ($this->status) { switch ($this->status) {
case 1: // 已结算 case 1: // 已结算
//更新挂号订单为已结算 //更新挂号订单为已结算
$Register->is_settled = 1; $Register->is_settled = 1;
$Register->created_at = strtotime($Register->created_at); $Register->created_at = strtotime($Register->created_at);
$Register->updated_at = $time; $Register->updated_at = $time;
$Register->saveOrFail(); $Register->saveOrFail();
//分账表批量更新状态为已结算 //分账表批量更新状态为已结算
Ledger::updateAll(['status' => 1, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 2]); //1产品订单 2挂号订单 Ledger::updateAll(['status' => 1, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 2]); //1产品订单 2挂号订单
/******************************************** 门店 ********************************************** */ /******************************************** 门店 ********************************************** */
$storeTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_id' => $store->id, 'user_type' => 1, 'order_type' => 2, 'fee_type' => 2])->sum('money'); // 该订单门店分佣总金额 $storeTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_id' => $store->id, 'user_type' => 1, 'order_type' => 2, 'fee_type' => 2])->sum('money'); // 该订单门店分佣总金额
$storeTotal = round($storeTotal, 2);//4舍5入 $storeTotal = round($storeTotal, 2);//4舍5入
//增加门店分佣 //增加门店分佣
$log = clone $model; $log = clone $model;
$log->order_id = $this->order_id; $log->order_id = $this->order_id;
@@ -713,8 +695,13 @@ class LedgerForm extends BaseModel
$log->saveOrFail(); $log->saveOrFail();
//门店可提现及累计金额更新 //门店可提现及累计金额更新
CashAccount::updateAllCounters(['able_cash' => $storeTotal, 'total_cash' => $storeTotal],['user_type' => 1, 'user_id' => $store->id]); //门店 $this->applyCashAccountDeltaWithLog((int)$store->id, 1, $storeTotal, 'settle', [
'order_id' => (int)$this->order_id,
'order_type' => 2,
'order_no' => (string)($Register->order_no ?? ''),
'remark' => '挂号订单分账结算-门店',
]);
break; break;
case 2://已取消 case 2://已取消
if($Register->is_settled == 1){ //已结算回退 if($Register->is_settled == 1){ //已结算回退
@@ -722,7 +709,7 @@ class LedgerForm extends BaseModel
Reconciliation::updateAll(['status' => -1], ['order_id' => $this->order_id]); Reconciliation::updateAll(['status' => -1], ['order_id' => $this->order_id]);
//分账表批量更新状态为已取消 //分账表批量更新状态为已取消
Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]);//1产品订单 2挂号订单 Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]);//1产品订单 2挂号订单
$ledgerLog = LedgerLog::find()->where(['order_id' => $this->order_id])->asArray()->all(); $ledgerLog = LedgerLog::find()->where(['order_id' => $this->order_id])->asArray()->all();
foreach($ledgerLog as $v){ foreach($ledgerLog as $v){
$log = clone $model; $log = clone $model;
@@ -737,9 +724,19 @@ class LedgerForm extends BaseModel
$log->created_at = $time; $log->created_at = $time;
$log->updated_at = $time; $log->updated_at = $time;
$log->saveOrFail(); $log->saveOrFail();
//可提现及累计金额更新 //可提现及累计金额更新
CashAccount::updateAllCounters(['able_cash' => $v['amount'] * -1, 'total_cash' => $v['amount'] * -1],['user_type' => $v['user_type'], 'user_id' => $v['user_id'], 'order_type' => $v['order_type'], 'fee_type' => $v['fee_type']]); $this->applyCashAccountDeltaWithLog(
(int)$v['user_id'],
(int)$v['user_type'],
(float)$v['amount'] * -1,
'refund',
[
'order_id' => (int)$v['order_id'],
'order_type' => (int)$v['order_type'],
'remark' => '订单退款扣减账户余额',
]
);
} }
} else { // 未结算 } else { // 未结算
Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 2]); Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 2]);
@@ -757,7 +754,7 @@ class LedgerForm extends BaseModel
throw $e; throw $e;
} }
break; break;
default: //产品订单 default: //产品订单
ProductOrderLog::saveLog($this->order_id, '产品订单结算更新开始'); ProductOrderLog::saveLog($this->order_id, '产品订单结算更新开始');
$productOrder = ProductOrder::find()->where(['id' => $this->order_id])->one(); $productOrder = ProductOrder::find()->where(['id' => $this->order_id])->one();
@@ -767,17 +764,17 @@ class LedgerForm extends BaseModel
$store = Store::findOne(['id' => $productOrder->store_id]); $store = Store::findOne(['id' => $productOrder->store_id]);
if(!$store){ if(!$store){
throw new Exception('门店不存在'); throw new Exception('门店不存在');
} }
$time = time(); $time = time();
$t = \Yii::$app->db->beginTransaction(); $t = \Yii::$app->db->beginTransaction();
$model = new LedgerLog(); $model = new LedgerLog();
try { try {
switch ($this->status) { switch ($this->status) {
case 1: // 已结算 case 1: // 已结算
//更新产品订单为已结算 //更新产品订单为已结算
$productOrder->is_settled = 1; $productOrder->is_settled = 1;
$productOrder->saveOrFail(); $productOrder->saveOrFail();
$productOrderItems = ProductOrderItems::find()->with(['drug.supplier'])->where(['product_order_id' => $productOrder->id])->asArray()->all(); $productOrderItems = ProductOrderItems::find()->with(['drug.supplier'])->where(['product_order_id' => $productOrder->id])->asArray()->all();
$Reconciliation = new Reconciliation(); $Reconciliation = new Reconciliation();
foreach($productOrderItems as $v){ foreach($productOrderItems as $v){
@@ -834,12 +831,12 @@ class LedgerForm extends BaseModel
]); ]);
} }
} }
//分账表批量更新状态为已结算 //分账表批量更新状态为已结算
Ledger::updateAll(['status' => 1, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]); //1产品订单 2挂号订单 Ledger::updateAll(['status' => 1, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]); //1产品订单 2挂号订单
/******************************************** 平台 ********************************************** */ /******************************************** 平台 ********************************************** */
$platformDrugTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_type' => 2, 'order_type' => 1, 'fee_type' => 1])->sum('money'); // 该订单平台分佣总金额 $platformDrugTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_type' => 2, 'order_type' => 1, 'fee_type' => 1])->sum('money'); // 该订单平台分佣总金额
//增加药品分佣 //增加药品分佣
$log = clone $model; $log = clone $model;
$log->order_id = $this->order_id; $log->order_id = $this->order_id;
@@ -911,13 +908,18 @@ class LedgerForm extends BaseModel
$money1 = bcadd($platformDrugTotal, $platformProcessTotal, 2); $money1 = bcadd($platformDrugTotal, $platformProcessTotal, 2);
$money2 = bcadd($platformDeliveryTotal, $platformDecoctTotal, 2); $money2 = bcadd($platformDeliveryTotal, $platformDecoctTotal, 2);
$platformTotal = round(bcadd($money1, $money2, 2), 2); //该订单平台分佣总金额 $platformTotal = round(bcadd($money1, $money2, 2), 2); //该订单平台分佣总金额
//可提现金额表更新 //门店可提现及累计金额更新
CashAccount::updateAllCounters(['able_cash' => $platformTotal, 'total_cash' => $platformTotal],['user_type' => 2]); //平台 $this->applyCashAccountDeltaWithLog(0, 2, $platformTotal, 'settle', [
'order_id' => (int)$this->order_id,
'order_type' => 1,
'order_no' => (string)($productOrder->order_no ?? ''),
'remark' => '产品订单分账结算-平台',
]);
/******************************************** 门店 ********************************************** */ /******************************************** 门店 ********************************************** */
$storeTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_id' => $store->id, 'user_type' => 1, 'order_type' => 1, 'fee_type' => 1])->sum('money'); // 该订单门店分佣总金额 $storeTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_id' => $store->id, 'user_type' => 1, 'order_type' => 1, 'fee_type' => 1])->sum('money'); // 该订单门店分佣总金额
$storeTotal = round($storeTotal, 2);//4舍5入 $storeTotal = round($storeTotal, 2);//4舍5入
//增加门店分佣 //增加门店分佣
$log = clone $model; $log = clone $model;
$log->order_id = $this->order_id; $log->order_id = $this->order_id;
@@ -934,7 +936,8 @@ class LedgerForm extends BaseModel
//增加诊疗费 //增加诊疗费
if($productOrder->treatement_price > 0){ if($productOrder->treatement_price > 0){
$platformTreatementTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_type' => 2, 'order_type' => 1, 'fee_type' => 6])->sum('money'); // 该订单诊疗费用 // $platformTreatementTotal = Ledger::find()->where(['order_id' => $this->order_id, 'user_type' => 1, 'order_type' => 1, 'fee_type' => 6])->sum('money'); // 该订单诊疗费用
$platformTreatementTotal = Ledger::find()->where(['order_id' => $this->order_id, 'order_type' => 1, 'fee_type' => 6])->sum('money'); // 该订单诊疗费用
$logTreatement = clone $model; $logTreatement = clone $model;
$logTreatement->order_id = $this->order_id; $logTreatement->order_id = $this->order_id;
$logTreatement->user_id = $store->id; $logTreatement->user_id = $store->id;
@@ -949,9 +952,14 @@ class LedgerForm extends BaseModel
$logTreatement->saveOrFail(); $logTreatement->saveOrFail();
} }
//门店可提现及累计金额更新 //门店可提现及累计金额更新
CashAccount::updateAllCounters(['able_cash' => $storeTotal, 'total_cash' => $storeTotal],['user_type' => 1, 'user_id' => $store->id]); //门店 $this->applyCashAccountDeltaWithLog((int)$store->id, 1, $storeTotal, 'settle', [
'order_id' => (int)$this->order_id,
'order_type' => 1,
'order_no' => (string)($productOrder->order_no ?? ''),
'remark' => '产品订单分账结算-门店',
]);
break; break;
case 2://已取消 case 2://已取消
if($productOrder->is_settled == 1){ //已结算回退 if($productOrder->is_settled == 1){ //已结算回退
@@ -959,7 +967,7 @@ class LedgerForm extends BaseModel
Reconciliation::updateAll(['status' => -1], ['order_id' => $this->order_id]); Reconciliation::updateAll(['status' => -1], ['order_id' => $this->order_id]);
//分账表批量更新状态为已取消 //分账表批量更新状态为已取消
Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]);//1产品订单 2挂号订单 Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 1]);//1产品订单 2挂号订单
$ledgerLog = LedgerLog::find()->where(['order_id' => $this->order_id])->asArray()->all(); $ledgerLog = LedgerLog::find()->where(['order_id' => $this->order_id])->asArray()->all();
foreach($ledgerLog as $v){ foreach($ledgerLog as $v){
if ($v['user_type'] === 3) { if ($v['user_type'] === 3) {
@@ -979,13 +987,16 @@ class LedgerForm extends BaseModel
$log->saveOrFail(); $log->saveOrFail();
//供应商冻结金额及累计金额更新 //供应商冻结金额及累计金额更新
AccountBalanceModel::updateAllCounters([ $this->applySupplierBalanceDeltaWithLog(
// 'total' => bcmul($v['amount'], -1, 6), (int)$v['user_id'],
'balance' => bcmul($v['amount'], -1, 6), (float)bcmul($v['amount'], -1, 6),
], [ 'refund',
'user_id' => $v['user_id'], [
'type' => 3 'order_id' => (int)$v['order_id'],
]); 'order_type' => (int)$v['order_type'],
'remark' => '订单退款扣减供应商余额',
]
);
} else { } else {
$log = clone $model; $log = clone $model;
$log->order_id = $v['order_id']; $log->order_id = $v['order_id'];
@@ -1001,7 +1012,17 @@ class LedgerForm extends BaseModel
$log->saveOrFail(); $log->saveOrFail();
//可提现及累计金额更新 //可提现及累计金额更新
CashAccount::updateAllCounters(['able_cash' => $v['amount'] * -1, 'total_cash' => $v['amount'] * -1],['user_type' => $v['user_type'], 'user_id' => $v['user_id']]); $this->applyCashAccountDeltaWithLog(
(int)$v['user_id'],
(int)$v['user_type'],
(float)$v['amount'] * -1,
'refund',
[
'order_id' => (int)$v['order_id'],
'order_type' => (int)$v['order_type'],
'remark' => '产品订单退款扣减账户余额',
]
);
} }
} }
} else { // 未结算 } else { // 未结算
@@ -1020,7 +1041,47 @@ class LedgerForm extends BaseModel
throw $e; throw $e;
} }
break; break;
} }
}
private function applyCashAccountDeltaWithLog(int $userId, int $userType, $delta, string $sourceType, array $extra = []): void
{
$account = CashAccount::findOne(['user_type' => $userType, 'user_id' => $userId]);
$before = $account ? $account->able_cash : 0;
CashAccount::updateAllCounters(
['able_cash' => $delta, 'total_cash' => $delta],
['user_type' => $userType, 'user_id' => $userId]
);
$account = CashAccount::findOne(['user_type' => $userType, 'user_id' => $userId]);
$after = $account ? $account->able_cash : bcadd((string)$before, (string)$delta, 2);
AccountAbleChangeLogService::logCashAccountAbleChange(
$userId,
$userType,
$before,
$after,
$sourceType,
'yii_ledger_log',
(int)($extra['source_id'] ?? 0),
$extra
);
}
private function applySupplierBalanceDeltaWithLog(int $userId, $delta, string $sourceType, array $extra = []): void
{
$account = AccountBalanceModel::findOne(['user_id' => $userId, 'type' => 3]);
$before = $account ? $account->balance : 0;
AccountBalanceModel::updateAllCounters(['balance' => $delta], ['user_id' => $userId, 'type' => 3]);
$account = AccountBalanceModel::findOne(['user_id' => $userId, 'type' => 3]);
$after = $account ? $account->balance : bcadd((string)$before, (string)$delta, 6);
AccountAbleChangeLogService::logSupplierBalanceChange(
$userId,
$before,
$after,
$sourceType,
'yii_ledger_log',
(int)($extra['source_id'] ?? 0),
$extra
);
} }
} }

View File

@@ -32,6 +32,30 @@ class PrescriptionCreated extends BaseJob implements JobInterface
throw new Exception('处方不存在或已取消'); throw new Exception('处方不存在或已取消');
} }
PrescriptionLog::saveLog($this->orderId,'处方订单生成通知用户支付订阅消息发送队列 load');
PrescriptionLog::saveLog($this->orderId,json_encode([
'touser' => $Prescription->user->openid,
'template_id' => \Yii::$app->params['template']['user']['prescription_created'],
'page' => 'subPackages/my/myrecord-detail?id='.$Prescription->id.'&no='.$Prescription->prescription_no,
'data' => [
'name1' => [
'value' => $Prescription->userPatient->name,
],
'thing2' => [
'value' => $Prescription->clinical_diagnose,
],
'name4' => [
'value' => $Prescription->doctorInfo->name,
],
'time9' => [
'value' => date('Y-m-d H:i:s',$Prescription->created_at),
],
'thing11' => [
'value' => '医生已为您开具处方,请尽快前往支付!',
]
]
]));
PrescriptionLog::saveLog($this->orderId,'处方订单生成通知用户支付订阅消息发送队列 load end');
$result = WechatService::getInstance()->app->subscribe_message->send([ $result = WechatService::getInstance()->app->subscribe_message->send([
'touser' => $Prescription->user->openid, 'touser' => $Prescription->user->openid,
'template_id' => \Yii::$app->params['template']['user']['prescription_created'], 'template_id' => \Yii::$app->params['template']['user']['prescription_created'],

View File

@@ -0,0 +1,11 @@
<?php
namespace common\models\newDb;
class AccountAbleChangeLogModel extends \common\core\BaseNewActiveRecord
{
public static function tableName()
{
return 'xk_account_able_change_log';
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace common\models\newDb;
class ClinicSalespersonModel extends \common\core\BaseNewActiveRecord
{
public static function tableName()
{
return 'xk_clinic_salesperson';
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace common\models\newDb;
/**
* 配送仓库主体(新库)
* 供会员端订单详情回填仓名使用
*/
class DeliveryWarehouseModel extends \common\core\BaseNewActiveRecord
{
public static function tableName()
{
return 'xk_delivery_warehouse';
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace common\models\newDb;
class SalespersonQrCodeModel extends \common\core\BaseNewActiveRecord
{
public static function tableName()
{
return 'xk_salesperson_qr_code';
}
public function getClinicSalesperson()
{
return $this->hasOne(ClinicSalespersonModel::class, ['id' => 'salesperson_id']);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace common\models\newDb;
class UserSalespersonModel extends \common\core\BaseNewActiveRecord
{
public static function tableName()
{
return 'xk_user_salesperson';
}
public function getClinicSalesperson()
{
return $this->hasOne(ClinicSalespersonModel::class, ['id' => 'salesperson_id']);
}
}

View File

@@ -32,6 +32,7 @@ namespace common\modelsgii\oldDb;
* @property string|null $drug_alias 药品别名 * @property string|null $drug_alias 药品别名
* @property string|null $place 产地 * @property string|null $place 产地
* @property int $decotion 煎法 * @property int $decotion 煎法
* @property float $erp_qty_factor ERP抓取数量倍数,默认1
* @property int $updated_at * @property int $updated_at
* @property int $created_at * @property int $created_at
*/ */

View File

@@ -18,8 +18,9 @@ class ProductOrderItems extends \common\core\BaseActiveRecord
public function rules() public function rules()
{ {
return [ return [
[['product_order_id', 'drug_id'], 'integer'], [['product_order_id', 'drug_id', 'dosage', 'number', 'type'], 'integer'],
[['drug_image', 'drug_name', 'small_info', 'created_at', 'updated_at'], 'string'], [['buy_price', 'price'], 'number'],
[['drug_image', 'drug_name', 'small_info', 'drug_no', 'function', 'created_at', 'updated_at'], 'string'],
]; ];
} }

View File

@@ -10,6 +10,7 @@ namespace common\modelsgii\oldDb;
* @property int $service_user_id 医生id * @property int $service_user_id 医生id
* @property int $user_patient_id 就诊人id * @property int $user_patient_id 就诊人id
* @property int $store_id 诊所id * @property int $store_id 诊所id
* @property int $origin_store_id 发起委托方诊所/药店ID(药价)
* @property string $order_no 订单号 * @property string $order_no 订单号
* @property int $depart_id * @property int $depart_id
* @property int $order_number 挂号序号 * @property int $order_number 挂号序号
@@ -44,7 +45,7 @@ class Register extends \common\core\BaseActiveRecord
{ {
return [ return [
[['user_id', 'service_user_id', 'user_patient_id', 'store_id', 'order_no', 'depart_id', 'order_number'], 'required'], [['user_id', 'service_user_id', 'user_patient_id', 'store_id', 'order_no', 'depart_id', 'order_number'], 'required'],
[['user_id', 'service_user_id', 'user_patient_id', 'store_id', 'depart_id', 'order_number', 'is_pay', 'status', 'pay_type', 'pay_time', 'is_cancel', 'cancel_time', 'refund_status', 'refund_time', 'created_at', 'updated_at', 'is_delete'], 'integer'], [['user_id', 'service_user_id', 'user_patient_id', 'store_id', 'origin_store_id', 'depart_id', 'order_number', 'is_pay', 'status', 'pay_type', 'pay_time', 'is_cancel', 'cancel_time', 'refund_status', 'refund_time', 'created_at', 'updated_at', 'is_delete'], 'integer'],
[['price'], 'number'], [['price'], 'number'],
[['order_no', 'refuse_reason'], 'string', 'max' => 255], [['order_no', 'refuse_reason'], 'string', 'max' => 255],
]; ];
@@ -61,6 +62,7 @@ class Register extends \common\core\BaseActiveRecord
'service_user_id' => 'Service User ID', 'service_user_id' => 'Service User ID',
'user_patient_id' => 'User Patient ID', 'user_patient_id' => 'User Patient ID',
'store_id' => 'Store ID', 'store_id' => 'Store ID',
'origin_store_id' => 'Origin Store ID',
'order_no' => 'Order No', 'order_no' => 'Order No',
'depart_id' => 'Depart ID', 'depart_id' => 'Depart ID',
'order_number' => 'Order Number', 'order_number' => 'Order Number',

View File

@@ -0,0 +1,101 @@
<?php
namespace common\services;
use common\models\newDb\AccountAbleChangeLogModel;
use Yii;
class AccountAbleChangeLogService
{
public const ACCOUNT_TABLE_CASH = 'yii_cash_account';
public const ACCOUNT_TABLE_BALANCE = 'xk_account_balance';
public const FIELD_ABLE_CASH = 'able_cash';
public const FIELD_BALANCE = 'balance';
public static function recordWithdrawableChange(
int $userId,
int $userType,
string $accountTable,
string $fieldName,
$before,
$after,
string $sourceType,
string $sourceTable,
int $sourceId = 0,
array $extra = []
): void {
$change = bcsub((string)$after, (string)$before, 6);
if (bccomp($change, '0', 6) === 0) {
return;
}
$time = time();
$model = new AccountAbleChangeLogModel();
$model->user_id = $userId;
$model->user_type = $userType;
$model->account_table = $accountTable;
$model->field_name = $fieldName;
$model->before_amount = $before;
$model->after_amount = $after;
$model->change_amount = $change;
$model->source_type = $sourceType;
$model->source_table = $sourceTable;
$model->source_id = $sourceId;
$model->order_id = (int)($extra['order_id'] ?? 0);
$model->order_type = (int)($extra['order_type'] ?? 0);
$model->order_no = (string)($extra['order_no'] ?? '');
$model->remark = (string)($extra['remark'] ?? '');
$model->created_at = $time;
$model->updated_at = $time;
if (!$model->save(false)) {
Yii::warning('写入 xk_account_able_change_log 失败', __METHOD__);
}
}
public static function logCashAccountAbleChange(
int $userId,
int $userType,
$before,
$after,
string $sourceType,
string $sourceTable,
int $sourceId = 0,
array $extra = []
): void {
self::recordWithdrawableChange(
$userId,
$userType,
self::ACCOUNT_TABLE_CASH,
self::FIELD_ABLE_CASH,
$before,
$after,
$sourceType,
$sourceTable,
$sourceId,
$extra
);
}
public static function logSupplierBalanceChange(
int $userId,
$before,
$after,
string $sourceType,
string $sourceTable,
int $sourceId = 0,
array $extra = []
): void {
self::recordWithdrawableChange(
$userId,
3,
self::ACCOUNT_TABLE_BALANCE,
self::FIELD_BALANCE,
$before,
$after,
$sourceType,
$sourceTable,
$sourceId,
$extra
);
}
}

View File

@@ -12,6 +12,7 @@ use common\models\oldDb\ProductOrder;
use common\models\oldDb\Store; use common\models\oldDb\Store;
use common\modelsgii\oldDb\DoctorIdentity; use common\modelsgii\oldDb\DoctorIdentity;
use Exception; use Exception;
use Yii;
use yii\helpers\Json; use yii\helpers\Json;
class PrescriptionService{ class PrescriptionService{
@@ -26,11 +27,11 @@ class PrescriptionService{
} }
if($prescriptionNo){ if($prescriptionNo){
$prescription = Prescription::find()->select('id,store_id,prescription_no,online_prescription_no,is_online,prescription_type,type,is_dispense,valid_hours,content,doctor_order,status,pharmacist_id,su_id,process_rule_id,process_rule,process_rule_note,doctor_second_sign')->where([ $prescription = Prescription::find()->select('id,store_id,prescription_no,online_prescription_no,is_online,prescription_type,type,is_dispense,valid_hours,content,doctor_order,status,pharmacist_id,su_id,process_rule_id,process_rule,process_rule_note,doctor_second_sign,created_at')->where([
'prescription_no' => $prescriptionNo 'prescription_no' => $prescriptionNo
])->with('pharmacistInfo')->asArray()->one(); ])->with('pharmacistInfo')->asArray()->one();
} else { } else {
$prescription = Prescription::find()->select('id,store_id,prescription_no,online_prescription_no,is_online,prescription_type,type,is_dispense,valid_hours,content,doctor_order,status,pharmacist_id,su_id,process_rule_id,process_rule,process_rule_note,doctor_second_sign')->where([ $prescription = Prescription::find()->select('id,store_id,prescription_no,online_prescription_no,is_online,prescription_type,type,is_dispense,valid_hours,content,doctor_order,status,pharmacist_id,su_id,process_rule_id,process_rule,process_rule_note,doctor_second_sign,created_at')->where([
'id' => $presciptionId 'id' => $presciptionId
])->with('pharmacistInfo')->asArray()->one(); ])->with('pharmacistInfo')->asArray()->one();
} }
@@ -59,10 +60,97 @@ class PrescriptionService{
$prescription['Pharmacist_sign_image']=$PharmacistIdentity['sign_image']?? ''; $prescription['Pharmacist_sign_image']=$PharmacistIdentity['sign_image']?? '';
$prescription['Pharmacist_sign_type']=$PharmacistIdentity['sign_type']?? ''; $prescription['Pharmacist_sign_type']=$PharmacistIdentity['sign_type']?? '';
$prescription['online_tcm_print'] = $this->buildOnlineTcmPrint($prescription);
return $prescription; return $prescription;
} catch (Exception $e) { } catch (Exception $e) {
throw new Exception($e->getMessage(). json_encode($e->getLine())); throw new Exception($e->getMessage(). json_encode($e->getLine()));
} }
} }
} /**
* 在线中药处方笺:监管中医术语展示(与 xk-api online_tcm_print 一致)
*
* @param array<string, mixed> $prescription
* @return array<string, mixed>
*/
private function buildOnlineTcmPrint(array $prescription): array
{
$ptype = (int) ($prescription['prescription_type'] ?? 0);
$isOnline = (int) ($prescription['is_online'] ?? 0);
if ($ptype !== 1 || !in_array($isOnline, [1, 2, 3], true)) {
return ['show' => false];
}
$prescriptionId = (int) ($prescription['id'] ?? 0);
if ($prescriptionId <= 0) {
return ['show' => false];
}
try {
$syndrome = $this->fetchTcmTermNames(
'prescription_disease',
'disease_id',
'traditional_chinese_medicine_diseases',
$prescriptionId
);
$method = $this->fetchTcmTermNames(
'prescription_method',
'method_id',
'traditional_chinese_medicine_method',
$prescriptionId
);
$disease = $this->fetchTcmTermNames(
'prescription_syndrome',
'syndrome_id',
'traditional_chinese_medicine_syndrome',
$prescriptionId
);
if ($syndrome === '' && $method === '' && $disease === '') {
return ['show' => false, 'a' => 1];
}
$result = ['show' => true];
if ($syndrome !== '') {
$result['tcm_syndrome'] = $syndrome;
}
if ($method !== '') {
$result['tcm_method'] = $method;
}
if ($disease !== '') {
$result['tcm_disease'] = $disease;
}
return $result;
} catch (\Throwable $e) {
Yii::warning('online_tcm_print query failed: '.$e->getMessage(), __METHOD__);
return ['show' => false, 'a' => $e->getMessage()];
}
}
private function fetchTcmTermNames(
string $linkTable,
string $linkColumn,
string $termTable,
int $prescriptionId
): string {
if (! Yii::$app->has('new_db')) {
return '';
}
$db = Yii::$app->new_db;
$rows = $db->createCommand(
"SELECT t.name FROM {{%{$linkTable}}} l
INNER JOIN {{%{$termTable}}} t ON t.id = l.{$linkColumn}
WHERE l.prescription_id = :pid",
[':pid' => $prescriptionId]
)->queryColumn();
$names = array_filter(array_map('trim', $rows));
return implode('、', $names);
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace common\services;
use common\models\newDb\ClinicSalespersonModel;
use common\models\newDb\SalespersonQrCodeModel;
use common\models\newDb\UserSalespersonModel;
use Yii;
/**
* 推广员与订单/挂号绑定解析(与 Laravel SalespersonOrderBindService 规则一致)。
*/
class SalespersonOrderBindService
{
/**
* @return array{salesperson_id: int, user_salesperson_id: int}
*/
public function resolveForOrder(int $userId, int $storeId, int $orderCreatedAt): array
{
$empty = ['salesperson_id' => 0, 'user_salesperson_id' => 0];
if ($userId <= 0 || $storeId <= 0 || !Yii::$app->has('new_db')) {
return $empty;
}
$bind = UserSalespersonModel::find()
->where(['user_id' => $userId, 'status' => 0])
->orderBy(['id' => SORT_DESC])
->one();
if (!$bind) {
return $empty;
}
$salespersonId = (int) ($bind->salesperson_id ?? 0);

View File

@@ -96,6 +96,21 @@ class LoginForm extends BaseModel
'user_id' => $user->id, 'user_id' => $user->id,
'store_id' => Yii::$app->store, 'store_id' => Yii::$app->store,
])->one(); ])->one();
$storeUserJl = StoreUser::find()->where([
'user_id' => $user->id,
'store_id' => 11001,
])->one();
if (!$storeUserJl) {
//用户关联门店
$StoreUser = new StoreUser();
$StoreUser->store_id = 11001;
$StoreUser->user_id = $user->id;
$StoreUser->is_online = 0;
$StoreUser->last_login_time = time();
$StoreUser->saveOrFail();
}
if (!$storeUser) { if (!$storeUser) {
//用户关联门店 //用户关联门店
@@ -178,6 +193,19 @@ class LoginForm extends BaseModel
'is_delete' => 0 'is_delete' => 0
]); ]);
} }
$storeUserJl = StoreUser::find()->where([
'user_id' => $user->id,
'store_id' => 11001,
])->one();
if (!$storeUserJl) {
//用户关联门店
$StoreUser = new StoreUser();
$StoreUser->store_id = 11001;
$StoreUser->user_id = $user->id;
$StoreUser->is_online = 0;
$StoreUser->last_login_time = time();
$StoreUser->saveOrFail();
}
$transaction->commit(); $transaction->commit();
} catch (Exception $exception) { } catch (Exception $exception) {

View File

@@ -15,6 +15,7 @@ use common\models\oldDb\Store;
use common\models\oldDb\StoreDoctor; use common\models\oldDb\StoreDoctor;
use common\models\oldDb\UserPatient; use common\models\oldDb\UserPatient;
use common\modelsgii\oldDb\PayConfig; use common\modelsgii\oldDb\PayConfig;
use common\services\SalespersonOrderBindService;
use yii\db\Exception; use yii\db\Exception;
//挂号form //挂号form
@@ -26,11 +27,12 @@ class RegisterForm extends BaseModel
public $service_user_id; public $service_user_id;
public $register_id; public $register_id;
public $register_type; public $register_type;
public $origin_store_id;
public function rules() public function rules()
{ {
return [ return [
[['store_id', 'user_id','register_id'], 'integer'], [['store_id', 'user_id', 'register_id', 'origin_store_id'], 'integer'],
[['user_patient_id', 'service_user_id', 'register_type'], 'required'] [['user_patient_id', 'service_user_id', 'register_type'], 'required']
]; ];
} }
@@ -117,26 +119,36 @@ class RegisterForm extends BaseModel
$t = \Yii::$app->db->beginTransaction(); $t = \Yii::$app->db->beginTransaction();
try { try {
// 确定实际使用的门店ID // 确定实际使用的门店ID(履约诊所)
// 如果是购药(register_type=3)且当前门店(药店)配置了委托诊所,则使用委托诊所ID // 在线场景:有委托诊所配置时服务端强制写成委托诊所;发起方写入 origin_store_id
// 如果是诊所在线复诊(register_type=2),需要确保是诊所(store.type=0) $actualStoreId = (int) ($this->store_id ?: \Yii::$app->store);
$actualStoreId = \Yii::$app->store; if (in_array((int) $this->register_type, [2, 3], true)) {
if ($this->register_type == 3) { $currentStore = Store::findOne(\Yii::$app->store);
$currentStore = Store::findOne($actualStoreId); if ($this->register_type == 2) {
// 诊所在线复诊:发起方诊所校验(会话门店须为诊所)
if ($currentStore && $currentStore->type != 0) {
throw new Exception('诊所在线复诊只能在诊所进行');
}
}
// type=2/3:配置了委托诊所则履约店强制为委托诊所(不单靠前端传参)
if ($currentStore && !empty($currentStore->delegate_store_id)) { if ($currentStore && !empty($currentStore->delegate_store_id)) {
$actualStoreId = $currentStore->delegate_store_id; $actualStoreId = (int) $currentStore->delegate_store_id;
}
} elseif ($this->register_type == 2) {
// 诊所在线复诊:确保是诊所(store.type=0)
$currentStore = Store::findOne($actualStoreId);
if ($currentStore && $currentStore->type != 0) {
throw new Exception('诊所在线复诊只能在诊所进行');
} }
} }
$originStoreId = (int) ($this->origin_store_id ?: \Yii::$app->store);
$shouldPersistOrigin = in_array((int) $this->register_type, [2, 3], true)
|| ((int) $this->register_type === 1 && (int) $this->origin_store_id > 0);
if (!$shouldPersistOrigin) {
$originStoreId = 0;
}
$UserRegister = new Register(); $UserRegister = new Register();
$UserRegister->user_id = \Yii::$app->user->id; $UserRegister->user_id = \Yii::$app->user->id;
$UserRegister->store_id = $actualStoreId; $UserRegister->store_id = $actualStoreId;
if ($UserRegister->hasAttribute('origin_store_id')) {
$UserRegister->origin_store_id = $originStoreId;
}
$UserRegister->order_no = FuncHelper::generate_order_no('SN'); $UserRegister->order_no = FuncHelper::generate_order_no('SN');
$UserRegister->user_patient_id = $this->user_patient_id; $UserRegister->user_patient_id = $this->user_patient_id;
$UserRegister->service_user_id = $this->service_user_id; $UserRegister->service_user_id = $this->service_user_id;
@@ -145,6 +157,14 @@ class RegisterForm extends BaseModel
$UserRegister->order_number = ($order_number['order_number']??0 ) + 1; $UserRegister->order_number = ($order_number['order_number']??0 ) + 1;
$UserRegister->price = $ServiceUser->docService->register_price; $UserRegister->price = $ServiceUser->docService->register_price;
$UserRegister->pay_type = $payConfig->pay_type??2;//1微信 2易票联 $UserRegister->pay_type = $payConfig->pay_type??2;//1微信 2易票联
if ($UserRegister->hasAttribute('salesperson_id')) {
$bindResult = (new SalespersonOrderBindService())->resolveForOrder(
(int) \Yii::$app->user->id,
$actualStoreId,
time()
);
$UserRegister->salesperson_id = (int) ($bindResult['salesperson_id'] ?? 0);
}
$UserRegister->saveOrFail(); $UserRegister->saveOrFail();
$event = new RegisterEvent();//触发订单创建事件 $event = new RegisterEvent();//触发订单创建事件

View File

@@ -85,6 +85,8 @@ class DoctorController extends BaseAppController
$query->joinWith(['docInfo' => function ($q) use ($id, $keyword, $depart_arr, $title_arr) { $query->joinWith(['docInfo' => function ($q) use ($id, $keyword, $depart_arr, $title_arr) {
$q->alias('i'); $q->alias('i');
// 患者端列表不展示测试医生
$q->andWhere(['i.is_test' => 0]);
//搜索框搜索姓名和科室 //搜索框搜索姓名和科室
if (!empty($keyword)) { if (!empty($keyword)) {
$q->andWhere([ $q->andWhere([

View File

@@ -13,6 +13,7 @@ use common\models\oldDb\CashAccount;
use common\models\oldDb\CashApply; use common\models\oldDb\CashApply;
use common\models\oldDb\ChargeCashPayRecord; use common\models\oldDb\ChargeCashPayRecord;
use common\models\oldDb\FundWater; use common\models\oldDb\FundWater;
use common\services\AccountAbleChangeLogService;
use common\models\oldDb\PaymentProductOrder; use common\models\oldDb\PaymentProductOrder;
use common\models\oldDb\PaymentProductRefund; use common\models\oldDb\PaymentProductRefund;
use common\models\oldDb\PaymentRegister; use common\models\oldDb\PaymentRegister;
@@ -309,13 +310,35 @@ class EplpayCallbackController extends \yii\web\Controller
$applyOrder->saveOrFail(); $applyOrder->saveOrFail();
if ($applyOrder->user_type === 3) { if ($applyOrder->user_type === 3) {
$before = $CashAccount->balance;
$CashAccount->balance = bcadd($CashAccount->balance, $applyOrder->apply_cash, 6); $CashAccount->balance = bcadd($CashAccount->balance, $applyOrder->apply_cash, 6);
$CashAccount->withdrawn_frozen = bcsub($CashAccount->withdrawn_frozen, $applyOrder->apply_cash, 6); $CashAccount->withdrawn_frozen = bcsub($CashAccount->withdrawn_frozen, $applyOrder->apply_cash, 6);
$CashAccount->saveOrFail();
AccountAbleChangeLogService::logSupplierBalanceChange(
(int)$applyOrder->user_id,
$before,
$CashAccount->balance,
'withdraw',
'yii_cash_apply',
(int)$applyOrder->id,
['order_no' => (string)$applyOrder->order_no, 'remark' => '提现回调失败回退可提现余额']
);
} else { } else {
$before = $CashAccount->able_cash;
$CashAccount->able_cash = $CashAccount->able_cash + $applyOrder->apply_cash; $CashAccount->able_cash = $CashAccount->able_cash + $applyOrder->apply_cash;
$CashAccount->frozen_cash -= $applyOrder->apply_cash; $CashAccount->frozen_cash -= $applyOrder->apply_cash;
$CashAccount->saveOrFail();
AccountAbleChangeLogService::logCashAccountAbleChange(
(int)$applyOrder->user_id,
(int)$applyOrder->user_type,
$before,
$CashAccount->able_cash,
'withdraw',
'yii_cash_apply',
(int)$applyOrder->id,
['order_no' => (string)$applyOrder->order_no, 'remark' => '提现回调失败回退可提现金额']
);
} }
$CashAccount->saveOrFail();
} else { } else {
// 获取代扣订单 // 获取代扣订单
$chargeCpr = ChargeCashPayRecord::find()->where([ $chargeCpr = ChargeCashPayRecord::find()->where([

View File

@@ -10,6 +10,7 @@ use common\forms\ProductRefundForm;
use common\jobs\ProductOrderSyncPlatformJob; use common\jobs\ProductOrderSyncPlatformJob;
use common\models\oldDb\Address; use common\models\oldDb\Address;
use common\models\oldDb\ChineseRepice; use common\models\oldDb\ChineseRepice;
use common\models\oldDb\Drug;
use common\models\oldDb\DoctorInfo; use common\models\oldDb\DoctorInfo;
use common\models\oldDb\GranularRepice; use common\models\oldDb\GranularRepice;
use common\models\oldDb\Prescription; use common\models\oldDb\Prescription;
@@ -20,7 +21,9 @@ use common\models\oldDb\ServicePackageRepice;
use common\models\oldDb\Store; use common\models\oldDb\Store;
use common\models\oldDb\SystemConfig; use common\models\oldDb\SystemConfig;
use common\models\oldDb\User; use common\models\oldDb\User;
use common\models\oldDb\UserPatient;
use common\models\oldDb\WestRepice; use common\models\oldDb\WestRepice;
use common\models\newDb\DeliveryWarehouseModel;
use common\modelsgii\oldDb\RefundReason; use common\modelsgii\oldDb\RefundReason;
use common\services\ExpressService; use common\services\ExpressService;
use member\models\forms\ProductOrderSubmitForm; use member\models\forms\ProductOrderSubmitForm;
@@ -150,7 +153,7 @@ class ProductOrderController extends BaseAppController
$this->requestValidate($post, [ $this->requestValidate($post, [
['prescription_id', 'required'] ['prescription_id', 'required']
]); ]);
$ProductOrder = ProductOrder::find()->select('id,order_no,is_online,su_id,p_id,user_id,is_pay,prescription_type,address_id,address,decoct_price,order_type,items_price,process_price,treatement_price,total_pay_price,pay_method,trans_expenses,created_at,received_time,cancel_status,refund_status,status')->where([ $ProductOrder = ProductOrder::find()->select('id,order_no,is_online,su_id,p_id,up_id,user_id,is_pay,prescription_type,address_id,address,decoct_price,order_type,items_price,process_price,treatement_price,total_pay_price,pay_method,trans_expenses,created_at,received_time,cancel_status,refund_status,status')->where([
'p_id' => $post['prescription_id'], 'p_id' => $post['prescription_id'],
'user_id' => \Yii::$app->user->identity->getId(), 'user_id' => \Yii::$app->user->identity->getId(),
// 'store_id' => $post['store_id'] // 'store_id' => $post['store_id']
@@ -177,41 +180,63 @@ class ProductOrderController extends BaseAppController
$h->select('name'); $h->select('name');
}])->asArray()->one(); }])->asArray()->one();
$prescription = Prescription::find()->select('cr_ids,wr_ids,gr_ids,category')->where(['id' => $ProductOrder['p_id']])->one(); $prescription = Prescription::find()->select('cr_ids,wr_ids,gr_ids,category,store_id')->where(['id' => $ProductOrder['p_id']])->one();
if($prescription['wr_ids']){ // 获取处方来源诊所信息
$wr_ids = explode(',', $prescription['wr_ids']); $prescriptionStore = null;
if ($prescription && $prescription->store_id) {
$prescriptionStore = Store::find()->select('id,name,mobile,position')->where(['id' => $prescription->store_id])->asArray()->one();
}
$count = 0;
$west = null;
$chinese = null;
$granular = null;
if($prescription && $prescription->wr_ids){
$wr_ids = explode(',', $prescription->wr_ids);
if ($ProductOrder['prescription_type'] == 5) { if ($ProductOrder['prescription_type'] == 5) {
$west = ServicePackageRepice::find()->select('content,number,total_price')->where([ $westModels = ServicePackageRepice::find()->select('content,number,total_price')->where([
'in', 'id', $wr_ids 'in', 'id', $wr_ids
])->all(); ])->all();
} else { } else {
$west = WestRepice::find()->select('content,number,total_price')->where([ $westModels = WestRepice::find()->select('content,number,total_price')->where([
'in', 'id', $wr_ids 'in', 'id', $wr_ids
])->all(); ])->all();
} }
foreach ($west as $value) { $west = [];
$value['content']=Json::decode($value['content']); foreach ($westModels as $value) {
$row = $value->toArray();
$content = Json::decode($row['content']);
if (is_array($content) && !empty($content['id']) && empty($content['instruction'])) {
$drugInstruction = Drug::find()->select('instruction')->where(['id' => $content['id']])->scalar();
if ($drugInstruction) {
$content['instruction'] = $drugInstruction;
}
}
$row['content'] = $content;
$west[] = $row;
} }
$count = count($west); $count = count($west);
}else if($prescription['cr_ids']){ }else if($prescription && $prescription->cr_ids){
$cr_ids = explode(',', $prescription['cr_ids']); $cr_ids = explode(',', $prescription->cr_ids);
$chinese = ChineseRepice::find()->select('content,total_price')->where([ $chineseModels = ChineseRepice::find()->select('content,total_price')->where([
'in', 'id', $cr_ids 'in', 'id', $cr_ids
])->all(); ])->all();
foreach ($chinese as $val) { $chinese = ['list' => []];
foreach ($chineseModels as $val) {
$content = Json::decode($val['content']); $content = Json::decode($val['content']);
foreach ($content as $v){ foreach ($content as $v){
$chinese['list'][]= $v; $chinese['list'][]= $v;
} }
} }
$count = count($chinese['list']); $count = count($chinese['list']);
}else{ }else if($prescription && $prescription->gr_ids){
$gr_ids = explode(',', $prescription['gr_ids']); $gr_ids = explode(',', $prescription->gr_ids);
$granular = GranularRepice::find()->select('content,total_price')->where([ $granularModels = GranularRepice::find()->select('content,total_price')->where([
'in', 'id', $gr_ids 'in', 'id', $gr_ids
])->all(); ])->all();
foreach ($granular as $val) { $granular = ['list' => []];
foreach ($granularModels as $val) {
$content = Json::decode($val['content']); $content = Json::decode($val['content']);
foreach ($content as $v){ foreach ($content as $v){
$granular['list'][]= $v; $granular['list'][]= $v;
@@ -220,20 +245,56 @@ class ProductOrderController extends BaseAppController
$count = count($granular['list']); $count = count($granular['list']);
} }
if ($ProductOrder['p_id'] !== 0 && $ProductOrder['order_type'] !== 2) { if ($ProductOrder['p_id'] !== 0 && $ProductOrder['order_type'] !== 2) {
if ($prescription['category'] === 2) { if ($prescription && $prescription->category === 2) {
$ProductOrder['total_pay_price'] = $ProductOrder['trans_expenses']; $ProductOrder['total_pay_price'] = $ProductOrder['trans_expenses'];
$ProductOrder['items_price'] = 0; $ProductOrder['items_price'] = 0;
} }
} }
// 按订单明细回填仓名(appoint-medicine 展示用)
$orderItems = ProductOrderItems::find()
->where(['product_order_id' => $ProductOrder['id']])
->asArray()
->all();
$enriched = $this->enrichOrderItemsWarehouse($orderItems);
$ProductOrder['has_delivery_warehouse'] = $enriched['has_delivery_warehouse'] ? 1 : 0;
$warehouseNameByDrugId = [];
foreach ($enriched['items'] as $it) {
$warehouseNameByDrugId[(int) ($it['drug_id'] ?? 0)] = (string) ($it['delivery_warehouse_name'] ?? '');
}
if (!empty($west) && is_array($west)) {
foreach ($west as &$wItem) {
$drugId = (int) ($wItem['content']['id'] ?? 0);
$wItem['delivery_warehouse_name'] = $warehouseNameByDrugId[$drugId] ?? '';
}
unset($wItem);
}
if (!empty($chinese['list']) && is_array($chinese['list'])) {
foreach ($chinese['list'] as &$cItem) {
$drugId = (int) ($cItem['id'] ?? $cItem['drug_id'] ?? 0);
$cItem['delivery_warehouse_name'] = $warehouseNameByDrugId[$drugId] ?? '';
}
unset($cItem);
}
if (!empty($granular['list']) && is_array($granular['list'])) {
foreach ($granular['list'] as &$gItem) {
$drugId = (int) ($gItem['id'] ?? $gItem['drug_id'] ?? 0);
$gItem['delivery_warehouse_name'] = $warehouseNameByDrugId[$drugId] ?? '';
}
unset($gItem);
}
$ProductOrder['count'] = $count; $ProductOrder['count'] = $count;
return [ return [
'ProductOrder' => $ProductOrder, 'ProductOrder' => $ProductOrder,
'userInfo' => $userInfo, 'userInfo' => $userInfo,
'hospital' => $hospital, 'hospital' => $hospital,
'west' => $west ?? null, 'west' => $west,
'chinese' => $chinese ?? null, 'chinese' => $chinese,
'granular' => $granular ?? null, 'granular' => $granular,
'ProductOrderItems' => $enriched['items'],
'store' => $prescriptionStore ? ['store' => $prescriptionStore] : null,
'patient' => $this->getOrderPatientInfo((int) ($ProductOrder['up_id'] ?? 0), (int) ($ProductOrder['p_id'] ?? 0)),
]; ];
} }
@@ -391,7 +452,7 @@ class ProductOrderController extends BaseAppController
$this->requestValidate($post, [ $this->requestValidate($post, [
['order_id', 'required'] ['order_id', 'required']
]); ]);
$ProductOrder = ProductOrder::find()->select('id,is_online,order_no,delivery_method,su_id,p_id,user_id,is_pay,prescription_type,address_id,address,decoct_price,items_price,process_price,treatement_price,total_pay_price,pay_method,trans_expenses,created_at,cancel_status,refund_status,status,pay_time')->where([ $ProductOrder = ProductOrder::find()->select('id,store_id,is_online,order_no,delivery_method,su_id,p_id,up_id,user_id,is_pay,prescription_type,address_id,address,decoct_price,items_price,process_price,treatement_price,total_pay_price,pay_method,trans_expenses,created_at,cancel_status,refund_status,status,pay_time')->where([
'id' => $post['order_id'], 'id' => $post['order_id'],
'user_id' => \Yii::$app->user->identity->getId(), 'user_id' => \Yii::$app->user->identity->getId(),
// 'store_id' => $post['store_id'] // 'store_id' => $post['store_id']
@@ -423,16 +484,76 @@ class ProductOrderController extends BaseAppController
$h->select('name'); $h->select('name');
}])->asArray()->one(); }])->asArray()->one();
$ProductOrderItems = ProductOrderItems::find()->where(['product_order_id' => $ProductOrder['id']])->with(['drug' => function($q){ $ProductOrderItems = ProductOrderItems::find()->where(['product_order_id' => $ProductOrder['id']])->with(['drug' => function($q){
$q->select('id,drug_name,function,specification,usage,instruction'); $q->select('id,drug_name,is_otc,type,function,specification,usage,instruction');
}])->asArray()->all(); }])->asArray()->all();
// 回填配送仓名,供小程序按药展示「该药品由xxx配送」
$enriched = $this->enrichOrderItemsWarehouse($ProductOrderItems);
$ProductOrderItems = $enriched['items'];
$ProductOrder['has_delivery_warehouse'] = $enriched['has_delivery_warehouse'] ? 1 : 0;
$ProductOrder['count'] = count($ProductOrderItems); $ProductOrder['count'] = count($ProductOrderItems);
// 获取处方来源诊所信息
$prescriptionStore = null;
if ($ProductOrder['p_id']) {
$prescription = Prescription::find()->select('store_id')->where(['id' => $ProductOrder['p_id']])->asArray()->one();
if ($prescription && isset($prescription['store_id']) && $prescription['store_id']) {
$prescriptionStore = Store::find()->select('id,name,mobile,position')->where(['id' => $prescription['store_id']])->asArray()->one();
}
}
return [ return [
'ProductOrder' => $ProductOrder, 'ProductOrder' => $ProductOrder,
'userInfo' => $userInfo, 'userInfo' => $userInfo,
'hospital' => $hospital, 'hospital' => $hospital,
'ProductOrderItems' => $ProductOrderItems 'ProductOrderItems' => $ProductOrderItems,
'store' => $prescriptionStore ? ['store' => $prescriptionStore] : null,
'patient' => $this->getOrderPatientInfo((int) ($ProductOrder['up_id'] ?? 0), (int) ($ProductOrder['p_id'] ?? 0)),
];
}
/**
* 为订单明细附加配送仓名称
* delivery_warehouse_id=0 → 萧康医药本仓库;>0 → xk_delivery_warehouse.name
* @param array $items
* @return array{items: array, has_delivery_warehouse: bool}
*/
private function enrichOrderItemsWarehouse(array $items): array
{
$warehouseIds = [];
$hasDeliveryWarehouse = false;
foreach ($items as $item) {
$wid = (int) ($item['delivery_warehouse_id'] ?? 0);
if ($wid > 0) {
$hasDeliveryWarehouse = true;
$warehouseIds[$wid] = true;
}
}
$nameMap = [];
if (!empty($warehouseIds)) {
$rows = DeliveryWarehouseModel::find()
->select(['id', 'name'])
->where(['id' => array_keys($warehouseIds), 'deleted_at' => 0])
->asArray()
->all();
foreach ($rows as $row) {
$nameMap[(int) $row['id']] = (string) $row['name'];
}
}
foreach ($items as &$item) {
$wid = (int) ($item['delivery_warehouse_id'] ?? 0);
$item['delivery_warehouse_id'] = $wid;
if ($wid > 0) {
$item['delivery_warehouse_name'] = $nameMap[$wid] ?? ('仓库' . $wid);
} else {
$item['delivery_warehouse_name'] = '萧康医药本仓库';
}
}
unset($item);
return [
'items' => $items,
'has_delivery_warehouse' => $hasDeliveryWarehouse,
]; ];
} }
@@ -567,4 +688,52 @@ class ProductOrderController extends BaseAppController
return $express; return $express;
} }
/**
* 获取产品订单关联的就诊人信息
* 优先订单 up_id,其次处方 up_id,最后从处方 content 兜底(兼容历史数据)
*
* @param int $upId 订单就诊人 id
* @param int $prescriptionId 处方 id
* @return array|null
*/
private function getOrderPatientInfo(int $upId, int $prescriptionId = 0): ?array
{
$patientUpId = $upId;
$prescription = null;
if (!$patientUpId && $prescriptionId > 0) {
$prescription = Prescription::find()->select('up_id,content')->where(['id' => $prescriptionId])->asArray()->one();
if ($prescription && !empty($prescription['up_id'])) {
$patientUpId = (int) $prescription['up_id'];
}
}
if ($patientUpId > 0) {
$patient = UserPatient::find()->select('id,name,mobile')->where([
'id' => $patientUpId,
'is_delete' => 0,
])->asArray()->one();
if ($patient) {
return $patient;
}
}
if (!$prescription && $prescriptionId > 0) {
$prescription = Prescription::find()->select('content')->where(['id' => $prescriptionId])->asArray()->one();
}
if ($prescription && !empty($prescription['content'])) {
$content = Json::decode($prescription['content']);
if (!empty($content['patient']['name'])) {
return [
'id' => (int) ($content['patient']['id'] ?? 0),
'name' => $content['patient']['name'],
'mobile' => $content['patient']['mobile'] ?? '',
];
}
}
return null;
}
} }

View File

@@ -13,7 +13,7 @@ use yii\db\Exception;
*/ */
class StoreController extends BaseAppController class StoreController extends BaseAppController
{ {
public $optional = ['issue', 'detail']; public $optional = ['issue', 'detail', 'store-change'];
/** /**
* @doc-name 门店信息 * @doc-name 门店信息
@@ -97,53 +97,72 @@ class StoreController extends BaseAppController
*/ */
public function actionStoreChange() public function actionStoreChange()
{ {
$post=\Yii::$app->request->post(); $post = \Yii::$app->request->post();
$this->requestValidate($post,[ $this->requestValidate($post, [
['store_id','required'] ['store_id', 'required']
]); ]);
$t=\Yii::$app->db->beginTransaction();
// 获取当前用户
try {
$userId = \Yii::$app->user->identity->getId();
} catch (\Exception $e) {
ds(1);
return ['登陆异常'];
}
$user = User::findOne($userId);
if (!$user) {
throw new Exception('用户不存在');
}
// 如果当前门店就是要切换的门店,直接返回
if ($user->current_store_id == $post['store_id']) {
return ['success1'];
}
$t = \Yii::$app->db->beginTransaction();
try { try {
$store = Store::findOne($post['store_id']); $store = Store::findOne($post['store_id']);
if(!$store)throw new Exception('门店不存在'); if (!$store) {
throw new Exception('门店不存在');
}
StoreUser::updateAll(['is_online' => 0], [
StoreUser::updateAll(['is_online' => 0],[ 'user_id' => $userId,
'user_id' => \Yii::$app->user->identity->getId(),
'is_delete' => 0, 'is_delete' => 0,
'is_online' => 1 'is_online' => 1
]); ]);
$StoreUser=StoreUser::find()->where([ $StoreUser = StoreUser::find()->where([
'user_id' => \Yii::$app->user->identity->getId(), 'user_id' => $userId,
'store_id' => $post['store_id'], 'store_id' => $post['store_id'],
'is_delete' => 0, 'is_delete' => 0,
])->one(); ])->one();
if (!$StoreUser){//绑定门店
if (!$StoreUser) { // 绑定门店
$StoreUser = new StoreUser(); $StoreUser = new StoreUser();
$StoreUser->store_id = $post['store_id']; $StoreUser->store_id = $post['store_id'];
$StoreUser->user_id = \Yii::$app->user->identity->getId(); $StoreUser->user_id = $userId;
//如果是搜索小程序进入后扫码其他门店,删除默认门店数据 // 如果是搜索小程序进入后扫码其他门店,删除默认门店数据
StoreUser::updateAll(['is_delete' => 1], [
StoreUser::updateAll(['is_delete' => 1],[ 'user_id' => $userId,
'user_id' => \Yii::$app->user->identity->getId(),
'is_delete' => 0, 'is_delete' => 0,
'type' => 1 'type' => 1
]); ]);
} }
$StoreUser->last_login_time = time(); $StoreUser->last_login_time = time();
$StoreUser->type=2; $StoreUser->type = 2;
$StoreUser->is_online=1; $StoreUser->is_online = 1;
$StoreUser->saveOrFail(); $StoreUser->saveOrFail();
$user=User::find()->where(['id'=>\Yii::$app->user->identity->getId()])->one(); $user->current_store_id = $post['store_id'];
if (!$user) throw new Exception('用户不存在');
$user->current_store_id=$post['store_id'];
$user->saveOrFail(); $user->saveOrFail();
$t->commit(); $t->commit();
return ['success']; return ['success'];
}catch (\Exception $exception){ } catch (\Exception $exception) {
$t->rollBack(); $t->rollBack();
throw new Exception($exception->getMessage()); throw new Exception($exception->getMessage());
} }

View File

@@ -9,6 +9,7 @@ namespace platform\modules\v1\controllers;
use common\jobs\ProductOrderSendJob; use common\jobs\ProductOrderSendJob;
use common\jobs\templateMessage\ProductOrderSend; use common\jobs\templateMessage\ProductOrderSend;
use common\models\oldDb\ExpressNos; use common\models\oldDb\ExpressNos;
use common\models\oldDb\Drug;
use common\models\oldDb\Prescription; use common\models\oldDb\Prescription;
use common\models\oldDb\ProductOrder; use common\models\oldDb\ProductOrder;
use common\models\oldDb\ProductOrderLog; use common\models\oldDb\ProductOrderLog;
@@ -40,23 +41,29 @@ class ErpController extends Controller
ProductOrderLog::saveLog(0,'江奥川ERP拉取西(中成)药订单开始 startDate:'.$post['startDate'].' endDate:'.$post['endDate']); ProductOrderLog::saveLog(0,'江奥川ERP拉取西(中成)药订单开始 startDate:'.$post['startDate'].' endDate:'.$post['endDate']);
$startDate = strtotime($post['startDate']); $startDate = strtotime($post['startDate']);
$endDate = strtotime($post['endDate']) + 86400; $endDate = strtotime($post['endDate']) + 86400;
$productOrders = ProductOrder::find()->alias('po')->where([ $productOrders = ProductOrder::find()->alias('po')->where([
'po.prescription_type' => 2, // 'po.prescription_type' => 2,
'po.is_sync_erp' => 0, 'po.is_sync_erp' => 0,
]) ])
->andWhere([ ->andWhere([
'in','po.status',[1,2,3,6,7] 'in','po.status',[1,2,3,6,7]
]) ])
->andWhere([
'in','po.prescription_type',[2,3,5,6,7]
])
->andWhere(['BETWEEN', 'po.created_at', $startDate, $endDate]) ->andWhere(['BETWEEN', 'po.created_at', $startDate, $endDate])
// ->joinWith('approvedPrescription') // ->joinWith('approvedPrescription')
->with(['orderItems','store', 'prescription']) ->with(['orderItems','store', 'prescription'])
->asArray() ->asArray()
->all(); ->all();
// 批量加载药品 ERP 数量倍数,避免循环内逐条查询
$drugFactorMap = $this->buildDrugErpQtyFactorMap($productOrders);
//解析成erp所需参数(订单详情是否需要改动 - 线上订单的展示) //解析成erp所需参数(订单详情是否需要改动 - 线上订单的展示)
$erpData = []; $erpData = [];
$ids = []; $ids = [];
// 暂时默认使用11007诊所
$defaultUserId = '41677'; $defaultUserId = '41677';
foreach($productOrders as $k=>$v){ foreach($productOrders as $k=>$v){
// 如果是商城订单 // 如果是商城订单
@@ -94,14 +101,7 @@ class ErpController extends Controller
$orderItems = []; $orderItems = [];
foreach($v['orderItems'] as $vk=>$vv){ foreach($v['orderItems'] as $vk=>$vv){
// $drug = Drug::findOne($vv['drug_id']); $orderItems[$vk] = $this->buildErpOrderItem($vv, $drugFactorMap);
$orderItems[$vk] = [
'detailId' => $vv['id'],
'productSku' => $vv['drug_no'],
'quantity' => $vv['number'],
'paymentPrice' => $vv['buy_price'],
'price' => round($vv['number'] * $vv['buy_price'], 2)
];
} }
$erpData[$k]['orderItems'] = $orderItems; $erpData[$k]['orderItems'] = $orderItems;
@@ -118,11 +118,14 @@ class ErpController extends Controller
$erpData[$k]['orderId'] = $v['order_no']; $erpData[$k]['orderId'] = $v['order_no'];
$erpData[$k]['createTime'] = date('Y-m-d H:i:s', $v['created_at']); $erpData[$k]['createTime'] = date('Y-m-d H:i:s', $v['created_at']);
// 如果是商城处方订单 // 如果是商城处方订单
if ($v['is_online'] == 3) {
$erpData[$k]['userId'] = $defaultUserId; // 暂时默认使用11007诊所
} else { $erpData[$k]['userId'] = $defaultUserId;
$erpData[$k]['userId'] = $v['store']['erp_id']; // if ($v['is_online'] == 3 || $v['is_online'] == 2) {
} // $erpData[$k]['userId'] = $defaultUserId;
// } else {
// $erpData[$k]['userId'] = $v['store']['erp_id'];
// }
$erpData[$k]['orderStatus'] = $v['status']; $erpData[$k]['orderStatus'] = $v['status'];
$erpData[$k]['totalAmount'] = $v['total_pay_price']; $erpData[$k]['totalAmount'] = $v['total_pay_price'];
// $erpData[$k]['deliveryAmount'] = $v['trans_expenses']; // $erpData[$k]['deliveryAmount'] = $v['trans_expenses'];
@@ -140,14 +143,7 @@ class ErpController extends Controller
$orderItems = []; $orderItems = [];
foreach($v['orderItems'] as $vk=>$vv){ foreach($v['orderItems'] as $vk=>$vv){
// $drug = Drug::findOne($vv['drug_id']); $orderItems[$vk] = $this->buildErpOrderItem($vv, $drugFactorMap);
$orderItems[$vk] = [
'detailId' => $vv['id'],
'productSku' => $vv['drug_no'],
'quantity' => $vv['number'],
'paymentPrice' => $vv['buy_price'],
'price' => round($vv['number'] * $vv['buy_price'], 2)
];
} }
$erpData[$k]['orderItems'] = $orderItems; $erpData[$k]['orderItems'] = $orderItems;
@@ -158,7 +154,9 @@ class ErpController extends Controller
} }
} }
// ds($erpData); // key重置
$erpData = array_values($erpData);
ProductOrderLog::saveLog(0,'江奥川ERP拉取西(中成)药订单结束,拉取订单数据'. '--------'. json_encode($erpData));
if(!empty($ids)){ if(!empty($ids)){
//更新为已同步erp //更新为已同步erp
\Yii::$app->db->createCommand()->update('yii_product_order', [ \Yii::$app->db->createCommand()->update('yii_product_order', [
@@ -184,6 +182,69 @@ class ErpController extends Controller
return $erpData; return $erpData;
} }
/**
* 从待同步订单中收集 drug_id,批量查询 ERP 数量倍数
* @param array $productOrders
* @return array<int, float> drug_id => factor
*/
private function buildDrugErpQtyFactorMap(array $productOrders): array
{
$drugIds = [];
foreach ($productOrders as $order) {
if (empty($order['orderItems'])) {
continue;
}
foreach ($order['orderItems'] as $item) {
if (!empty($item['drug_id'])) {
$drugIds[] = (int) $item['drug_id'];
}
}
}
$drugIds = array_unique($drugIds);
if (empty($drugIds)) {
return [];
}
$rows = Drug::find()
->select(['id', 'erp_qty_factor'])
->where(['id' => $drugIds])
->asArray()
->all();
$map = [];
foreach ($rows as $row) {
$factor = (float) ($row['erp_qty_factor'] ?? 1);
$map[(int) $row['id']] = $factor > 0 ? $factor : 1;
}
return $map;
}
/**
* 构建 ERP 订单明细:quantity 按药品倍数换算,price 仍按原订单数量
* @param array $item 订单明细
* @param array<int, float> $drugFactorMap
* @return array
*/
private function buildErpOrderItem(array $item, array $drugFactorMap): array
{
$drugId = (int) ($item['drug_id'] ?? 0);
$factor = $drugFactorMap[$drugId] ?? 1;
$originQty = (int) ($item['number'] ?? 0);
$erpQty = (int) round($originQty * $factor);
$scale = 2; // 金额一般保留 2 位小数
$buyPrice = $item['buy_price'];
if (bccomp($factor, '1', $scale) === 1) {
$erpPaymentPrice = bcdiv($buyPrice, $factor, $scale);
} else {
$erpPaymentPrice = $buyPrice;
}
return [
'detailId' => $item['id'],
'productSku' => $item['drug_no'],
'quantity' => (string)$erpQty,
'paymentPrice' => $erpPaymentPrice,
'price' => round($originQty * $item['buy_price'], 2),
];
}
/** /**
* @author: liudiao * @author: liudiao
* @Date: 2023-08-01 14:10:45 * @Date: 2023-08-01 14:10:45

View File

@@ -32,9 +32,9 @@ class AgreementForm extends BaseModel
} }
return BaseConfig::find() return BaseConfig::find()
->where([ ->where([
'end' => $this->end, 'end' => 2,
'status' => 0, 'status' => 0,
'store_id'=>\Yii::$app->store // 'store_id'=>\Yii::$app->store
])->andWhere(['type'=>[1,2]]) ])->andWhere(['type'=>[1,2]])
->select(['content', 'change_at']) ->select(['content', 'change_at'])
->orderBy(['change_at' => SORT_DESC]) ->orderBy(['change_at' => SORT_DESC])

View File

@@ -206,6 +206,21 @@ class LoginForm extends BaseModel
'su_id' => $ServiceUser->id, 'su_id' => $ServiceUser->id,
])->with(['serviceUser']) ])->with(['serviceUser'])
->asArray()->one(); ->asArray()->one();
// 把ServiceUser信息存在Redis里面(使用DB 1,key前缀加上doctor_wx区分)
$ServiceUserData = [
'user' => [
'id' => $ServiceUser->id,
'mobile' => $ServiceUser->mobile ?? '',
'nickname' => $ServiceUser->nickname ?? '微信用户',
'role' => $ServiceUser->role,
'status' => $ServiceUser->status,
'plate_type' => $ServiceUser->plate_type,
]
];
\Yii::$app->redis->select(1);
\Yii::$app->redis->set('xiaokang_database_xk_user_doctor_wx_' . $token, json_encode($ServiceUserData));
return [ return [
'token'=>$token, 'token'=>$token,
'data'=>$StoreDoctor 'data'=>$StoreDoctor
@@ -256,6 +271,21 @@ class LoginForm extends BaseModel
$StoreDoctor = StoreDoctor::find()->where([ $StoreDoctor = StoreDoctor::find()->where([
'su_id' => $ServiceUser->id, 'su_id' => $ServiceUser->id,
])->with(['serviceUser'])->asArray()->one(); ])->with(['serviceUser'])->asArray()->one();
// 把ServiceUser信息存在Redis里面(使用DB 1,key前缀加上doctor_wx区分)
$ServiceUserData = [
'user' => [
'id' => $ServiceUser->id,
'mobile' => $ServiceUser->mobile ?? '',
'nickname' => $ServiceUser->nickname ?? '微信用户',
'role' => $ServiceUser->role,
'status' => $ServiceUser->status,
'plate_type' => $ServiceUser->plate_type,
]
];
\Yii::$app->redis->select(1);
\Yii::$app->redis->set('xiaokang_database_xk_user_doctor_wx_' . $token, json_encode($ServiceUserData));
return [ return [
'token'=>$token, 'token'=>$token,
'data'=>$StoreDoctor, 'data'=>$StoreDoctor,
@@ -321,6 +351,21 @@ class LoginForm extends BaseModel
} }
$t->commit(); $t->commit();
// 把ServiceUser信息存在Redis里面(使用DB 1,key前缀加上doctor_wx区分)
$ServiceUserData = [
'user' => [
'id' => $ServiceUser->id,
'mobile' => $ServiceUser->mobile ?? '',
'nickname' => $ServiceUser->nickname ?? '微信用户',
'role' => $ServiceUser->role,
'status' => $ServiceUser->status,
'plate_type' => $ServiceUser->plate_type,
]
];
\Yii::$app->redis->select(1);
\Yii::$app->redis->set('xiaokang_database_xk_user_doctor_wx_' . $token, json_encode($ServiceUserData));
return [ return [
'token'=>$token, 'token'=>$token,
'StoreDoctor'=>$StoreDoctor, 'StoreDoctor'=>$StoreDoctor,

View File

@@ -4,15 +4,21 @@ namespace service\modules\v1\controllers;
use common\core\BaseAppController; use common\core\BaseAppController;
use common\helpers\FuncHelper; use common\helpers\FuncHelper;
use common\models\oldDb\PackageMethod;
use common\models\oldDb\ChineseRepice; use common\models\oldDb\ChineseRepice;
use common\models\oldDb\Drug;
use common\models\oldDb\GranularRepice; use common\models\oldDb\GranularRepice;
use common\models\oldDb\ProcessRule;
use common\models\oldDb\ProcessRuleNote;
use common\models\oldDb\Prescription; use common\models\oldDb\Prescription;
use common\models\oldDb\PrescriptionChinese; use common\models\oldDb\PrescriptionChinese;
use common\models\oldDb\PrescriptionGranular; use common\models\oldDb\PrescriptionGranular;
use common\models\oldDb\PrescriptionWest; use common\models\oldDb\PrescriptionWest;
use common\models\oldDb\WestRepice; use common\models\oldDb\WestRepice;
use common\modelsgii\oldDb\ChineseMedicine;
use common\services\PrescriptionService; use common\services\PrescriptionService;
use yii\base\Exception; use yii\base\Exception;
use yii\helpers\Json;
/** /**
* @doc-module 处方详情 * @doc-module 处方详情
@@ -103,6 +109,354 @@ class PrescripDetailController extends BaseAppController
* 开处方-常用方 * 开处方-常用方
*/ */
public function actionCommonUse() public function actionCommonUse()
{
return $this->commonUseResponseLikeXkApi(\Yii::$app->request->post());
}
/**
* @doc-name 开处方-常用方详情(中药)
* @doc-param int id 处方id
*/
public function actionCommonChinese()
{
return $this->commonChineseDetailLikeXkApi(\Yii::$app->request->post());
}
/**
* @doc-name 开处方-常用方详情(颗粒药)
* @doc-param int id 处方id
*/
public function actionCommonGranular()
{
return $this->commonGranularDetailLikeXkApi(\Yii::$app->request->post());
}
/**
* @doc-name 开处方-常用方详情(西药)
* @doc-param int id 处方id
*/
public function actionCommonWest()
{
return $this->commonWestDetailLikeXkApi(\Yii::$app->request->post());
}
protected function commonUseResponseLikeXkApi(array $post): array
{
$this->requestValidate($post, [
['store_id', 'required'],
]);
$storeId = (int) $post['store_id'];
// $checkPrice = !isset($post['check_price']) || (int) $post['check_price'] === 1;
$checkPrice = 1;
$chinese = PrescriptionChinese::find()->where([
'type' => 2,
'store_id' => $storeId,
])->andWhere(['su_id' => \Yii::$app->user->identity->id])->asArray()->all();
$west = PrescriptionWest::find()->where([
'type' => 2,
'store_id' => $storeId,
])->andWhere(['su_id' => \Yii::$app->user->identity->id])->asArray()->all();
$granular = PrescriptionGranular::find()->where([
'type' => 2,
'store_id' => $storeId,
])->andWhere(['su_id' => \Yii::$app->user->identity->id])->asArray()->all();
if (!$chinese && !$west && !$granular) {
throw new Exception('没有常用方');
}
$chineseRepice = [];
foreach ($chinese as &$chineseRow) {
$ids = array_filter(explode(',', (string) $chineseRow['cr_ids']));
$recipes = ChineseRepice::find()->where(['in', 'id', $ids])->asArray()->all();
$syncResult = $this->syncChineseCommonRecipesWithStorePrices($storeId, $chineseRow, $recipes, $checkPrice);
$recipes = $syncResult['recipes'];
$chineseRow['price_adjusted'] = $syncResult['price_adjusted'] ? 1 : 0;
if (!empty($recipes[0])) {
$this->attachChineseMetaForList($chineseRow, $recipes[0]);
}
foreach ($recipes as &$recipeRow) {
$recipeRow = $this->normalizeChineseRecipeRow($recipeRow);
}
unset($recipeRow);
$chineseRepice[] = $recipes;
}
unset($chineseRow);
$westRepice = [];
foreach ($west as $westRow) {
$ids = array_filter(explode(',', (string) $westRow['wr_ids']));
$recipes = WestRepice::find()->where(['in', 'id', $ids])
->with(['usetime', 'usetype', 'frequency', 'westUnit'])
->asArray()->all();
$westRepice[] = $this->buildCommonWestRecipeRowsLikeXkApi($recipes);
}
$granularRepice = [];
foreach ($granular as $granularRow) {
$ids = array_filter(explode(',', (string) $granularRow['gr_ids']));
$recipes = GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all();
$granularRepice[] = $this->buildCommonGranularRecipeRowsLikeXkApi($recipes);
}
return [
'chin_prescription' => $chinese,
'chinese' => $chineseRepice,
'west_prescription' => $west,
'west' => $westRepice,
'granular_prescription' => $granular,
'granular' => $granularRepice,
];
}
protected function commonChineseDetailLikeXkApi(array $post): array
{
$this->requestValidate($post, [
['id', 'required'],
['store_id', 'required'],
]);
$chinese = PrescriptionChinese::find()->where([
'id' => $post['id'],
'store_id' => $post['store_id'],
])->andWhere(['type' => 2])->asArray()->one();
if (!$chinese) {
throw new Exception('没有该处方');
}
$ids = array_filter(explode(',', (string) $chinese['cr_ids']));
$recipes = ChineseRepice::find()->where(['in', 'id', $ids])->asArray()->all();
$syncResult = $this->syncChineseCommonRecipesWithStorePrices((int) $chinese['store_id'], $chinese, $recipes, true);
$recipes = $syncResult['recipes'];
foreach ($recipes as &$recipeRow) {
$recipeRow = $this->normalizeChineseRecipeRow($recipeRow);
}
unset($recipeRow);
return $recipes;
}
protected function commonGranularDetailLikeXkApi(array $post): array
{
$this->requestValidate($post, [
['id', 'required'],
['store_id', 'required'],
]);
$granular = PrescriptionGranular::find()->where([
'id' => $post['id'],
'store_id' => $post['store_id'],
])->andWhere(['type' => 2])->asArray()->one();
if (!$granular) {
throw new Exception('没有该处方');
}
$ids = array_filter(explode(',', (string) $granular['gr_ids']));
$recipes = GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all();
return $this->buildCommonGranularRecipeRowsLikeXkApi($recipes);
}
protected function commonWestDetailLikeXkApi(array $post): array
{
$this->requestValidate($post, [
['id', 'required'],
['store_id', 'required'],
]);
$west = PrescriptionWest::find()->where([
'id' => $post['id'],
'store_id' => $post['store_id'],
])->andWhere(['type' => 2])->asArray()->one();
if (!$west) {
throw new Exception('没有该处方');
}
$ids = array_filter(explode(',', (string) $west['wr_ids']));
$recipes = WestRepice::find()->where(['in', 'id', $ids])
->with(['usetime', 'usetype', 'frequency', 'westUnit'])
->asArray()->all();
return $this->buildCommonWestRecipeRowsLikeXkApi($recipes);
}
protected function syncChineseCommonRecipesWithStorePrices(int $storeId, array $prescriptionRow, array $recipeRows, bool $persist): array
{
$priceAdjusted = false;
if (empty($recipeRows)) {
return ['recipes' => $recipeRows, 'price_adjusted' => false];
}
$time = time();
$transaction = \Yii::$app->db->beginTransaction();
try {
foreach ($recipeRows as &$recipeRow) {
$contentList = Json::decode($recipeRow['content'] ?? '', true);
if (!is_array($contentList)) {
continue;
}
$cmIds = array_values(array_filter(explode(',', (string) ($recipeRow['cm_id'] ?? ''))));
$dosage = max(1, (int) ($recipeRow['dosage'] ?? 1));
$drugTotal = 0.0;
$recipeChanged = false;
foreach ($contentList as $idx => &$drugRow) {
$drugRow = $this->normalizeChineseDrugRow($drugRow);
$drugId = (int) ($drugRow['drug_id'] ?? $drugRow['id'] ?? 0);
$price = (float) ($drugRow['price'] ?? 0);
$buyPrice = (float) ($drugRow['buy_price'] ?? 0);
if ($drugId > 0) {
$drug = Drug::find()->alias('d')->select('d.*')->where([
'd.id' => $drugId,
])->joinWith(['drugStoreDrug dsd' => function ($q) {
$q->andWhere(['dsd.status' => 2]);
}])->joinWith(['drugStoreRelation dsr' => function ($q) use ($storeId) {
$q->andWhere(['dsr.store_id' => $storeId]);
$q->andWhere(['dsr.status' => 2]);
}])->asArray()->one();
if ($drug && !empty($drug['drugStoreRelation'])) {
$latestPrice = (float) $drug['drugStoreRelation']['price'];
$latestBuyPrice = (float) $drug['drugStoreRelation']['buy_price'];
if ($latestPrice !== $price || $latestBuyPrice !== $buyPrice) {
$priceAdjusted = true;
$recipeChanged = true;
}
$price = $latestPrice;
$buyPrice = $latestBuyPrice;
$drugRow['price'] = $latestPrice;
$drugRow['buy_price'] = $latestBuyPrice;
if ($persist && isset($cmIds[$idx]) && is_numeric($cmIds[$idx])) {
ChineseMedicine::updateAll([
'price' => $latestPrice,
'buy_price' => $latestBuyPrice,
'updated_at' => $time,
], ['id' => (int) $cmIds[$idx]]);
}
}
}
$drugTotal += (float) ($drugRow['number'] ?? 0) * $price * $dosage;
}
unset($drugRow);
if ($persist && $recipeChanged) {
$recipeRow['content'] = Json::encode($contentList);
$recipeRow['total_price'] = round($drugTotal, 4);
ChineseRepice::updateAll([
'content' => $recipeRow['content'],
'total_price' => $recipeRow['total_price'],
'updated_at' => $time,
], ['id' => $recipeRow['id']]);
} else {
$recipeRow['content'] = Json::encode($contentList);
$recipeRow['total_price'] = round($drugTotal, 4);
}
}
unset($recipeRow);
if ($persist && $priceAdjusted && !empty($prescriptionRow['id'])) {
PrescriptionChinese::updateAll(['updated_at' => $time], ['id' => $prescriptionRow['id']]);
}
$transaction->commit();
return ['recipes' => $recipeRows, 'price_adjusted' => $priceAdjusted];
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}
protected function normalizeChineseRecipeRow(array $recipeRow): array
{
$contentList = Json::decode($recipeRow['content'] ?? '', true);
if (is_array($contentList)) {
foreach ($contentList as &$drugRow) {
$drugRow = $this->normalizeChineseDrugRow($drugRow);
}
unset($drugRow);
$recipeRow['content'] = Json::encode($contentList);
}
return $recipeRow;
}
protected function normalizeChineseDrugRow(array $drugRow): array
{
$name = $drugRow['drug_name'] ?? ($drugRow['name'] ?? '');
$drugRow['name'] = $name;
$drugRow['drug_name'] = $name;
if (isset($drugRow['way_id']) && !isset($drugRow['order'])) {
$drugRow['order'] = $drugRow['way_id'];
}
if (isset($drugRow['order']) && !isset($drugRow['way_id'])) {
$drugRow['way_id'] = $drugRow['order'];
}
if (!isset($drugRow['unit']) || empty($drugRow['unit'])) {
$drugRow['unit'] = ['name' => 'g'];
}
return $drugRow;
}
protected function attachChineseMetaForList(array &$prescriptionRow, array $firstRecipeRow): void
{
$prescriptionRow['rule_type'] = (int) ($firstRecipeRow['deployment'] ?? 1);
$prescriptionRow['dosage'] = (int) ($firstRecipeRow['dosage'] ?? 7);
$prescriptionRow['day_dosage'] = (int) ($firstRecipeRow['consumption'] ?? 2);
$prescriptionRow['process_rule_id'] = (int) ($firstRecipeRow['process_rule_id'] ?? 0);
$prescriptionRow['process_rule_note'] = $firstRecipeRow['process_rule_note'] ?? '';
$prescriptionRow['package_method_id'] = (int) ($firstRecipeRow['package_method_id'] ?? 0);
if ($prescriptionRow['process_rule_id']) {
$processRule = ProcessRule::findOne($prescriptionRow['process_rule_id']);
$prescriptionRow['process_rule_name'] = $processRule ? $processRule->name : '';
}
if ($prescriptionRow['process_rule_note']) {
$processRuleNote = ProcessRuleNote::find()->where(['note' => $prescriptionRow['process_rule_note']])->one();
$prescriptionRow['process_rule_note_name'] = $processRuleNote ? $processRuleNote->note : $prescriptionRow['process_rule_note'];
}
if ($prescriptionRow['package_method_id']) {
$packageMethod = PackageMethod::findOne($prescriptionRow['package_method_id']);
$prescriptionRow['package_method_name'] = $packageMethod ? $packageMethod->name : '';
}
}
protected function buildCommonWestRecipeRowsLikeXkApi(array $recipeRows): array
{
foreach ($recipeRows as &$recipeRow) {
$content = Json::decode($recipeRow['content'] ?? '', true);
if (is_array($content)) {
$recipeRow['drug_name'] = $content['drug_name'] ?? '';
$recipeRow['drug_id'] = $content['id'] ?? 0;
$recipeRow['image'] = $content['image'] ?? '';
$recipeRow['price'] = $content['price'] ?? ($recipeRow['total_price'] ?? 0);
}
$recipeRow['frequency_id'] = $recipeRow['f_id'] ?? 0;
$recipeRow['unit_id'] = $recipeRow['wu_id'] ?? 0;
$recipeRow['number'] = $recipeRow['grain_number'] ?? ($recipeRow['number'] ?? 1);
}
unset($recipeRow);
return $recipeRows;
}
protected function buildCommonGranularRecipeRowsLikeXkApi(array $recipeRows): array
{
foreach ($recipeRows as &$recipeRow) {
$contentList = Json::decode($recipeRow['content'] ?? '', true);
if (!is_array($contentList)) {
continue;
}
foreach ($contentList as &$drugRow) {
$name = $drugRow['drug_name'] ?? ($drugRow['name'] ?? '');
$drugRow['name'] = $name;
$drugRow['drug_name'] = $name;
if (isset($drugRow['way_id']) && !isset($drugRow['order'])) {
$drugRow['order'] = $drugRow['way_id'];
}
if (isset($drugRow['order']) && !isset($drugRow['way_id'])) {
$drugRow['way_id'] = $drugRow['order'];
}
if (!isset($drugRow['unit']) || empty($drugRow['unit'])) {
$drugRow['unit'] = ['name' => 'g'];
}
}
unset($drugRow);
$recipeRow['content'] = Json::encode($contentList);
}
unset($recipeRow);
return $recipeRows;
}
protected function actionCommonUseLegacy()
{ {
$post = \YII::$app->request->post(); $post = \YII::$app->request->post();
@@ -134,14 +488,14 @@ class PrescripDetailController extends BaseAppController
$westRepice[] = WestRepice::find()->where(['in', 'id', $ids])->with(['usetime', 'usetype', 'frequency', 'westUnit'])->asArray()->all(); $westRepice[] = WestRepice::find()->where(['in', 'id', $ids])->with(['usetime', 'usetype', 'frequency', 'westUnit'])->asArray()->all();
} }
} }
if($granular){ if($granular){
foreach ($granular as $value) { foreach ($granular as $value) {
$ids = explode(',', $value['gr_ids']); $ids = explode(',', $value['gr_ids']);
$granularRepice[] = GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all(); $granularRepice[] = GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all();
} }
} }
return [ return [
'chin_prescription' => $chinese, 'chin_prescription' => $chinese,
'chinese' => $chineseRepice, 'chinese' => $chineseRepice,
@@ -152,11 +506,7 @@ class PrescripDetailController extends BaseAppController
]; ];
} }
/** protected function actionCommonChineseLegacy()
* @doc-name 开处方-常用方详情(中药)
* @doc-param int id 处方id
*/
public function actionCommonChinese()
{ {
$post = \Yii::$app->request->post(); $post = \Yii::$app->request->post();
$this->requestValidate($post,[ $this->requestValidate($post,[
@@ -170,16 +520,10 @@ class PrescripDetailController extends BaseAppController
throw new Exception('没有该处方'); throw new Exception('没有该处方');
} }
$ids = explode(',', $chinese['cr_ids']); $ids = explode(',', $chinese['cr_ids']);
return ChineseRepice::find()->where(['in', 'id', $ids])->asArray()->all();
$recipe = ChineseRepice::find()->where(['in', 'id', $ids])->asArray()->all();
return $recipe;
} }
/** protected function actionCommonGranularLegacy()
* @doc-name 开处方-常用方详情(颗粒药)
* @doc-param int id 处方id
*/
public function actionCommonGranular()
{ {
$post = \Yii::$app->request->post(); $post = \Yii::$app->request->post();
$this->requestValidate($post,[ $this->requestValidate($post,[
@@ -193,17 +537,10 @@ class PrescripDetailController extends BaseAppController
throw new Exception('没有该处方'); throw new Exception('没有该处方');
} }
$ids = explode(',', $granular['gr_ids']); $ids = explode(',', $granular['gr_ids']);
return GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all();
$recipe = GranularRepice::find()->where(['in', 'id', $ids])->asArray()->all();
return $recipe;
} }
protected function actionCommonWestLegacy()
/**
* @doc-name 开处方-常用方详情(西药)
* @doc-param int id 处方id
*/
public function actionCommonWest()
{ {
$post = \Yii::$app->request->post(); $post = \Yii::$app->request->post();
$this->requestValidate($post,[ $this->requestValidate($post,[
@@ -217,9 +554,7 @@ class PrescripDetailController extends BaseAppController
throw new Exception('没有该处方'); throw new Exception('没有该处方');
} }
$ids = explode(',', $west['wr_ids']); $ids = explode(',', $west['wr_ids']);
return WestRepice::find()->where(['in', 'id', $ids])->with(['usetime', 'usetype', 'frequency', 'westUnit'])->asArray()->all();
$recipe = WestRepice::find()->where(['in', 'id', $ids])->with(['usetime', 'usetype', 'frequency', 'westUnit'])->asArray()->all();
return $recipe;
} }
/** /**

View File

@@ -871,25 +871,42 @@ class PrescriptionController extends BaseAppController
$drug_ids_str=implode(',',$drug_ids); $drug_ids_str=implode(',',$drug_ids);
$totalNum = 0; $totalNum = 0;
foreach ($medicine as $value){ $time = time();
foreach ($medicine as &$value) {
$drug = Drug::find()->alias('d')->select('d.*')->where([ $drug = Drug::find()->alias('d')->select('d.*')->where([
'd.id' => $value['drug_id'] 'd.id' => $value['drug_id'],
])->joinWith(['drugStoreDrug dsd' => function($q){ ])->joinWith(['drugStoreDrug dsd' => function ($q) {
$q->andWhere(['dsd.status' => 2]); $q->andWhere(['dsd.status' => 2]);
}])->joinWith(['drugStoreRelation dsr' => function ($q) use ($store_id){ }])->joinWith(['drugStoreRelation dsr' => function ($q) use ($store_id) {
$q->andWhere(['dsr.store_id' => $store_id]); $q->andWhere(['dsr.store_id' => $store_id]);
$q->andWhere(['dsr.status' => 2]); $q->andWhere(['dsr.status' => 2]);
}])->asArray()->one(); }])->asArray()->one();
if(!$drug){ if (!$drug) {
throw new Exception('药品库存数据错误'); throw new Exception('药品库存数据错误');
} }
if (empty($drug['drugStoreRelation'])) {
throw new Exception('药品暂不售卖');
}
$salePrice = $drug['drugStoreRelation']['price'];
$buyPrice = $drug['drugStoreRelation']['buy_price'];
ChineseMedicine::updateAll(
[
'price' => $salePrice,
'buy_price' => $buyPrice,
'updated_at' => $time,
],
['id' => $value['id']],
);
$value['price'] = $salePrice;
$value['buy_price'] = $buyPrice;
$drugNumber = (int) $value['number'] * (int) $param['dosage']; $drugNumber = (int) $value['number'] * (int) $param['dosage'];
if($drug['drugStoreDrug']['stock'] < $drugNumber){ if ($drug['drugStoreDrug']['stock'] < $drugNumber) {
throw new Exception($value['name'].'库存数量不足'); throw new Exception($value['name'] . '库存数量不足');
} }
$totalNum += $drugNumber; $totalNum += $drugNumber;
$price+=$value['number'] * $value['price'] * $param['dosage']; $price += $value['number'] * $salePrice * $param['dosage'];
} }
unset($value);
$process_price = 0; $process_price = 0;
$processRuleContent = ''; $processRuleContent = '';
@@ -1021,9 +1038,10 @@ class PrescriptionController extends BaseAppController
if(!$drug){ if(!$drug){
throw new Exception('药品库存数据错误'); throw new Exception('药品库存数据错误');
} }
$drugNumber = (int) $content[$j]['number'] * (int) $recipe['dosage']; $perDoseNumber = (int) $content[$j]['number'];
$drugNumber = $perDoseNumber * (int) $recipe['dosage'];
if($drug['drugStoreDrug']['stock']<$drugNumber){ if($drug['drugStoreDrug']['stock']<$drugNumber){
throw new Exception($content['name'].'库存数量不足'); throw new Exception($content[$j]['name'].'库存数量不足');
} }
\Yii::$app->db->createCommand()->update('yii_drug_store_relations', [ \Yii::$app->db->createCommand()->update('yii_drug_store_relations', [
'sale_number' => $drug['drugStoreRelation']['sale_number'] + $drugNumber 'sale_number' => $drug['drugStoreRelation']['sale_number'] + $drugNumber
@@ -1032,9 +1050,9 @@ class PrescriptionController extends BaseAppController
'stock' => $drug['drugStoreDrug']['stock'] - $drugNumber, 'stock' => $drug['drugStoreDrug']['stock'] - $drugNumber,
'frozen_number' => $drug['drugStoreDrug']['frozen_number'] + $drugNumber 'frozen_number' => $drug['drugStoreDrug']['frozen_number'] + $drugNumber
], ['id' => $drug['drugStoreDrug']['id']])->execute(); ], ['id' => $drug['drugStoreDrug']['id']])->execute();
$drug['number'] = $drugNumber; $drug['number'] = $perDoseNumber;
$drugStoreDrugs[] = $drug; $drugStoreDrugs[] = $drug;
$itemMarketPrice = bcmul($drugNumber,$drug['drugStoreRelation']['buy_price'],2); $itemMarketPrice = bcmul((string) $drugNumber,$drug['drugStoreRelation']['buy_price'],2);
$marketPrice = bcadd($marketPrice,$itemMarketPrice,2); $marketPrice = bcadd($marketPrice,$itemMarketPrice,2);
} }
@@ -1160,6 +1178,7 @@ class PrescriptionController extends BaseAppController
$item->drug_image = $v['image']; $item->drug_image = $v['image'];
$item->drug_no = $v['drug_number']; $item->drug_no = $v['drug_number'];
$item->number = $v['number']; $item->number = $v['number'];
$item->dosage = $repice[0]['dosage'];
$item->type = $v['type']; $item->type = $v['type'];
$item->price = $v['drugStoreRelation']['price']; $item->price = $v['drugStoreRelation']['price'];
$item->buy_price = $v['drugStoreRelation']['buy_price']; $item->buy_price = $v['drugStoreRelation']['buy_price'];
@@ -1724,6 +1743,7 @@ class PrescriptionController extends BaseAppController
$item->drug_image = $v['image']; $item->drug_image = $v['image'];
$item->drug_no = $v['drug_number']; $item->drug_no = $v['drug_number'];
$item->number = $v['number']; $item->number = $v['number'];
$item->dosage = $repice[0]['dosage'];
$item->type = $v['type']; $item->type = $v['type'];
$item->price = $v['drugStoreRelation']['price']; $item->price = $v['drugStoreRelation']['price'];
$item->buy_price = $v['drugStoreRelation']['buy_price']; $item->buy_price = $v['drugStoreRelation']['buy_price'];

View File

@@ -5,6 +5,7 @@ namespace service\modules\v1\controllers;
use common\core\BaseAppController; use common\core\BaseAppController;
use common\enums\RegisterEnum; use common\enums\RegisterEnum;
use common\helpers\FuncHelper; use common\helpers\FuncHelper;
use common\models\newDb\ClinicSalespersonModel;
use common\models\oldDb\Register; use common\models\oldDb\Register;
use common\models\oldDb\UserPatientCase; use common\models\oldDb\UserPatientCase;
use common\services\ExportService; use common\services\ExportService;
@@ -183,7 +184,18 @@ class RegisterController extends BaseAppController
'age' => function ($m) { 'age' => function ($m) {
return FuncHelper::getAgeFromIdNo($m->patient->id_card); return FuncHelper::getAgeFromIdNo($m->patient->id_card);
}, },
'sex'=>'patient.sex' 'sex'=>'patient.sex',
'salesperson_name' => function ($m) {
if (!$m->hasAttribute('salesperson_id') || (int) $m->salesperson_id <= 0) {
return '';
}
$sp = ClinicSalespersonModel::findOne((int) $m->salesperson_id);
if (!$sp) {
return '';
}
return (string) ($sp->nick_name ?? $sp->phone ?? '');
},
] ]
]; ];
return $this->create($query, $post); return $this->create($query, $post);