Compare commits

37 Commits
main ... master

Author SHA1 Message Date
李琦
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
25 changed files with 932 additions and 107 deletions

View File

@@ -12,6 +12,7 @@ use common\jobs\ProductOrderSyncJob;
use common\jobs\Sms\WaitApprovalMessageJob;
use common\jobs\templateMessage\PrescriptionCreated;
use common\models\oldDb\Prescription;
use common\models\oldDb\PrescriptionLog;
use common\models\oldDb\ProductOrder;
use common\models\oldDb\ProductOrderLog;
use common\models\oldDb\Reconciliation;
@@ -20,6 +21,7 @@ use common\models\oldDb\Store;
use common\models\oldDb\User;
use common\services\JacErpService;
use common\services\WeappService;
use common\services\WechatService;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\helpers\Json;
@@ -39,18 +41,91 @@ class OpenApiController extends BaseAdminController
$prescription = \Yii::$app->request->post('prescription');
//处方开具待支付订阅消息通知
\Yii::$app->queue->push(new PrescriptionCreated([
'orderId' => $prescription,
]));
$this->sendUserNote($prescription);
// //处方开具待支付订阅消息通知
// \Yii::$app->queue->push(new PrescriptionCreated([
// 'orderId' => $prescription,
// ]));
//处方生成短信通知药师审方
\Yii::$app->queue->push(new WaitApprovalMessageJob([
'orderId' => $prescription,
]));
// \Yii::$app->queue->push(new WaitApprovalMessageJob([
// 'orderId' => $prescription,
// ]));
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[]

View File

@@ -119,7 +119,8 @@ JJvBfLfudYNUjUCyW3gAcOIJ
'rsaPrivateKeyFilePath' => '/www/certs/user-rsa.pfx', //私钥文件路径
'publicKeyFilePath' => '/www/certs/efps.cer', //公钥
'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',
'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\RegisterLog;
use common\models\oldDb\Store;
use common\services\AccountAbleChangeLogService;
use yii\db\Exception;
@@ -694,7 +695,12 @@ class LedgerForm extends BaseModel
$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;
case 2://已取消
@@ -720,7 +726,17 @@ class LedgerForm extends BaseModel
$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 { // 未结算
Ledger::updateAll(['status' => 2, 'updated_at' => $time], ['order_id' => $this->order_id, 'order_type' => 2]);
@@ -892,8 +908,13 @@ class LedgerForm extends BaseModel
$money1 = bcadd($platformDrugTotal, $platformProcessTotal, 2);
$money2 = bcadd($platformDeliveryTotal, $platformDecoctTotal, 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' => '产品订单分账结算-平台',
]);
/******************************************** 门店 ********************************************** */
@@ -915,7 +936,8 @@ class LedgerForm extends BaseModel
//增加诊疗费
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->order_id = $this->order_id;
$logTreatement->user_id = $store->id;
@@ -931,7 +953,12 @@ class LedgerForm extends BaseModel
}
//门店可提现及累计金额更新
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;
case 2://已取消
@@ -960,13 +987,16 @@ class LedgerForm extends BaseModel
$log->saveOrFail();
//供应商冻结金额及累计金额更新
AccountBalanceModel::updateAllCounters([
// 'total' => bcmul($v['amount'], -1, 6),
'balance' => bcmul($v['amount'], -1, 6),
], [
'user_id' => $v['user_id'],
'type' => 3
]);
$this->applySupplierBalanceDeltaWithLog(
(int)$v['user_id'],
(float)bcmul($v['amount'], -1, 6),
'refund',
[
'order_id' => (int)$v['order_id'],
'order_type' => (int)$v['order_type'],
'remark' => '订单退款扣减供应商余额',
]
);
} else {
$log = clone $model;
$log->order_id = $v['order_id'];
@@ -982,7 +1012,17 @@ class LedgerForm extends BaseModel
$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 { // 未结算
@@ -1004,4 +1044,44 @@ class LedgerForm extends BaseModel
}
}
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('处方不存在或已取消');
}
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([
'touser' => $Prescription->user->openid,
'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 $place 产地
* @property int $decotion 煎法
* @property float $erp_qty_factor ERP抓取数量倍数默认1
* @property int $updated_at
* @property int $created_at
*/

View File

@@ -18,8 +18,9 @@ class ProductOrderItems extends \common\core\BaseActiveRecord
public function rules()
{
return [
[['product_order_id', 'drug_id'], 'integer'],
[['drug_image', 'drug_name', 'small_info', 'created_at', 'updated_at'], 'string'],
[['product_order_id', 'drug_id', 'dosage', 'number', 'type'], 'integer'],
[['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 $user_patient_id 就诊人id
* @property int $store_id 诊所id
* @property int $origin_store_id 发起委托方诊所/药店ID(药价)
* @property string $order_no 订单号
* @property int $depart_id
* @property int $order_number 挂号序号
@@ -44,7 +45,7 @@ class Register extends \common\core\BaseActiveRecord
{
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', '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'],
[['order_no', 'refuse_reason'], 'string', 'max' => 255],
];
@@ -61,6 +62,7 @@ class Register extends \common\core\BaseActiveRecord
'service_user_id' => 'Service User ID',
'user_patient_id' => 'User Patient ID',
'store_id' => 'Store ID',
'origin_store_id' => 'Origin Store ID',
'order_no' => 'Order No',
'depart_id' => 'Depart ID',
'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\modelsgii\oldDb\DoctorIdentity;
use Exception;
use Yii;
use yii\helpers\Json;
class PrescriptionService{
@@ -26,11 +27,11 @@ class PrescriptionService{
}
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
])->with('pharmacistInfo')->asArray()->one();
} 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
])->with('pharmacistInfo')->asArray()->one();
}
@@ -59,10 +60,97 @@ class PrescriptionService{
$prescription['Pharmacist_sign_image']=$PharmacistIdentity['sign_image']?? '';
$prescription['Pharmacist_sign_type']=$PharmacistIdentity['sign_type']?? '';
$prescription['online_tcm_print'] = $this->buildOnlineTcmPrint($prescription);
return $prescription;
} catch (Exception $e) {
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,
'store_id' => Yii::$app->store,
])->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) {
//用户关联门店
@@ -178,6 +193,19 @@ class LoginForm extends BaseModel
'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();
} catch (Exception $exception) {

View File

@@ -15,6 +15,7 @@ use common\models\oldDb\Store;
use common\models\oldDb\StoreDoctor;
use common\models\oldDb\UserPatient;
use common\modelsgii\oldDb\PayConfig;
use common\services\SalespersonOrderBindService;
use yii\db\Exception;
//挂号form
@@ -26,11 +27,12 @@ class RegisterForm extends BaseModel
public $service_user_id;
public $register_id;
public $register_type;
public $origin_store_id;
public function rules()
{
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']
];
}
@@ -117,26 +119,35 @@ class RegisterForm extends BaseModel
$t = \Yii::$app->db->beginTransaction();
try {
// 确定实际使用的门店ID
// 如果是购药register_type=3且当前门店药店配置了委托诊所则使用委托诊所ID
// 如果是诊所在线复诊register_type=2需要确保是诊所store.type=0
$actualStoreId = \Yii::$app->store;
// 确定实际使用的门店ID(履约诊所)
// 在线场景优先使用前端传入的 store_id如委托诊所药店复诊再按配置覆盖为委托诊所
$actualStoreId = (int) ($this->store_id ?: \Yii::$app->store);
if ($this->register_type == 3) {
$currentStore = Store::findOne($actualStoreId);
$currentStore = Store::findOne(\Yii::$app->store);
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);
// 诊所在线复诊:发起方诊所校验(会话门店须为诊所
$currentStore = Store::findOne(\Yii::$app->store);
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->user_id = \Yii::$app->user->id;
$UserRegister->store_id = $actualStoreId;
if ($UserRegister->hasAttribute('origin_store_id')) {
$UserRegister->origin_store_id = $originStoreId;
}
$UserRegister->order_no = FuncHelper::generate_order_no('SN');
$UserRegister->user_patient_id = $this->user_patient_id;
$UserRegister->service_user_id = $this->service_user_id;
@@ -145,6 +156,14 @@ class RegisterForm extends BaseModel
$UserRegister->order_number = ($order_number['order_number']??0 ) + 1;
$UserRegister->price = $ServiceUser->docService->register_price;
$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();
$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) {
$q->alias('i');
// 患者端列表不展示测试医生
$q->andWhere(['i.is_test' => 0]);
//搜索框搜索姓名和科室
if (!empty($keyword)) {
$q->andWhere([

View File

@@ -13,6 +13,7 @@ use common\models\oldDb\CashAccount;
use common\models\oldDb\CashApply;
use common\models\oldDb\ChargeCashPayRecord;
use common\models\oldDb\FundWater;
use common\services\AccountAbleChangeLogService;
use common\models\oldDb\PaymentProductOrder;
use common\models\oldDb\PaymentProductRefund;
use common\models\oldDb\PaymentRegister;
@@ -309,13 +310,35 @@ class EplpayCallbackController extends \yii\web\Controller
$applyOrder->saveOrFail();
if ($applyOrder->user_type === 3) {
$before = $CashAccount->balance;
$CashAccount->balance = bcadd($CashAccount->balance, $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 {
$before = $CashAccount->able_cash;
$CashAccount->able_cash = $CashAccount->able_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' => '提现回调失败回退可提现金额']
);
}
} else {
// 获取代扣订单
$chargeCpr = ChargeCashPayRecord::find()->where([

View File

@@ -10,6 +10,7 @@ use common\forms\ProductRefundForm;
use common\jobs\ProductOrderSyncPlatformJob;
use common\models\oldDb\Address;
use common\models\oldDb\ChineseRepice;
use common\models\oldDb\Drug;
use common\models\oldDb\DoctorInfo;
use common\models\oldDb\GranularRepice;
use common\models\oldDb\Prescription;
@@ -20,7 +21,9 @@ use common\models\oldDb\ServicePackageRepice;
use common\models\oldDb\Store;
use common\models\oldDb\SystemConfig;
use common\models\oldDb\User;
use common\models\oldDb\UserPatient;
use common\models\oldDb\WestRepice;
use common\models\newDb\DeliveryWarehouseModel;
use common\modelsgii\oldDb\RefundReason;
use common\services\ExpressService;
use member\models\forms\ProductOrderSubmitForm;
@@ -150,7 +153,7 @@ class ProductOrderController extends BaseAppController
$this->requestValidate($post, [
['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'],
'user_id' => \Yii::$app->user->identity->getId(),
// 'store_id' => $post['store_id']
@@ -186,27 +189,41 @@ class ProductOrderController extends BaseAppController
}
$count = 0;
$west = null;
$chinese = null;
$granular = null;
if($prescription && $prescription->wr_ids){
$wr_ids = explode(',', $prescription->wr_ids);
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
])->all();
} else {
$west = WestRepice::find()->select('content,number,total_price')->where([
$westModels = WestRepice::find()->select('content,number,total_price')->where([
'in', 'id', $wr_ids
])->all();
}
foreach ($west as $value) {
$value['content']=Json::decode($value['content']);
$west = [];
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);
}else if($prescription && $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
])->all();
foreach ($chinese as $val) {
$chinese = ['list' => []];
foreach ($chineseModels as $val) {
$content = Json::decode($val['content']);
foreach ($content as $v){
$chinese['list'][]= $v;
@@ -215,10 +232,11 @@ class ProductOrderController extends BaseAppController
$count = count($chinese['list']);
}else if($prescription && $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
])->all();
foreach ($granular as $val) {
$granular = ['list' => []];
foreach ($granularModels as $val) {
$content = Json::decode($val['content']);
foreach ($content as $v){
$granular['list'][]= $v;
@@ -233,15 +251,50 @@ class ProductOrderController extends BaseAppController
}
}
// 按订单明细回填仓名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;
return [
'ProductOrder' => $ProductOrder,
'userInfo' => $userInfo,
'hospital' => $hospital,
'west' => $west ?? null,
'chinese' => $chinese ?? null,
'granular' => $granular ?? null,
'west' => $west,
'chinese' => $chinese,
'granular' => $granular,
'ProductOrderItems' => $enriched['items'],
'store' => $prescriptionStore ? ['store' => $prescriptionStore] : null,
'patient' => $this->getOrderPatientInfo((int) ($ProductOrder['up_id'] ?? 0), (int) ($ProductOrder['p_id'] ?? 0)),
];
}
@@ -399,7 +452,7 @@ class ProductOrderController extends BaseAppController
$this->requestValidate($post, [
['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'],
'user_id' => \Yii::$app->user->identity->getId(),
// 'store_id' => $post['store_id']
@@ -431,8 +484,12 @@ class ProductOrderController extends BaseAppController
$h->select('name');
}])->asArray()->one();
$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();
// 回填配送仓名供小程序按药展示「该药品由xxx配送」
$enriched = $this->enrichOrderItemsWarehouse($ProductOrderItems);
$ProductOrderItems = $enriched['items'];
$ProductOrder['has_delivery_warehouse'] = $enriched['has_delivery_warehouse'] ? 1 : 0;
$ProductOrder['count'] = count($ProductOrderItems);
// 获取处方来源诊所信息
@@ -450,10 +507,55 @@ class ProductOrderController extends BaseAppController
'hospital' => $hospital,
'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,
];
}
/**
* @doc-name 支付产品订单
@@ -586,4 +688,52 @@ class ProductOrderController extends BaseAppController
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
{
public $optional = ['issue', 'detail'];
public $optional = ['issue', 'detail', 'store-change'];
/**
* @doc-name 门店信息
@@ -97,53 +97,72 @@ class StoreController extends BaseAppController
*/
public function actionStoreChange()
{
$post=\Yii::$app->request->post();
$post = \Yii::$app->request->post();
$this->requestValidate($post,[
['store_id','required']
$this->requestValidate($post, [
['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 {
$store = Store::findOne($post['store_id']);
if(!$store)throw new Exception('门店不存在');
if (!$store) {
throw new Exception('门店不存在');
}
StoreUser::updateAll(['is_online' => 0],[
'user_id' => \Yii::$app->user->identity->getId(),
StoreUser::updateAll(['is_online' => 0], [
'user_id' => $userId,
'is_delete' => 0,
'is_online' => 1
]);
$StoreUser=StoreUser::find()->where([
'user_id' => \Yii::$app->user->identity->getId(),
$StoreUser = StoreUser::find()->where([
'user_id' => $userId,
'store_id' => $post['store_id'],
'is_delete' => 0,
])->one();
if (!$StoreUser){//绑定门店
if (!$StoreUser) { // 绑定门店
$StoreUser = new StoreUser();
$StoreUser->store_id = $post['store_id'];
$StoreUser->user_id = \Yii::$app->user->identity->getId();
//如果是搜索小程序进入后扫码其他门店,删除默认门店数据
StoreUser::updateAll(['is_delete' => 1],[
'user_id' => \Yii::$app->user->identity->getId(),
$StoreUser->user_id = $userId;
// 如果是搜索小程序进入后扫码其他门店,删除默认门店数据
StoreUser::updateAll(['is_delete' => 1], [
'user_id' => $userId,
'is_delete' => 0,
'type' => 1
]);
}
$StoreUser->last_login_time = time();
$StoreUser->type=2;
$StoreUser->is_online=1;
$StoreUser->type = 2;
$StoreUser->is_online = 1;
$StoreUser->saveOrFail();
$user=User::find()->where(['id'=>\Yii::$app->user->identity->getId()])->one();
if (!$user) throw new Exception('用户不存在');
$user->current_store_id=$post['store_id'];
$user->current_store_id = $post['store_id'];
$user->saveOrFail();
$t->commit();
return ['success'];
}catch (\Exception $exception){
} catch (\Exception $exception) {
$t->rollBack();
throw new Exception($exception->getMessage());
}

View File

@@ -9,6 +9,7 @@ namespace platform\modules\v1\controllers;
use common\jobs\ProductOrderSendJob;
use common\jobs\templateMessage\ProductOrderSend;
use common\models\oldDb\ExpressNos;
use common\models\oldDb\Drug;
use common\models\oldDb\Prescription;
use common\models\oldDb\ProductOrder;
use common\models\oldDb\ProductOrderLog;
@@ -42,21 +43,27 @@ class ErpController extends Controller
$endDate = strtotime($post['endDate']) + 86400;
$productOrders = ProductOrder::find()->alias('po')->where([
'po.prescription_type' => 2,
// 'po.prescription_type' => 2,
'po.is_sync_erp' => 0,
])
->andWhere([
'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])
// ->joinWith('approvedPrescription')
->with(['orderItems','store', 'prescription'])
->asArray()
->all();
// 批量加载药品 ERP 数量倍数,避免循环内逐条查询
$drugFactorMap = $this->buildDrugErpQtyFactorMap($productOrders);
//解析成erp所需参数订单详情是否需要改动 - 线上订单的展示)
$erpData = [];
$ids = [];
// 暂时默认使用11007诊所
$defaultUserId = '41677';
foreach($productOrders as $k=>$v){
// 如果是商城订单
@@ -94,14 +101,7 @@ class ErpController extends Controller
$orderItems = [];
foreach($v['orderItems'] as $vk=>$vv){
// $drug = Drug::findOne($vv['drug_id']);
$orderItems[$vk] = [
'detailId' => $vv['id'],
'productSku' => $vv['drug_no'],
'quantity' => $vv['number'],
'paymentPrice' => $vv['buy_price'],
'price' => round($vv['number'] * $vv['buy_price'], 2)
];
$orderItems[$vk] = $this->buildErpOrderItem($vv, $drugFactorMap);
}
$erpData[$k]['orderItems'] = $orderItems;
@@ -118,7 +118,10 @@ class ErpController extends Controller
$erpData[$k]['orderId'] = $v['order_no'];
$erpData[$k]['createTime'] = date('Y-m-d H:i:s', $v['created_at']);
// 如果是商城处方订单
if ($v['is_online'] == 3) {
// 暂时默认使用11007诊所
// $erpData[$k]['userId'] = $defaultUserId;
if ($v['is_online'] == 3 || $v['is_online'] == 2) {
$erpData[$k]['userId'] = $defaultUserId;
} else {
$erpData[$k]['userId'] = $v['store']['erp_id'];
@@ -140,14 +143,7 @@ class ErpController extends Controller
$orderItems = [];
foreach($v['orderItems'] as $vk=>$vv){
// $drug = Drug::findOne($vv['drug_id']);
$orderItems[$vk] = [
'detailId' => $vv['id'],
'productSku' => $vv['drug_no'],
'quantity' => $vv['number'],
'paymentPrice' => $vv['buy_price'],
'price' => round($vv['number'] * $vv['buy_price'], 2)
];
$orderItems[$vk] = $this->buildErpOrderItem($vv, $drugFactorMap);
}
$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)){
//更新为已同步erp
\Yii::$app->db->createCommand()->update('yii_product_order', [
@@ -184,6 +182,69 @@ class ErpController extends Controller
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
* @Date: 2023-08-01 14:10:45

View File

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

View File

@@ -1038,10 +1038,10 @@ class PrescriptionController extends BaseAppController
if(!$drug){
throw new Exception('药品库存数据错误');
}
// $drugNumber = (int) $content[$j]['number'] * (int) $recipe['dosage'];
$drugNumber = $content[$j]['number'];
$perDoseNumber = (int) $content[$j]['number'];
$drugNumber = $perDoseNumber * (int) $recipe['dosage'];
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', [
'sale_number' => $drug['drugStoreRelation']['sale_number'] + $drugNumber
@@ -1050,9 +1050,9 @@ class PrescriptionController extends BaseAppController
'stock' => $drug['drugStoreDrug']['stock'] - $drugNumber,
'frozen_number' => $drug['drugStoreDrug']['frozen_number'] + $drugNumber
], ['id' => $drug['drugStoreDrug']['id']])->execute();
$drug['number'] = $drugNumber;
$drug['number'] = $perDoseNumber;
$drugStoreDrugs[] = $drug;
$itemMarketPrice = bcmul($drugNumber,$drug['drugStoreRelation']['buy_price'],2);
$itemMarketPrice = bcmul((string) $drugNumber,$drug['drugStoreRelation']['buy_price'],2);
$marketPrice = bcadd($marketPrice,$itemMarketPrice,2);
}

View File

@@ -5,6 +5,7 @@ namespace service\modules\v1\controllers;
use common\core\BaseAppController;
use common\enums\RegisterEnum;
use common\helpers\FuncHelper;
use common\models\newDb\ClinicSalespersonModel;
use common\models\oldDb\Register;
use common\models\oldDb\UserPatientCase;
use common\services\ExportService;
@@ -183,7 +184,18 @@ class RegisterController extends BaseAppController
'age' => function ($m) {
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);