Prechádzať zdrojové kódy

用观察者模式实现记录成长值与积分变动

shizhongqi 4 mesiacov pred
rodič
commit
fa7338dc54

+ 2 - 0
app-hd/controllers/CustomController.php

@@ -130,6 +130,7 @@ class CustomController extends BaseController
         $params = [
             'style' => 1,//手动修改
             'staffId' => $staffId,
+            'adminId' => $this->adminId,
             'staffName' => $staffName,
         ];
         $shop = $this->shop;
@@ -728,6 +729,7 @@ class CustomController extends BaseController
             }
         }
         $c->buyAmount = $buyAmount;
+        $c->listend = false;
         $c->save();
 
         // 2.更新此客户所对应花店的消费金额 expendAmount ---- xhHd -> expendAmount

+ 2 - 5
app-hd/controllers/RefundController.php

@@ -266,11 +266,8 @@ class RefundController extends BaseController
             $custom = CustomClass::getLockById($order->customId);
             if (!empty($custom)) {
                 $custom->buyAmount = bcsub($custom->buyAmount, $post['price'], 2);
-                $custom->integral = $custom->integral - intval($post['price']);
-                $custom->growth = $custom->growth - intval($post['price']);
-                $memberData = CustomClass::getCustomExpenseLevel($custom->growth, $this->mainId); // 设置等级多处需要同步修改的,请搜索:getCustomExpenseLevel
-                $custom->member = $memberData['level'];
-                $custom->memberName = $memberData['name'];
+                $custom->growthEventRemark = '退款';
+                $custom->mainId = $this->mainId;
                 $custom->save();
 
                 $hd = HdClass::getLockById($custom->hdId);

+ 16 - 17
biz-hd/custom/classes/CustomClass.php

@@ -11,7 +11,7 @@ use bizHd\member\classes\MemberLevelClass;
 use bizHd\order\classes\OrderClass;
 use bizHd\order\classes\SettleClass;
 use bizHd\shop\classes\ShopClass;
-use bizHd\user\services\UserGrowthService;
+use bizHd\user\classes\UserGrowthClass;
 use common\components\dict;
 use common\components\imgUtil;
 use common\components\noticeUtil;
@@ -183,11 +183,13 @@ class CustomClass extends BaseClass
     //会员等级变化,包括手动修改、自动降会员和充值升会员等 ssh 20250324
     public static function levelChange($oldLevel, $newLevel, $shop, $custom, $hd, $params)
     {
+        $adminId = $params['adminId'];
         $staffId = $params['staffId'] ?? 0;
         $staffName = $params['staffName'] ?? '';
         $style = $params['style'] ?? 0;
         $target = $params['target'] ?? [];
         $rechargeAmount = $params['rechargeAmount'] ?? 0;
+
         $targetId = $target->id ?? 0;
         $mainId = $shop->mainId;
         $shopId = $shop->id;
@@ -238,25 +240,22 @@ class CustomClass extends BaseClass
         //成长值变更
         $growth = $current['amount'] ?? 0;
         $custom->growth = $growth;
+        // $custom->growthEventRemark = '等级变更';
         $custom->save();
 
         //成长值变动记录
-        $growthData = [
-            'userId' => $custom->userId,
-            'userName' => $custom->name,
-            'sjId' => $custom->sjId,
-            'relateId' => 0,
-            'growth' => $growth,
-            'num' => $custom->growth - $oldGrowth,
-            'io' => 0,
-            'payWay' => 0,
-            'event' => "管理员变更{$memberName}级,成长值从{$oldGrowth}变更为{$growth}",
-            'operatorId' => $staffId,
-            'createTime' => date('Y-m-d H:i:s'),
-            'gainType' => 0,
-            'addTime' => time(),
-        ];
-        UserGrowthService::add($growthData);
+         $growthData = [
+             'userId' => $custom->userId,
+             'userName' => $custom->name,
+             'event' => "管理员变更{$memberName}级,成长值从{$oldGrowth}变更为{$growth}",
+             'relateId' => 0,
+             'relateType' => 0,
+             'num' => $custom->growth - $oldGrowth,
+             'growth' => $growth,
+             'operatorId' => $adminId,
+             'createTime' => date('Y-m-d H:i:s')
+         ];
+         UserGrowthClass::add($growthData);
     }
 
     //客户采购欠款金额增加,如果有余额时,要进行欠款销账 ssh 20250715

+ 48 - 0
biz-hd/custom/models/Custom.php

@@ -1,9 +1,57 @@
 <?php
 namespace bizHd\custom\models;
 use bizHd\base\models\Base;
+use bizHd\custom\observers\BuyAmountObserver;
 
 class Custom extends Base
 {
+    /**
+     * xhCustom 的 buyAmount 变动监听的总开头(默认是开启)
+     *
+     * @var bool
+     */
+    public $listend = true;
+
+    /**
+     * mainId(运行时临时属性,不入库)。
+     * 传递必要参数 mainId
+     * @var int
+     */
+    public $mainId = 0;
+
+    /**
+     * 关联id(运行时临时属性,不入库)。
+     *
+     * @var int
+     */
+    public $relateId = 0;
+
+    /**
+     * 关联的表或类别(运行时临时属性,不入库)。
+     *
+     * 关联的表或类别:0.无关联 1.零售订单  --  具体请查看 xhUserGrowth表的 relateType 字段
+     *
+     * @var int
+     */
+    public $relateType = 0;
+
+	/**
+	 * 成长值流水事件文案(运行时临时属性,不入库)。
+	 *
+	 * 业务侧可在 save() 前赋值,供 BuyAmountObserver 使用。
+	 *
+	 * @var string
+	 */
+	public $growthEventRemark = '';
+
+	// 加上了 xhCustom 的 buyAmount 变动监听(观察者模式),并处理了联动增减逻辑 -- 该监听依赖 AR 事件触发(如 $model->save())。
+	// 若某处直接用 updateAll()/updateByCondition() 直接改 buyAmount,不会触发该观察者。
+	public function behaviors()
+	{
+		return [
+			BuyAmountObserver::class,
+		];
+	}
 
 	public static function tableName()
 	{

+ 97 - 0
biz-hd/custom/observers/BuyAmountObserver.php

@@ -0,0 +1,97 @@
+<?php
+
+namespace bizHd\custom\observers;
+
+use bizHd\custom\classes\CustomClass;
+use bizHd\user\classes\UserIntegralClass;
+use yii\base\Behavior;
+use yii\db\ActiveRecord;
+use yii\db\AfterSaveEvent;
+use bizHd\user\classes\UserGrowthClass;
+
+class BuyAmountObserver extends Behavior
+{
+	public function events()
+	{
+		return [
+			ActiveRecord::EVENT_AFTER_INSERT => 'onAfterSave',
+			ActiveRecord::EVENT_AFTER_UPDATE => 'onAfterSave',
+		];
+	}
+
+	public function onAfterSave(AfterSaveEvent $event)
+	{
+		/** @var ActiveRecord $model */
+		$model = $this->owner;
+		if ($model->listend === false) { //根据总开关判断是否执行记录积分与成长值变动
+		    return;
+        }
+
+		$oldBuyAmount = array_key_exists('buyAmount',$event->changedAttributes) ? $event->changedAttributes['buyAmount'] : $model->getAttribute('buyAmount');
+		$newBuyAmount = $model->getAttribute('buyAmount');
+		if (bccomp($newBuyAmount, $oldBuyAmount, 2) === 0) {
+			return;
+		}
+
+		$oldGrowth = array_key_exists('growth', $event->changedAttributes)
+			? $event->changedAttributes['growth']
+			: $model->getAttribute('growth'); // changedAttributes 里没有 growth 时,说明这次更新没改 growth,这时直接取模型当前值即可(它就等于旧值)。
+		$buyAmountDelta = bcsub($newBuyAmount, $oldBuyAmount, 2);
+		$newGrowth = bcadd($oldGrowth, $buyAmountDelta, 2);
+
+		$oldIntegral = array_key_exists('integral', $event->changedAttributes)
+			? $event->changedAttributes['integral']
+			: $model->getAttribute('integral');
+		$newIntegral = bcadd($oldIntegral, $buyAmountDelta, 2);
+
+		$model::updateAll([
+			'growth' => $newGrowth,
+			'integral' => $newIntegral,
+		], ['id' => $model->getPrimaryKey()]);
+
+
+        $mainId = $model->mainId;
+        if ($mainId > 0) {
+            $memberData = CustomClass::getCustomExpenseLevel($newGrowth, $mainId); // 设置等级多处需要同步修改的,请搜索:getCustomExpenseLevel
+            $model::updateAll([
+                'member' => (int) ($memberData['level'] ?? 0),
+                'memberName' => (string) ($memberData['name'] ?? ''),
+            ], ['id' => $model->getPrimaryKey()]);
+        }else{
+            throw new \Exception('mainId is required');
+        }
+
+		if ($buyAmountDelta == 0 || $buyAmountDelta == 0.00) {
+			return;
+		}
+
+		$createTime = date('Y-m-d H:i:s');
+		$growthEventRemark = isset($model->growthEventRemark) ? trim((string) $model->growthEventRemark) : '';
+		$growthData = [
+			'userId' => $model->getAttribute('userId'),
+			'userName' => $model->getAttribute('name'),
+			'event' => $growthEventRemark !== '' ? $growthEventRemark . ',成长值同步变更' : '累计消费变更同步成长值',
+			'relateId' => $model->relateId,
+			'relateType' => $model->relateType,
+			'num' => $buyAmountDelta,
+			'growth' => $newGrowth,
+			'operatorId' => 0,
+			'createTime' => $createTime,
+		];
+		UserGrowthClass::add($growthData);
+
+		//积分变动记录
+		$integralData = [
+			'userId' => $model->getAttribute('userId'),
+			'userName' => $model->getAttribute('name'),
+			'event' => $growthEventRemark !== '' ? $growthEventRemark . ',积分同步变更' : '累计消费变更同步积分',
+			'relateId' => $model->relateId,
+			'relateType' => $model->relateType,
+			'num' => $buyAmountDelta,
+			'integral' => $newIntegral,
+			'operatorId' => 0,
+			'createTime' => $createTime,
+		];
+		UserIntegralClass::add($integralData);
+	}
+}

+ 5 - 7
biz-hd/order/classes/OrderClass.php

@@ -457,18 +457,16 @@ class OrderClass extends BaseClass
                 $myCustom->recentExpend = date("Y-m-d H:i:s");
                 $myCustom->visitTime = date("Y-m-d H:i:s");
                 $myCustom->buyAmount = bcadd($myCustom->buyAmount, $order->realPrice, 2);
-                $myCustom->growth = $myCustom->growth + intval($order->realPrice);
-                $myCustom->integral = $myCustom->integral + intval($order->realPrice);
+                $myCustom->growthEventRemark = '累计消费变更';
             } elseif ($order->forward == 1) { //1 售后付款单(红冲)
                 $myCustom->buyAmount = bcsub($myCustom->buyAmount, $order->realPrice, 2);
-                $myCustom->growth = $myCustom->growth - intval($order->realPrice);
-                $myCustom->integral = $myCustom->integral - intval($order->realPrice);
+                $myCustom->growthEventRemark = '累计消费回退';
             } else {
                 util::fail('订单类型不存在');
             }
-            $memberData = CustomClass::getCustomExpenseLevel($myCustom->growth, $order->mainId); // 设置等级多处需要同步修改的,请搜索:getCustomExpenseLevel
-            $myCustom->member = $memberData['level'];
-            $myCustom->memberName = $memberData['name'];
+            $myCustom->relateId = $orderId;
+            $myCustom->relateType = 1; //关联的表或类别:0.无关联 1.零售订单
+            $myCustom->mainId = $order->mainId;
             $myCustom->save();
 
             $hd = HdClass::getLockById($myCustom->hdId);

+ 0 - 4
biz-hd/user/classes/UserIntegralClass.php

@@ -2,13 +2,9 @@
 
 namespace bizHd\user\classes;
 
-use common\services\ImageService;
-use Yii;
 use bizHd\base\classes\BaseClass;
 
 class UserIntegralClass extends BaseClass
 {
-	
 	public static $baseFile = '\bizHd\user\models\UserIntegral';
-	
 }

+ 4 - 32
biz-hd/user/models/UserIntegral.php

@@ -1,28 +1,7 @@
 <?php
 namespace bizHd\user\models;
 use bizHd\base\models\Base;
-/**
- * This is the model class for table "xhUserIntegral".
- *
- * @property int $id
- * @property int $userId
- * @property string $userName 用户名
- * @property string $alipayId 支付宝的uid
- * @property int $sjId 商家id
- * @property string $relateId 关联id
- * @property string $amount 涉及金额
- * @property int $integral 剩余可兑换积分
- * @property int $num 积分数量
- * @property int $io 收支类型0收入 1支出
- * @property int $payWay 资金收支方式0微信1支付宝2余额3现金,具体请查看配置文件configDict payWay
- * @property int $capitalType 流水订单的类型 参考configDict capitalType
- * @property string $event 原由,事项,解释
- * @property int $operatorId 操作人,adminId
- * @property string $remark 备注
- * @property int $addTime 添加时间,时间戳格式
- * @property string $createTime 创建时间
- * @property string $updateTime
- */
+
 class UserIntegral extends Base
 {
 	/**
@@ -39,12 +18,11 @@ class UserIntegral extends Base
 	public function rules()
 	{
 		return [
-			[['userId', 'sjId', 'integral', 'num', 'io', 'payWay', 'capitalType', 'operatorId', 'addTime'], 'integer'],
-			[['amount'], 'number'],
-			[['capitalType', 'createTime'], 'required'],
+			[['userId', 'relateId', 'relateType', 'operatorId'], 'integer'],
+			[['integral', 'num', 'amount'], 'number'],
+			//[['capitalType', 'createTime'], 'required'],
 			[['createTime', 'updateTime'], 'safe'],
 			[['userName', 'alipayId'], 'string', 'max' => 50],
-			[['relateId'], 'string', 'max' => 100],
 			[['event'], 'string', 'max' => 200],
 			[['remark'], 'string', 'max' => 1000],
 		];
@@ -59,19 +37,13 @@ class UserIntegral extends Base
 			'id' => 'ID',
 			'userId' => 'User ID',
 			'userName' => 'User Name',
-			'alipayId' => 'Alipay ID',
-			'sjId' => 'Merchant ID',
 			'relateId' => 'Relate ID',
 			'amount' => 'Amount',
 			'integral' => 'Integral',
 			'num' => 'Num',
-			'io' => 'Io',
-			'payWay' => 'Pay Way',
-			'capitalType' => 'Capital Type',
 			'event' => 'Event',
 			'operatorId' => 'Operator ID',
 			'remark' => 'Remark',
-			'addTime' => 'Add Time',
 			'createTime' => 'Create Time',
 			'updateTime' => 'Update Time',
 		];

+ 0 - 4
biz-mall/user/classes/UserIntegralClass.php

@@ -2,13 +2,9 @@
 
 namespace bizMall\user\classes;
 
-use common\services\ImageService;
-use Yii;
 use bizMall\base\classes\BaseClass;
 
 class UserIntegralClass extends BaseClass
 {
-	
 	public static $baseFile = '\bizMall\user\models\UserIntegral';
-	
 }

+ 20 - 48
biz-mall/user/models/UserIntegral.php

@@ -1,28 +1,7 @@
 <?php
 namespace bizMall\user\models;
 use bizMall\base\models\Base;
-/**
- * This is the model class for table "xhUserIntegral".
- *
- * @property int $id
- * @property int $userId
- * @property string $userName 用户名
- * @property string $alipayId 支付宝的uid
- * @property int $sjId 商家id
- * @property string $relateId 关联id
- * @property string $amount 涉及金额
- * @property int $integral 剩余可兑换积分
- * @property int $num 积分数量
- * @property int $io 收支类型0收入 1支出
- * @property int $payWay 资金收支方式0微信1支付宝2余额3现金,具体请查看配置文件configDict payWay
- * @property int $capitalType 流水订单的类型 参考configDict capitalType
- * @property string $event 原由,事项,解释
- * @property int $operatorId 操作人,adminId
- * @property string $remark 备注
- * @property int $addTime 添加时间,时间戳格式
- * @property string $createTime 创建时间
- * @property string $updateTime
- */
+
 class UserIntegral extends Base
 {
 	/**
@@ -39,14 +18,13 @@ class UserIntegral extends Base
 	public function rules()
 	{
 		return [
-			[['userId', 'sjId', 'integral', 'num', 'io', 'payWay', 'capitalType', 'operatorId', 'addTime'], 'integer'],
-			[['amount'], 'number'],
-			[['capitalType', 'createTime'], 'required'],
-			[['createTime', 'updateTime'], 'safe'],
-			[['userName', 'alipayId'], 'string', 'max' => 50],
-			[['relateId'], 'string', 'max' => 100],
-			[['event'], 'string', 'max' => 200],
-			[['remark'], 'string', 'max' => 1000],
+            [['userId', 'relateId', 'relateType', 'operatorId'], 'integer'],
+            [['integral', 'num', 'amount'], 'number'],
+            //[['capitalType', 'createTime'], 'required'],
+            [['createTime', 'updateTime'], 'safe'],
+            [['userName', 'alipayId'], 'string', 'max' => 50],
+            [['event'], 'string', 'max' => 200],
+            [['remark'], 'string', 'max' => 1000],
 		];
 	}
 	
@@ -56,24 +34,18 @@ class UserIntegral extends Base
 	public function attributeLabels()
 	{
 		return [
-			'id' => 'ID',
-			'userId' => 'User ID',
-			'userName' => 'User Name',
-			'alipayId' => 'Alipay ID',
-			'sjId' => 'Merchant ID',
-			'relateId' => 'Relate ID',
-			'amount' => 'Amount',
-			'integral' => 'Integral',
-			'num' => 'Num',
-			'io' => 'Io',
-			'payWay' => 'Pay Way',
-			'capitalType' => 'Capital Type',
-			'event' => 'Event',
-			'operatorId' => 'Operator ID',
-			'remark' => 'Remark',
-			'addTime' => 'Add Time',
-			'createTime' => 'Create Time',
-			'updateTime' => 'Update Time',
+            'id' => 'ID',
+            'userId' => 'User ID',
+            'userName' => 'User Name',
+            'relateId' => 'Relate ID',
+            'amount' => 'Amount',
+            'integral' => 'Integral',
+            'num' => 'Num',
+            'event' => 'Event',
+            'operatorId' => 'Operator ID',
+            'remark' => 'Remark',
+            'createTime' => 'Create Time',
+            'updateTime' => 'Update Time',
 		];
 	}
 }

+ 1 - 0
console/controllers/CustomController.php

@@ -178,6 +178,7 @@ class CustomController extends Controller
                             $memberData = CustomClass::getCustomExpenseLevel($c->growth, $mainId, $levelDatas); // 设置等级多处需要同步修改的,请搜索:getCustomExpenseLevel
                             $c->member = $memberData['level'];
                             $c->memberName = $memberData['name'];
+                            $c->listend = false; //关闭对 xhCustom 的 buyAmount 变动监听
                             $c->save();
 
                             // 更新客户所对应花店的消费金额