DeclarationUpgradeForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. $diffPerf = $this->nowPerf;
  122. if ($this->decWay != 2) {
  123. throw new Exception('升级方式不正确,请联系客服人员');
  124. }
  125. if($this->decWay==1) {
  126. // 先不加套餐升级方式
  127. // $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
  128. // $this->_decAmount = $decPackage['AMOUNT'];
  129. // $this->_decPv = $decPackage['PV'];
  130. // $this->_orderGoods[] = [
  131. // 'GOODS_ID' => $this->packageId,
  132. // 'PRICE' => $this->_decAmount,
  133. // 'REAL_PRICE' => $this->_decAmount,
  134. // 'PV' => $this->_decPv,
  135. // 'REAL_PV' => $this->_decPv,
  136. // 'BUY_NUMS' => 1,
  137. // 'SKU_CODE' => $decPackage['PACKAGE_NO'],
  138. // 'GOODS_TITLE' => $decPackage['PACKAGE_NAME']
  139. // ];
  140. } else {
  141. $ids = $this->goodsId;
  142. $totalAmount = 0;
  143. $totalPv = 0;
  144. foreach ($this->goodsNum as $k => $v) {
  145. if ($v) {
  146. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  147. if($goods['STORE_NUMS']>0){
  148. $totalAmount += $goods['SELL_PRICE'] * intval($v);
  149. $totalPv += $goods['PRICE_PV'] * intval($v);
  150. $this->_orderGoods[] = [
  151. 'GOODS_ID' => $goods['ID'],
  152. 'PRICE' => $goods['SELL_PRICE'],
  153. 'REAL_PRICE' => $goods['SELL_PRICE'],
  154. 'PV' => $goods['PRICE_PV'],
  155. 'REAL_PV' => $goods['PRICE_PV'],
  156. 'POINT' => $goods['POINT'],
  157. 'BUY_NUMS' => intval($v),
  158. 'SKU_CODE' => $goods['GOODS_NO'],
  159. 'GOODS_TITLE' => $goods['GOODS_NAME']
  160. ];
  161. }
  162. }
  163. }
  164. // 这里特殊是用户原报单PV之和+用户购买的商品总PV
  165. $checkPv = $totalPv + $diffPerf;
  166. if($checkPv < $decLevel['PERF']) {
  167. throw new Exception('总PV不能小于所选级别PV');
  168. }
  169. foreach ($decLevelConfig as $key=>$val){
  170. if($checkPv>=$val['PERF']){
  171. $toDecLevel = $key;
  172. }
  173. }
  174. if($this->decLv!=$toDecLevel){
  175. throw new Exception('总PV不能超过已选级别下一个级别的PV值');
  176. }
  177. $this->_decAmount = $totalAmount;
  178. $this->_decPv = $totalPv;
  179. }
  180. //看现金余额是否充足
  181. if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
  182. throw new Exception('报单人现金不足,无法完成报单');
  183. }
  184. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  185. $this->_insertUserId = $baseInfo['ID']; // 被报单人,通过insername 查找用户id
  186. $insertConId = $baseInfo['CON_UID'];
  187. $insertRecId = $baseInfo['REC_UID'];
  188. if(!($decResult = $this->addDecOrder($insertConId,$insertRecId, $baseInfo['DEC_LV'],$isObserve,$this->remark))) {
  189. throw new Exception("操作失败");
  190. }
  191. }
  192. return true;
  193. }
  194. /**
  195. * 添加报单订单
  196. * @return bool|UserInfo|null
  197. * @throws \yii\db\Exception
  198. */
  199. public function addDecOrder($insertConId,$insertRecId,$oriDecLv,$isObserve,$remark=''){
  200. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  201. if(!$warehouse){
  202. throw new Exception('地区暂时不支持配送,具体联系客服');
  203. }
  204. $upgradeType = $isObserve ? 1 : 2; // 1补差 2全额
  205. $periodObj = Period::instance();
  206. $nowPeriodNum = $periodObj->getNowPeriodNum();
  207. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  208. $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
  209. // 加入报单信息
  210. $db = \Yii::$app->db;
  211. $transaction = $db->beginTransaction();
  212. try {
  213. $decOrderModel = new DecOrder();
  214. $decOrderModel->DEC_SN = 'DS'.$ord;
  215. $decOrderModel->ORDER_SN = 'OS'.$ord;
  216. $decOrderModel->TYPE = $this->type;
  217. $decOrderModel->USER_ID = \Yii::$app->user->id; // 报单人
  218. $decOrderModel->TO_USER_ID = $this->_insertUserId; // 被报单人
  219. $decOrderModel->DEC_AMOUNT = $this->_decAmount;
  220. $decOrderModel->DEC_PV = $this->_decPv;
  221. $decOrderModel->PERIOD_NUM = $nowPeriodNum;
  222. $decOrderModel->CALC_MONTH = $nowCalcMonth;
  223. $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  224. $decOrderModel->PAID_WALLET = 'cash';
  225. $decOrderModel->CON_USER_ID = $insertConId;
  226. $decOrderModel->REC_USER_ID = $insertRecId;
  227. $decOrderModel->DEC_ID = $this->_decId;
  228. $decOrderModel->IS_DEL = 0;
  229. $decOrderModel->DETAIL_TYPE = 2;
  230. $decOrderModel->CREATED_AT = Date::nowTime();
  231. $decOrderModel->UPGRADE_TYPE = $upgradeType;
  232. $decOrderModel->REMARK = $remark;
  233. if(!$decOrderModel->save()){
  234. $transaction->rollBack();
  235. throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
  236. }
  237. $orderModel = new Order();
  238. $orderModel->SN = 'OS'.$ord;
  239. $orderModel->DEC_SN = 'DS'.$ord;
  240. $orderModel->ORDER_TYPE = $this->type;
  241. $orderModel->USER_ID = $this->_insertUserId;
  242. $orderModel->USER_NAME = $this->insertUserName; // 要升级的用户
  243. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  244. $orderModel->PV = $this->_decPv;
  245. $orderModel->PAY_AMOUNT = $this->_decAmount;
  246. $orderModel->PAY_PV = $this->_decPv;
  247. $orderModel->PAY_AT = Date::nowTime();
  248. $orderModel->PAY_TYPE = 'cash';
  249. $orderModel->PERIOD_NUM = $nowPeriodNum;
  250. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  251. $orderModel->FREIGHT = 0;
  252. $orderModel->PAY_FREIGHT = 0;
  253. $orderModel->CONSIGNEE = $this->consignee;
  254. $orderModel->MOBILE = $this->acceptMobile;
  255. $orderModel->PROVINCE = $this->province;
  256. $orderModel->CITY = $this->city;
  257. $orderModel->COUNTY = intval($this->county) ?? 0;
  258. $orderModel->ADDRESS = $this->address;
  259. $orderModel->WAREHOUSE = $warehouse;
  260. $orderModel->STATUS = 1;
  261. $orderModel->CREATED_AT = Date::nowTime();
  262. $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
  263. if(!$orderModel->save()){
  264. $transaction->rollBack();
  265. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  266. }
  267. // 加入商品到订单商品表
  268. foreach($this->_orderGoods as $key=>$value){
  269. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  270. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  271. }
  272. OrderGoods::batchInsert($this->_orderGoods);
  273. //写入收货地址信息
  274. $addressModel = new ReceiveAddress();
  275. $addressModel->USER_ID = $this->_insertUserId;
  276. $addressModel->USER_NAME = $this->insertUserName;
  277. $addressModel->CONSIGNEE = $this->consignee;
  278. $addressModel->MOBILE = $this->acceptMobile;
  279. $addressModel->PROVINCE = $this->province;
  280. $addressModel->CITY = $this->city;
  281. $addressModel->COUNTY = intval($this->county) ?? 0;
  282. $addressModel->ADDRESS = $this->address;
  283. $addressModel->IS_DEFAULT = 0;
  284. if(!$addressModel->save()){
  285. $transaction->rollBack();
  286. throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
  287. }
  288. // 扣报单人现金钱包
  289. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单']);
  290. // 为被升级人进行升级操作
  291. $decLevelLog = new DecLevelLog();
  292. $decLog = [
  293. 'userId' => $this->_insertUserId,//会员ID
  294. 'fromId' => $oriDecLv, // 变动前的级别
  295. 'levelId' => $this->decLv,// 变动后的级别
  296. 'actionId' => \Yii::$app->user->id,
  297. 'remark' => $this->remark,
  298. 'lvPv' => $this->_decPv
  299. ];
  300. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  301. if (empty($modifyDecLv)) {
  302. $transaction->rollBack();
  303. throw new Exception("为会员升级失败");
  304. }
  305. $transaction->commit();
  306. } catch(Exception $e) {
  307. $transaction->rollBack();
  308. throw new Exception($e->getMessage());
  309. return false;
  310. }
  311. return $modifyDecLv;
  312. }
  313. /**
  314. * 判断报单中心是否存在
  315. * @param $attribute
  316. */
  317. public function issetDec($attribute){
  318. $decUser = User::find()
  319. ->select('ID')
  320. ->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])
  321. ->asArray()
  322. ->one();
  323. if (!$decUser) {
  324. $this->addError($attribute, '报单中心不存在');
  325. return false;
  326. } else {
  327. // 判断报单中心是否在新加入会员的安置网上级中
  328. $this->loopFindParentToNetwork($this->insertUserName);
  329. //反转数组,in_array搜索错误
  330. //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
  331. $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
  332. if (!isset($flipParent[$this->decUserName])) {
  333. $this->addError($attribute, '为' . $this->insertUserName . '升级报单,报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
  334. return ;
  335. }
  336. $this->_decId = $decUser['ID'];
  337. }
  338. }
  339. // 判断是否已选择商品或套餐
  340. public function hasProduct($attribute) {
  341. if ($this->decWay==1 && empty($this->packageId)) {
  342. $this->addError($attribute, '购买套餐升级,请选择套餐');
  343. return false;
  344. }
  345. if ($this->decWay!=1 && empty($this->goodsId)) {
  346. $this->addError($attribute, '购买商品升级,请选择商品');
  347. return false;
  348. }
  349. return true;
  350. }
  351. // 判断要升级的会员,是否已是最高级别
  352. public function alreadyMaxDec($attribute) {
  353. $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
  354. $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
  355. $maxPerfInfo = DeclarationLevel::getMaxDecPref();
  356. $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
  357. if ($maxDecId == $userDecId) {
  358. $this->addError($attribute, '已是最高级别,无需升级');
  359. return false;
  360. }
  361. return true;
  362. }
  363. /**
  364. * 寻找被升级人的上级
  365. * @param null $conUserName
  366. * @return bool
  367. */
  368. private function loopFindParentToNetwork($conUserName = null) {
  369. if($conUserName == null ){
  370. $conUserName = $this->insertUserName;
  371. }
  372. $baseUser = Info::getBaseUserByUserName($conUserName);
  373. $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
  374. unset($baseUser);
  375. $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
  376. unset($userNetworkInfo);
  377. $allParentUserIds = array_reverse($allParentUserIdsArr);
  378. unset($allParentUserIdsArr);
  379. if($allParentUserIds){
  380. foreach($allParentUserIds as $parentUserId) {
  381. $parentBaseUser = Info::getBaseUserById($parentUserId);
  382. $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;
  383. unset($parentUserId, $parentBaseUser);
  384. }
  385. }
  386. unset($allParentUserIds);
  387. return true;
  388. }
  389. // /**
  390. // * 删单
  391. // * @return bool
  392. // * @throws \yii\db\Exception
  393. // */
  394. // public function delete(){
  395. // if(!$this->validate()){
  396. // return false;
  397. // }
  398. // $transaction = \Yii::$app->db->beginTransaction();
  399. // try {
  400. // $oneOrder = $this->_oneOrder;
  401. // // 首购单要删除会员
  402. // if($this->type == self::TYPE_ZC){
  403. // UserInfo::deleteUser($oneOrder['TO_USER_ID']);
  404. // }
  405. // // 如果是复销单的话,还需要考虑给会员的复销池减去金额
  406. // elseif($this->type == self::TYPE_FX){
  407. // Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
  408. // }
  409. // $transaction->commit();
  410. // } catch (Exception $e) {
  411. // $transaction->rollBack();
  412. // $this->addError('delete', $e->getMessage());
  413. // return false;
  414. // }
  415. // return true;
  416. // }
  417. }