BaDeclarationForm.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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\Reconsume;
  9. use common\helpers\user\Info;
  10. use common\models\DeclarationPackage;
  11. use common\models\BaDecOrder;
  12. use common\models\EmployLevel;
  13. use common\models\BaOrder;
  14. use common\models\BaOrderGoods;
  15. use common\models\Period;
  16. use common\models\ReceiveAddress;
  17. use common\models\ReconsumePool;
  18. use common\models\ReconsumePoolFlow;
  19. use common\models\DeclarationLevel;
  20. use common\models\Region;
  21. use common\models\ShopGoods;
  22. use common\models\BaUser;
  23. use common\models\BaUserInfo;
  24. use common\models\UserNetwork;
  25. use common\models\UserRelation;
  26. use yii\base\Exception;
  27. /**
  28. * Login form
  29. */
  30. class BaDeclarationForm extends Model
  31. {
  32. public $type;
  33. public $decLv;
  34. public $decWay;
  35. public $packageId;
  36. public $goodsId;
  37. public $goodsNum;
  38. public $insertUserName;
  39. public $password;
  40. public $payPassword;
  41. public $realName;
  42. public $insertUserIdCard;
  43. public $mobile;
  44. public $email;
  45. public $address;
  46. public $openBank;
  47. public $bankAddress;
  48. public $bankNo;
  49. public $bankProvince;
  50. public $bankCity;
  51. public $bankCounty;
  52. public $conUserName;
  53. public $recUserName;
  54. public $decUserName;
  55. public $location;
  56. public $consignee;
  57. public $acceptMobile;
  58. public $province;
  59. public $city;
  60. public $county;
  61. public $cityName;
  62. public $lgaName;
  63. // 传过来的全部数据
  64. public $allData;
  65. private $_decId;
  66. public $_insertUserId;
  67. private $_decAmount;
  68. // private $_decPv;
  69. private $_orderGoods;
  70. // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
  71. const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';
  72. const TYPE_ZC = 'ZC';
  73. // const TYPE_YH = 'YH';
  74. const TYPE_ZG = 'ZG';
  75. const TYPE_LS = 'LS';
  76. const TYPE_FX = 'FX';
  77. // private $_modelClass = null;
  78. private $_oneOrder = null;
  79. private $_userForm = null;
  80. // 全部的上级(安置网和开拓网)
  81. private $_tempParentUser = [];
  82. // 全部的安置网上级
  83. private $_tempNetworkParentUser = [];
  84. // 全部的开拓网上级
  85. private $_tempRelationParentUser = [];
  86. private $_types = [
  87. self::TYPE_ZC => [
  88. 'name' => '首购单',
  89. ],
  90. // self::TYPE_YH => [
  91. // 'class' => DeclarationYH::class,
  92. // 'table' => '{{%DECLARATION_YH}}',
  93. // 'name' => '优惠单',
  94. // ],
  95. self::TYPE_ZG => [
  96. 'name' => '升级增购单',
  97. ],
  98. self::TYPE_LS => [
  99. 'name' => '零售单',
  100. ],
  101. self::TYPE_FX => [
  102. 'name' => '复销单',
  103. ],
  104. ];
  105. /**
  106. * @inheritdoc
  107. */
  108. public function rules()
  109. {
  110. return [
  111. [['type','decLv','decWay','packageId', 'insertUserName', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','cityName','lgaName','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
  112. [['type','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
  113. // [['type'], 'isType', 'on'=>['userDec', 'canDec']],
  114. // [['insertUserName'], 'isCanAddUser'],
  115. // [['decUserName'], 'issetDec'],
  116. // [['conUserName'], 'isConUserName'],
  117. // [['recUserName'], 'isRecUserName'],
  118. // [['location'], 'isLocation'],
  119. // [['insertUserIdCard'], 'isSameSystem'],
  120. ];
  121. }
  122. public function attributeLabels()
  123. {
  124. return [
  125. 'type' => 'Entry type', // 报单类型
  126. 'goodsId' => 'product ID', // 商品ID
  127. 'goodsNum' => 'Product quantity', // 商品数量
  128. 'insertUserName' => 'Member user name', // 会员用户名
  129. 'password' => 'Login password', // 登陆密码
  130. 'payPassword' => 'Payment password', // 支付密码
  131. 'realName' => 'Member name', // 会员姓名
  132. 'mobile' => 'Phone Number', // 手机号
  133. 'recUserName' => 'Developer user name', // 开拓人用户名
  134. 'decUserName' => 'Stockist user name', // 报单中心用户名
  135. 'conUid' => 'Instructor Member ID', // 指导老师会员ID
  136. 'recUid' => 'Sponsor Member ID', // 开拓人会员ID
  137. 'location' => 'market', // 市场
  138. 'consignee' => 'Recipient', // 收货人
  139. 'acceptMobile' => 'Recipient Phone Number', // 收货人手机
  140. 'province' => 'Receiving Province',//收货省
  141. 'address' => 'Receiving detailed address',//收货详细地址
  142. ];
  143. }
  144. /**
  145. * 指定场景
  146. * @return array
  147. */
  148. public function scenarios()
  149. {
  150. $parentScenarios = parent::scenarios();
  151. $customScenarios = [
  152. 'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName', 'mobile', 'address', 'consignee','acceptMobile','province','decUserName', 'location', 'email'],
  153. ];
  154. return array_merge($parentScenarios, $customScenarios);
  155. }
  156. /**
  157. * 判断报单中心是否存在
  158. * @param $attribute
  159. */
  160. public function issetDec($attribute){
  161. if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
  162. $this->addError($attribute, 'Stockist does not exist'); // 报单中心不存在
  163. return false;
  164. } else {
  165. $this->_decId = $decUser['ID'];
  166. }
  167. }
  168. /**
  169. * 添加报单
  170. * @param $allData
  171. * @return bool|null
  172. * @throws Exception
  173. * @throws \yii\db\Exception
  174. */
  175. public function add($allData){
  176. if(!$this->validate()){
  177. return null;
  178. }
  179. // 首购单,需要添加会员操作
  180. if($this->type == self::TYPE_ZC){
  181. if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) { // 判断字符串中是否有中文
  182. throw new Exception('Member number cannot contain Chinese characters'); // 会员编号中不能含有汉字
  183. }
  184. // //报单商品及PV判断
  185. // $decLevelConfig = Cache::getDecLevelConfig();
  186. // $decLevel = $decLevelConfig[$this->decLv];
  187. // $toDecLevel = $this->decLv;
  188. // if(!$this->decLv){
  189. // throw new Exception('Please select the entry level'); // 请选择报单级别
  190. // }
  191. if($this->decWay==1) {
  192. // $decPackage = BaDeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
  193. // $this->_decAmount = $decPackage['AMOUNT'];
  194. // $this->_decPv = $decPackage['PV'];
  195. // $this->_orderGoods[] = [
  196. // 'GOODS_ID' => $this->packageId,
  197. // 'PRICE' => $this->_decAmount,
  198. // 'REAL_PRICE' => $this->_decAmount,
  199. // 'PV' => $this->_decPv,
  200. // 'REAL_PV' => $this->_decPv,
  201. // 'BUY_NUMS' => 1,
  202. // 'SKU_CODE' => $decPackage['PACKAGE_NO'],
  203. // 'GOODS_TITLE' => $decPackage['PACKAGE_NAME'],
  204. // 'EMAIL' => $this->email
  205. // ];
  206. }else{
  207. $ids = $this->goodsId;
  208. $totalAmount = 0;
  209. $totalPv = 0;
  210. foreach ($this->goodsNum as $k => $v) {
  211. if ($v) {
  212. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  213. if($goods['STORE_NUMS']>0){
  214. $totalAmount += $goods['SELL_PRICE'] * intval($v);
  215. $totalPv += $goods['PRICE_PV'] * intval($v);
  216. $this->_orderGoods[] = [
  217. 'GOODS_ID' => $goods['ID'],
  218. 'PRICE' => $goods['SELL_PRICE'],
  219. 'REAL_PRICE' => $goods['SELL_PRICE'],
  220. 'PV' => $goods['PRICE_PV'],
  221. 'REAL_PV' => $goods['PRICE_PV'],
  222. 'POINT' => $goods['POINT'],
  223. 'BUY_NUMS' => intval($v),
  224. 'SKU_CODE' => $goods['GOODS_NO'],
  225. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  226. 'EMAIL' => $this->email,
  227. 'TAX_RATE' => $goods['TAX_RATE'],
  228. ];
  229. }
  230. }
  231. }
  232. // if($totalPv<$decLevel['PERF']){
  233. // throw new Exception('The total BV of self selected goods cannot be less than the BV of the selected entry level');//自选商品总BV不能小于所选报单级别BV
  234. // }
  235. // foreach ($decLevelConfig as $key=>$val){
  236. // if($totalPv>=$val['PERF']){
  237. // $toDecLevel = $key;
  238. // }
  239. // }
  240. // if($this->decLv!=$toDecLevel){
  241. // throw new Exception('The total BV of self selected goods cannot exceed the BV value of the next level under the selected level');//自选商品总BV不能超过已选级别下一个级别的BV值
  242. // }
  243. $this->_decAmount = $totalAmount;
  244. // $this->_decPv = $totalPv;
  245. }
  246. //看现金余额是否充足
  247. $loginUserId = \Yii::$app->user->id;
  248. if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
  249. throw new Exception('The applicant is short of cash and cannot complete the declaration');//报单人现金不足,无法完成报单
  250. }
  251. if(!($zcResult = $this->addBaUser($allData))) {
  252. throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
  253. }
  254. if(!($decResult = $this->addBaDecOrder())) {
  255. throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
  256. }
  257. }
  258. return true;
  259. }
  260. /**
  261. * 添加会员
  262. * @param $allData
  263. * @return bool|UserInfo|null
  264. * @throws \yii\db\Exception
  265. */
  266. public function addBaUser($allData){
  267. $period = Period::instance();
  268. // 增加会员
  269. $user = new BaUser();
  270. $user->USER_NAME = $this->insertUserName;
  271. $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
  272. $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
  273. $user->NATION = 0;
  274. $user->REAL_NAME = $this->realName;
  275. $user->ID_CARD = $this->mobile;
  276. $user->MOBILE = $this->mobile;
  277. $user->EMAIL = $this->email;
  278. $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
  279. // $user->OPEN_BANK = $this->openBank;
  280. // $user->BANK_ADDRESS = $this->bankAddress;
  281. // $user->BANK_NO = $this->bankNo;
  282. // $user->BANK_PROVINCE = $this->bankProvince ?? 0;
  283. // $user->BANK_CITY = $this->bankCity ?? 0;
  284. // $user->BANK_COUNTY = $this->bankCounty ?? 0;
  285. $user->CREATED_AT = Date::nowTime();
  286. $user->STATUS = 1;
  287. // $user->DEC_LV = $this->decLv;
  288. // $user->LAST_DEC_LV = $this->decLv;
  289. // $user->EMP_LV = EmployLevel::getDefaultLevelId();
  290. $user->PROVINCE = $this->province ?? 0;
  291. $user->LGA_NAME = $this->lgaName;
  292. $user->CITY_NAME = $this->cityName;
  293. $user->AVATAR = 'avatar/1.png';
  294. $user->IS_DEC = 0;
  295. $user->DEC_ID = $this->_decId ?? null;
  296. $user->DEC_ROLE_ID = $this->decRoleId ?? null;
  297. $user->PERIOD_AT = $period->getNowPeriodNum();
  298. $user->IS_DIRECT_SELLER = 0;
  299. $user->VERIFIED = 1;
  300. $user->VERIFIED_AT = Date::nowTime();
  301. if (!$user->save()) {
  302. throw new Exception(Form::formatErrorsForApi($user->getErrors()));
  303. }
  304. $this->_insertUserId = $user->ID;
  305. $userForm = new BaUserForm();
  306. $this->_userForm = $userForm;
  307. $userForm->scenario = 'addWithUserName';
  308. $userForm->userId = $this->_insertUserId;
  309. $userForm->userName = $this->insertUserName;
  310. // $userForm->zcPv = $this->_decPv;
  311. // $userForm->zcAmount = $this->_decAmount;
  312. // $userForm->conUserName = $this->conUserName;
  313. $userForm->recUserName = $this->recUserName;
  314. // $userForm->location = $this->location;
  315. $userForm->idCard = $this->mobile;
  316. $userForm->allData = $allData;
  317. if(!$userForm->validate()){
  318. $this->addErrors($userForm->getErrors());
  319. return false;
  320. }
  321. if($result = $userForm->add()){
  322. return $result;
  323. } else {
  324. return false;
  325. }
  326. }
  327. /**
  328. * 添加报单订单
  329. * @return bool|UserInfo|null
  330. * @throws \yii\db\Exception
  331. */
  332. public function addBaDecOrder(){
  333. $periodObj = Period::instance();
  334. $nowPeriodNum = $periodObj->getNowPeriodNum();
  335. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  336. $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
  337. // 加入报单信息
  338. $decOrderModel = new BaDecOrder();
  339. $decOrderModel->DEC_SN = 'DS'.$ord;
  340. $decOrderModel->ORDER_SN = 'OS'.$ord;
  341. $decOrderModel->TYPE = $this->type;
  342. $decOrderModel->USER_ID = \Yii::$app->user->id;
  343. $decOrderModel->TO_USER_ID = $this->_insertUserId;
  344. $decOrderModel->DEC_AMOUNT = $this->_decAmount;
  345. $decOrderModel->DEC_PV = $this->_decPv;
  346. $decOrderModel->PERIOD_NUM = $nowPeriodNum;
  347. $decOrderModel->CALC_MONTH = $nowCalcMonth;
  348. $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  349. $decOrderModel->PAID_WALLET = 'cash';
  350. $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
  351. $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
  352. $decOrderModel->DEC_ID = $this->_decId;
  353. $decOrderModel->IS_DEL = 0;
  354. $decOrderModel->CREATED_AT = Date::nowTime();
  355. if(!$decOrderModel->save()){
  356. throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
  357. }
  358. // 加入订单信息
  359. if($this->province!=1){
  360. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  361. if(!$warehouse){
  362. throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');//地区暂时不支持配送,具体联系客服
  363. }
  364. }else{
  365. $warehouse = '01';
  366. }
  367. $orderModel = new BaOrder();
  368. $orderModel->SN = 'OS'.$ord;
  369. $orderModel->DEC_SN = 'DS'.$ord;
  370. $orderModel->ORDER_TYPE = $this->type;
  371. $orderModel->USER_ID = $this->_insertUserId;
  372. $orderModel->USER_NAME = $this->insertUserName;
  373. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  374. $orderModel->PV = $this->_decPv;
  375. $orderModel->PAY_AMOUNT = $this->_decAmount;
  376. $orderModel->PAY_PV = $this->_decPv;
  377. $orderModel->PAY_AT = Date::nowTime();
  378. $orderModel->PAY_TYPE = 'cash';
  379. $orderModel->PERIOD_NUM = $nowPeriodNum;
  380. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  381. $orderModel->FREIGHT = 0;
  382. $orderModel->PAY_FREIGHT = 0;
  383. $orderModel->CONSIGNEE = $this->consignee;
  384. $orderModel->MOBILE = $this->acceptMobile;
  385. $orderModel->EMAIL = $this->email;
  386. $orderModel->PROVINCE = $this->province;
  387. $orderModel->LGA_NAME = $this->lgaName;
  388. $orderModel->CITY_NAME = $this->cityName;
  389. $orderModel->ADDRESS = $this->address;
  390. $orderModel->WAREHOUSE = $warehouse;
  391. $orderModel->STATUS = 1;
  392. $orderModel->CREATED_AT = Date::nowTime();
  393. $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
  394. if($this->province==1){
  395. $orderModel->EXPRESS_TYPE = 1;
  396. }
  397. if(!$orderModel->save()){
  398. throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
  399. }
  400. // 加入商品到订单商品表
  401. foreach($this->_orderGoods as $key=>$value){
  402. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  403. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  404. }
  405. BaOrderGoods::batchInsert($this->_orderGoods);
  406. //写入收货地址信息,判断province字段,当不为1时,插入收货地址信息
  407. if($this->province!=1){
  408. $addressModel = new ReceiveAddress();
  409. $addressModel->USER_ID = $this->_insertUserId;
  410. $addressModel->USER_NAME = $this->insertUserName;
  411. $addressModel->CONSIGNEE = $this->consignee;
  412. $addressModel->MOBILE = $this->acceptMobile;
  413. $addressModel->PROVINCE = $this->province;
  414. $addressModel->CITY_NAME = $this->cityName;
  415. $addressModel->LGA_NAME = $this->lgaName;
  416. $addressModel->ADDRESS = $this->address;
  417. $addressModel->IS_DEFAULT = 1;
  418. if(!$addressModel->save()){
  419. throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
  420. }
  421. //扣报单人现金钱包
  422. // Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单']);
  423. Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']);
  424. return $addressModel;
  425. }else{
  426. $addressModel = new ReceiveAddress();
  427. return $addressModel;
  428. }
  429. }
  430. /**
  431. * 删单
  432. * @return bool
  433. * @throws \yii\db\Exception
  434. */
  435. public function delete(){
  436. if(!$this->validate()){
  437. return false;
  438. }
  439. $transaction = \Yii::$app->db->beginTransaction();
  440. try {
  441. $oneOrder = $this->_oneOrder;
  442. // 首购单要删除会员
  443. if($this->type == self::TYPE_ZC){
  444. BaUserInfo::deleteUser($oneOrder['TO_USER_ID']);
  445. }
  446. // 如果是复销单的话,还需要考虑给会员的复销池减去金额
  447. elseif($this->type == self::TYPE_FX){
  448. // Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
  449. Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
  450. }
  451. $transaction->commit();
  452. } catch (Exception $e) {
  453. $transaction->rollBack();
  454. $this->addError('delete', $e->getMessage());
  455. return false;
  456. }
  457. return true;
  458. }
  459. }