DeclarationUpgradeForm.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. namespace common\models\forms;
  3. use common\components\Model;
  4. use common\helpers\Cache;
  5. use common\helpers\Date;
  6. use common\helpers\Form;
  7. use common\helpers\user\Cash;
  8. use common\helpers\user\Info;
  9. use common\models\Config;
  10. use common\models\DeclarationLevel;
  11. use common\models\DeclarationPackage;
  12. use common\models\DecLevelLog;
  13. use common\models\DecOrder;
  14. use common\models\EmployLevel;
  15. use common\models\Order;
  16. use common\models\OrderGoods;
  17. use common\models\Period;
  18. use common\models\ReceiveAddress;
  19. use common\models\Region;
  20. use common\models\ShopGoods;
  21. use common\models\User;
  22. use common\models\UserInfo;
  23. use common\models\UserNetwork;
  24. use yii\base\Exception;
  25. /**
  26. * 升级管理,进行升级
  27. */
  28. class DeclarationUpgradeForm extends Model
  29. {
  30. public $type;
  31. public $decLv;
  32. public $decWay;
  33. public $packageId;
  34. public $goodsId;
  35. public $goodsNum;
  36. public $insertUserName;
  37. public $consignee;
  38. public $acceptMobile;
  39. public $province;
  40. public $city;
  41. public $county;
  42. public $address;
  43. public $nowPerf;
  44. public $nextPerf;
  45. public $decUserName;
  46. public $remark;
  47. // 传过来的全部数据
  48. public $allData;
  49. private $_decId;
  50. public $_insertUserId;
  51. private $_decAmount;
  52. private $_decPv;
  53. private $_orderGoods;
  54. const TYPE_ZC = 'ZC';
  55. private $_userForm = null;
  56. // 全部的安置网上级
  57. private $_tempNetworkParentUser = [];
  58. /**
  59. * @inheritdoc
  60. */
  61. public function rules()
  62. {
  63. return [
  64. [['remark','type','decLv','decWay','packageId','goodsId', 'goodsNum', 'insertUserName','consignee','acceptMobile','province','city','county','address','nowPerf','nextPerf'], 'trim'],
  65. [['type','decLv','decWay','insertUserName','nowPerf','province','city','county','address','acceptMobile'], 'required'],
  66. [['decUserName'], 'issetDec'], // 必须是报单中心
  67. [['decWay'], 'hasProduct'],// 必须选择商品
  68. [['decLv'], 'alreadyMaxDec'], //判断要升级用户是否已经是最高级
  69. ];
  70. }
  71. public function attributeLabels()
  72. {
  73. return [
  74. 'type' => '升级类型',
  75. 'decLv' => '升级级别',
  76. 'decWay' => '报单方式',
  77. 'packageId' => '升级套餐',
  78. 'goodsId' => '商品ID',
  79. 'goodsNum' => '商品数量',
  80. 'insertUserName' => '要升级的会员编号',
  81. 'consignee' => '收货人',
  82. 'acceptMobile' => '收货人手机',
  83. 'province' => '收货省',
  84. 'city' => '收货市',
  85. 'county' => '收货区县',
  86. 'address' => '收货详细地址',
  87. ];
  88. }
  89. /**
  90. * 添加报单
  91. * @param $allData
  92. * @return bool|null
  93. * @throws Exception
  94. * @throws \yii\db\Exception
  95. */
  96. public function add($allData){
  97. if(!$this->validate()){
  98. return null;
  99. }
  100. $loginUserId = \Yii::$app->user->id;
  101. // 首购单
  102. if($this->type == self::TYPE_ZC){
  103. //报单商品及PV判断
  104. $decLevelConfig = Cache::getDecLevelConfig();
  105. $decLevel = $decLevelConfig[$this->decLv];
  106. $toDecLevel = $this->decLv;
  107. if(!$this->decLv){
  108. throw new Exception('请选择升级级别');
  109. }
  110. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  111. $userId = $baseInfo['ID'];
  112. $userDecPvSum = User::sumDevPvByUserId($userId); // 用户所有报单PV总和
  113. if ($userDecPvSum != $this->nowPerf) {
  114. throw new Exception('请联系客服人员核对升级会员业绩');
  115. }
  116. // 获取用户是否是观察期
  117. $observe = Config::getConfigByType('observe'); // 获取观察期配置信息
  118. $observeLimit = $observe['observePeriodLimit']['value']; // 月份限制
  119. $isObserve = User::checkIsObserve($baseInfo['CREATED_AT'], $observeLimit); // 判断用户是否再观察期中
  120. $diffPerf = $isObserve ? $this->nowPerf : 0; // 观察期内升级要加上用户累计的PV,全额则基础PV为0,全额购买
  121. if ($this->decWay != 2) {
  122. throw new Exception('升级方式不正确,请联系客服人员');
  123. }
  124. if($this->decWay==1) {
  125. // 先不加套餐升级方式
  126. // $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
  127. // $this->_decAmount = $decPackage['AMOUNT'];
  128. // $this->_decPv = $decPackage['PV'];
  129. // $this->_orderGoods[] = [
  130. // 'GOODS_ID' => $this->packageId,
  131. // 'PRICE' => $this->_decAmount,
  132. // 'REAL_PRICE' => $this->_decAmount,
  133. // 'PV' => $this->_decPv,
  134. // 'REAL_PV' => $this->_decPv,
  135. // 'BUY_NUMS' => 1,
  136. // 'SKU_CODE' => $decPackage['PACKAGE_NO'],
  137. // 'GOODS_TITLE' => $decPackage['PACKAGE_NAME']
  138. // ];
  139. } else {
  140. $ids = $this->goodsId;
  141. $totalAmount = 0;
  142. $totalPv = 0;
  143. foreach ($this->goodsNum as $k => $v) {
  144. if ($v) {
  145. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  146. if (!$goods) {
  147. throw new Exception('商品不存在');
  148. }
  149. if($goods['STORE_NUMS']>0){
  150. $totalAmount += $goods['SELL_PRICE'] * intval($v);
  151. $totalPv += $goods['PRICE_PV'] * intval($v);
  152. $this->_orderGoods[] = [
  153. 'GOODS_ID' => $goods['ID'],
  154. 'PRICE' => $goods['SELL_PRICE'],
  155. 'REAL_PRICE' => $goods['SELL_PRICE'],
  156. 'PV' => $goods['PRICE_PV'],
  157. 'REAL_PV' => $goods['PRICE_PV'],
  158. 'POINT' => $goods['POINT'],
  159. 'BUY_NUMS' => intval($v),
  160. 'SKU_CODE' => $goods['GOODS_NO'],
  161. 'GOODS_TITLE' => $goods['GOODS_NAME']
  162. ];
  163. }
  164. }
  165. }
  166. // 这里特殊是用户原报单PV之和+用户购买的商品总PV
  167. $checkPv = $totalPv + $diffPerf;
  168. if($checkPv < $decLevel['PERF']) {
  169. throw new Exception('总PV不能小于所选级别PV');
  170. }
  171. foreach ($decLevelConfig as $key=>$val){
  172. if($checkPv>=$val['PERF']){
  173. $toDecLevel = $key;
  174. }
  175. }
  176. if($this->decLv!=$toDecLevel){
  177. throw new Exception('总PV不能超过已选级别下一个级别的PV值');
  178. }
  179. $this->_decAmount = $totalAmount;
  180. $this->_decPv = $totalPv;
  181. }
  182. //看现金余额是否充足
  183. if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
  184. throw new Exception('报单人现金不足,无法完成报单');
  185. }
  186. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  187. $this->_insertUserId = $baseInfo['ID']; // 被报单人,通过insername 查找用户id
  188. $insertConId = $baseInfo['CON_UID'];
  189. $insertRecId = $baseInfo['REC_UID'];
  190. if(!($decResult = $this->addDecOrder($insertConId,$insertRecId, $baseInfo['DEC_LV'],$isObserve,$this->remark))) {
  191. throw new Exception("操作失败");
  192. }
  193. }
  194. return true;
  195. }
  196. /**
  197. * 添加报单订单
  198. * @return bool|UserInfo|null
  199. * @throws \yii\db\Exception
  200. */
  201. public function addDecOrder($insertConId,$insertRecId,$oriDecLv,$isObserve,$remark=''){
  202. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  203. if(!$warehouse){
  204. throw new Exception('地区暂时不支持配送,具体联系客服');
  205. }
  206. $upgradeType = $isObserve ? 1 : 2; // 1补差 2全额
  207. $periodObj = Period::instance();
  208. $nowPeriodNum = $periodObj->getNowPeriodNum();
  209. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  210. $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
  211. // 加入报单信息
  212. $db = \Yii::$app->db;
  213. $transaction = $db->beginTransaction();
  214. try {
  215. $decOrderModel = new DecOrder();
  216. $decOrderModel->DEC_SN = 'DS'.$ord;
  217. $decOrderModel->ORDER_SN = 'OS'.$ord;
  218. $decOrderModel->TYPE = $this->type;
  219. $decOrderModel->USER_ID = \Yii::$app->user->id; // 报单人
  220. $decOrderModel->TO_USER_ID = $this->_insertUserId; // 被报单人
  221. $decOrderModel->DEC_AMOUNT = $this->_decAmount;
  222. $decOrderModel->DEC_PV = $this->_decPv;
  223. $decOrderModel->PERIOD_NUM = $nowPeriodNum;
  224. $decOrderModel->CALC_MONTH = $nowCalcMonth;
  225. $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  226. $decOrderModel->PAID_WALLET = 'cash';
  227. $decOrderModel->CON_USER_ID = $insertConId;
  228. $decOrderModel->REC_USER_ID = $insertRecId;
  229. $decOrderModel->DEC_ID = $this->_decId;
  230. $decOrderModel->IS_DEL = 0;
  231. $decOrderModel->DETAIL_TYPE = 2;
  232. $decOrderModel->CREATED_AT = Date::nowTime();
  233. $decOrderModel->UPGRADE_TYPE = $upgradeType;
  234. $decOrderModel->REMARK = $remark;
  235. $decOrderModel->ORI_LV = $oriDecLv; // 变更前的级别
  236. $decOrderModel->UPGRADE_LV = $this->decLv; // 变更后的级别
  237. if(!$decOrderModel->save()){
  238. $transaction->rollBack();
  239. throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
  240. }
  241. $orderModel = new Order();
  242. $orderModel->SN = 'OS'.$ord;
  243. $orderModel->DEC_SN = 'DS'.$ord;
  244. $orderModel->ORDER_TYPE = $this->type;
  245. $orderModel->USER_ID = $this->_insertUserId;
  246. $orderModel->USER_NAME = $this->insertUserName; // 要升级的用户
  247. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  248. $orderModel->PV = $this->_decPv;
  249. $orderModel->PAY_AMOUNT = $this->_decAmount;
  250. $orderModel->PAY_PV = $this->_decPv;
  251. $orderModel->PAY_AT = Date::nowTime();
  252. $orderModel->PAY_TYPE = 'cash';
  253. $orderModel->PERIOD_NUM = $nowPeriodNum;
  254. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  255. $orderModel->FREIGHT = 0;
  256. $orderModel->PAY_FREIGHT = 0;
  257. $orderModel->CONSIGNEE = $this->consignee;
  258. $orderModel->MOBILE = $this->acceptMobile;
  259. $orderModel->PROVINCE = $this->province;
  260. $orderModel->CITY = $this->city;
  261. $orderModel->COUNTY = intval($this->county) ?? 0;
  262. $orderModel->ADDRESS = $this->address;
  263. $orderModel->WAREHOUSE = $warehouse;
  264. $orderModel->STATUS = 1;
  265. $orderModel->CREATED_AT = Date::nowTime();
  266. $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
  267. if(!$orderModel->save()){
  268. $transaction->rollBack();
  269. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  270. }
  271. /**
  272. * 2022-05-10
  273. * York
  274. */
  275. foreach ($this->goodsNum as $k => $v) {
  276. if ($v) {
  277. $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $this->goodsId[$k]]);
  278. if (!$goods) {
  279. throw new Exception('商品不存在');
  280. }
  281. $storenums = $goods['STORE_NUMS'] - $this->goodsNum[$k];
  282. if($goods['STATUS']==1){
  283. if($goods['STORE_NUMS'] >=$this->goodsNum[$k]){
  284. $data = ShopGoods::find()->where(['ID' => $this->goodsId[$k]])->one();
  285. $data->STORE_NUMS = $storenums;
  286. $data->update();
  287. if ($storenums==0){
  288. $data->STATUS = 0;
  289. $data->UPDATED_AT = Date::nowTime();
  290. $data->update();
  291. }
  292. }else{
  293. throw new Exception("商品".$goods['GOODS_NAME']."库存不足");
  294. }
  295. }else{
  296. throw new Exception("商品".$goods['GOODS_NAME']."已下架");
  297. }
  298. }
  299. }
  300. // 加入商品到订单商品表
  301. foreach($this->_orderGoods as $key=>$value){
  302. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  303. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  304. }
  305. OrderGoods::batchInsert($this->_orderGoods);
  306. //写入收货地址信息
  307. $addressModel = new ReceiveAddress();
  308. $addressModel->USER_ID = $this->_insertUserId;
  309. $addressModel->USER_NAME = $this->insertUserName;
  310. $addressModel->CONSIGNEE = $this->consignee;
  311. $addressModel->MOBILE = $this->acceptMobile;
  312. $addressModel->PROVINCE = $this->province;
  313. $addressModel->CITY = $this->city;
  314. $addressModel->COUNTY = intval($this->county) ?? 0;
  315. $addressModel->ADDRESS = $this->address;
  316. $addressModel->IS_DEFAULT = 0;
  317. if(!$addressModel->save()){
  318. $transaction->rollBack();
  319. throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
  320. }
  321. // 扣报单人现金钱包
  322. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单']);
  323. // 为被升级人进行升级操作
  324. $decLevelLog = new DecLevelLog();
  325. $decLog = [
  326. 'userId' => $this->_insertUserId,//会员ID
  327. 'fromId' => $oriDecLv, // 变动前的级别
  328. 'levelId' => $this->decLv,// 变动后的级别
  329. 'actionId' => \Yii::$app->user->id,
  330. 'remark' => $this->remark,
  331. 'lvPv' => $this->_decPv
  332. ];
  333. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  334. if (empty($modifyDecLv)) {
  335. $transaction->rollBack();
  336. throw new Exception("为会员升级失败");
  337. }
  338. $transaction->commit();
  339. } catch(Exception $e) {
  340. $transaction->rollBack();
  341. throw new Exception($e->getMessage());
  342. return false;
  343. }
  344. return $modifyDecLv;
  345. }
  346. /**
  347. * 判断报单中心是否存在
  348. * @param $attribute
  349. */
  350. public function issetDec($attribute){
  351. $decUser = User::find()
  352. ->select('ID')
  353. ->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])
  354. ->asArray()
  355. ->one();
  356. if (!$decUser) {
  357. $this->addError($attribute, '报单中心不存在');
  358. return false;
  359. } else {
  360. // 判断报单中心是否在新加入会员的安置网上级中
  361. $this->loopFindParentToNetwork($this->insertUserName);
  362. //反转数组,in_array搜索错误
  363. //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
  364. // $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
  365. // if (!isset($flipParent[$this->decUserName])) {
  366. // $this->addError($attribute, '为' . $this->insertUserName . '升级报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
  367. // return ;
  368. // }
  369. $this->_decId = $decUser['ID'];
  370. }
  371. }
  372. // 判断是否已选择商品或套餐
  373. public function hasProduct($attribute) {
  374. if ($this->decWay==1 && empty($this->packageId)) {
  375. $this->addError($attribute, '购买套餐升级,请选择套餐');
  376. return false;
  377. }
  378. if ($this->decWay!=1 && empty($this->goodsId)) {
  379. $this->addError($attribute, '购买商品升级,请选择商品');
  380. return false;
  381. }
  382. return true;
  383. }
  384. // 判断要升级的会员,是否已是最高级别
  385. public function alreadyMaxDec($attribute) {
  386. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  387. $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
  388. $maxPerfInfo = DeclarationLevel::getMaxDecPref();
  389. $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
  390. if ($maxDecId == $userDecId) {
  391. $this->addError($attribute, '已是最高级别,无需升级');
  392. return false;
  393. }
  394. return true;
  395. }
  396. /**
  397. * 寻找被升级人的上级
  398. * @param null $conUserName
  399. * @return bool
  400. */
  401. private function loopFindParentToNetwork($conUserName = null) {
  402. if($conUserName == null ){
  403. $conUserName = $this->insertUserName;
  404. }
  405. $baseUser = Info::getBaseUserByUserName($conUserName);
  406. $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
  407. unset($baseUser);
  408. $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
  409. unset($userNetworkInfo);
  410. $allParentUserIds = array_reverse($allParentUserIdsArr);
  411. unset($allParentUserIdsArr);
  412. if($allParentUserIds){
  413. foreach($allParentUserIds as $parentUserId) {
  414. $parentBaseUser = Info::getBaseUserById($parentUserId);
  415. $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
  416. unset($parentUserId, $parentBaseUser);
  417. }
  418. }
  419. unset($allParentUserIds);
  420. return true;
  421. }
  422. // /**
  423. // * 删单
  424. // * @return bool
  425. // * @throws \yii\db\Exception
  426. // */
  427. // public function delete(){
  428. // if(!$this->validate()){
  429. // return false;
  430. // }
  431. // $transaction = \Yii::$app->db->beginTransaction();
  432. // try {
  433. // $oneOrder = $this->_oneOrder;
  434. // // 首购单要删除会员
  435. // if($this->type == self::TYPE_ZC){
  436. // UserInfo::deleteUser($oneOrder['TO_USER_ID']);
  437. // }
  438. // // 如果是复销单的话,还需要考虑给会员的复销池减去金额
  439. // elseif($this->type == self::TYPE_FX){
  440. // Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
  441. // }
  442. // $transaction->commit();
  443. // } catch (Exception $e) {
  444. // $transaction->rollBack();
  445. // $this->addError('delete', $e->getMessage());
  446. // return false;
  447. // }
  448. // return true;
  449. // }
  450. }