ApproachOrderForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\helpers\Date;
  5. use common\components\Model;
  6. use common\helpers\Form;
  7. use common\helpers\PayStack;
  8. use common\helpers\user\Balance;
  9. use common\helpers\user\Cash;
  10. use common\helpers\user\Info;
  11. use common\libs\logging\operate\AdminOperate;
  12. use common\models\ApproachOrder;
  13. use common\models\ApproachOrderGoods;
  14. use common\models\DealType;
  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\UserNetwork;
  23. use yii\base\Exception;
  24. /**
  25. * Login form
  26. */
  27. class ApproachOrderForm extends Model
  28. {
  29. public $sn;
  30. public $expressCompany;
  31. public $orderTrackNo;
  32. public $status;
  33. public $remark;
  34. public $note;
  35. public $type;
  36. public $addressId;
  37. public $payType;
  38. public $goodsId;
  39. public $goodsNum;
  40. public $payPassword;
  41. public $email;
  42. public $userName;
  43. public $consignee;
  44. public $acceptMobile;
  45. public $province;
  46. public $city;
  47. public $county;
  48. public $lgaName;
  49. public $cityName;
  50. public $detailaddress;
  51. private $_address;
  52. private $_decAmount;
  53. private $_decPv;
  54. private $_freight;
  55. private $_payAmount;
  56. private $_orderGoods;
  57. /**
  58. * @var ApproachOrder
  59. */
  60. private $_model;
  61. public function init() {
  62. parent::init();
  63. $this->adminOperateLogger = new AdminOperate([
  64. 'fetchClass' => ApproachOrder::class,
  65. ]);
  66. }
  67. /**
  68. * @inheritdoc
  69. */
  70. public function rules()
  71. {
  72. return [
  73. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
  74. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
  75. [['status'], 'isStatus'],
  76. [['addressId'], 'isAddress'],
  77. [['payType'], 'isPayType'],
  78. [['payPassword'], 'validatePassword'],
  79. ];
  80. }
  81. public function attributeLabels()
  82. {
  83. return [
  84. 'sn' => '订单号',
  85. 'expressCompany' => '快递公司',
  86. 'orderTrackNo' => '快递单号',
  87. 'status' => '状态',
  88. 'remark' => '备注',
  89. 'type' => '订单类型',
  90. 'addressId' => '收货地址',
  91. 'payType' => '支付方式',
  92. 'goodsId' => '商品ID',
  93. 'goodsNum' => '商品数量',
  94. 'userName' => '复消会员编号',
  95. 'consignee' => '收货人',
  96. 'acceptMobile' => '收货电话',
  97. 'province' => '省',
  98. 'city' => '市',
  99. 'county' => '区',
  100. 'lgaName' => 'lga name',
  101. 'cityName' => 'City Name',
  102. 'detailaddress' => '收货详细地址',
  103. 'email' => 'Email',
  104. ];
  105. }
  106. /**
  107. * 指定校验场景
  108. * @return array
  109. */
  110. public function scenarios()
  111. {
  112. $parentScenarios = parent::scenarios();
  113. $customScenarios = [
  114. // 管理员修改订单状态
  115. 'adminStatus' => ['sn', 'status'],
  116. // 校验订单支付
  117. 'verifyPayStack' => ['sn', 'note'],
  118. // 会员下单
  119. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
  120. ];
  121. return array_merge($parentScenarios, $customScenarios);
  122. }
  123. /**
  124. * 校验之前
  125. * @return bool
  126. */
  127. public function beforeValidate()
  128. {
  129. $parentValidate = parent::beforeValidate();
  130. if ($this->sn) {
  131. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  132. if (!$this->_model){
  133. $this->addError('sn', '订单不存在');
  134. return false;
  135. }
  136. }
  137. if ($this->scenario == 'verifyPayStack'){
  138. if ($this->_model['STATUS'] != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  139. $this->addError('sn', '订单支付状态错误');
  140. return false;
  141. }
  142. }
  143. return $parentValidate;
  144. }
  145. /**
  146. * 判断收货地址是否存在
  147. * @param $attribute
  148. */
  149. public function isAddress($attribute){
  150. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  151. $this->addError($attribute, '收货地址不存在');
  152. } else {
  153. $this->_address = $receiveAddress;
  154. }
  155. }
  156. /**
  157. * 校验支付密码
  158. * @param $attribute
  159. * @param $params
  160. */
  161. public function validatePassword($attribute, $params) {
  162. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  163. $this->addError($attribute, '支付密码不正确');
  164. }
  165. }
  166. /**
  167. * 判断支付方式
  168. * @param $attribute
  169. */
  170. public function isPayType($attribute)
  171. {
  172. if ($this->payType != 'pay_stack'){
  173. $this->addError($attribute, '只允许PayStack方式支付');
  174. return;
  175. }
  176. // 一个订单只能包含一类商品
  177. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  178. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  179. if (count($goodsCategoryType) != 1) {
  180. $this->addError($attribute, '订单不能包含多种商品分类');
  181. return;
  182. }
  183. // 购买方式
  184. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  185. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  186. $this->addError($attribute, '不支持PayStack方式支付');
  187. return;
  188. }
  189. // 所选支付方式必须是商品分类支持的类型
  190. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  191. // 商品类型
  192. $currCategoryType = $goodsCategoryType[0];
  193. if (!array_key_exists($currCategoryType, $categoryType)) {
  194. $this->addError($attribute, '商品分类错误');
  195. return;
  196. }
  197. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  198. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  199. $this->addError($attribute, '支付方式错误3');
  200. }
  201. }
  202. /**
  203. * 校验类型
  204. * @param $attribute
  205. */
  206. public function isStatus($attribute){
  207. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  208. $this->addError($attribute, '类型错误');
  209. return ;
  210. }
  211. if ($this->scenario == 'adminStatus'){
  212. if ($this->status == $this->_model['STATUS']) {
  213. $this->addError($attribute, '订单状态没有改变');
  214. return ;
  215. }
  216. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  217. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  218. return ;
  219. }
  220. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  221. $this->addError($attribute, '订单已失效不能处理');
  222. return ;
  223. }
  224. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  225. $this->addError($attribute, '订单不能单独处理为物流状态');
  226. return ;
  227. }
  228. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  229. $this->addError($attribute, '订单已失效不能处理');
  230. return ;
  231. }
  232. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  233. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  234. $this->addError($attribute, '订单已完成不能取消');
  235. return ;
  236. }
  237. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  238. $this->addError($attribute, '订单已删除不能取消');
  239. return ;
  240. }
  241. }
  242. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  243. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  244. $this->addError($attribute, '订单已完成不能删除');
  245. return ;
  246. }
  247. }
  248. }
  249. }
  250. /**
  251. * 校验PayStack支付,更新订单状态.同步到正式订单.
  252. * @throws Exception
  253. */
  254. public function verifyPayStack(): ?ApproachOrder
  255. {
  256. if (!$this->validate()) {
  257. return null;
  258. }
  259. // 调用PayStack支付校验
  260. $payload = PayStack::transactionVerify($this->remark['reference']);
  261. if ($payload['status'] !== true) {
  262. throw new Exception(Form::formatErrorsForApi($payload['message']));
  263. }
  264. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  265. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  266. }
  267. $db = \Yii::$app->db;
  268. $transaction = $db->beginTransaction();
  269. try {
  270. // 更新准订单状态为已支付
  271. $this->_model->STATUS = \Yii::$app->params['orderStatus']['paid']['value'];
  272. $this->_model->NOTE = json_encode($this->remark);
  273. $this->_model->PAY_AT = Date::nowTime();
  274. $this->_model->EMAIL = $this->email;
  275. if (!$this->_model->save()) {
  276. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  277. }
  278. // 更新订单商品的支付Email
  279. ApproachOrderGoods::updateAll(['EMAIL' => $this->email], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  280. // 同步准订单到正式订单
  281. Order::insertOne($this->_model->toArray());
  282. // 同步准订单商品到正式订单商品
  283. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  284. foreach ($approachOrderGoods as &$approachOrderGood) {
  285. $approachOrderGood['EMAIL'] = $this->email;
  286. }
  287. OrderGoods::batchInsert($approachOrderGoods);
  288. $transaction->commit();
  289. } catch (Exception $e) {
  290. $transaction->rollBack();
  291. $this->addError('edit', $e->getMessage());
  292. return null;
  293. }
  294. return $this->_model;
  295. }
  296. /**
  297. * 复销
  298. * @throws Exception
  299. * @throws \yii\db\Exception
  300. */
  301. public function add(){
  302. if(!$this->validate()){
  303. return null;
  304. }
  305. $ids = $this->goodsId;
  306. $totalAmount = 0;
  307. $totalPv = 0;
  308. $goodsType = ShopGoods::GOODS_TYPE;
  309. foreach ($this->goodsNum as $k => $v) {
  310. if ($v) {
  311. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  312. if($goods['STORE_NUMS']>0){
  313. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  314. $discount = $goodsType[$goods['TYPE']]['discount'];
  315. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  316. $realPv = $goods['PRICE_PV'] * $discount/100;
  317. } else {
  318. $discount = $goods['SELL_DISCOUNT'];
  319. $realPrice = $goods['SELL_PRICE'] * $discount;
  320. $realPv = $goods['PRICE_PV'] * $discount;
  321. }
  322. $totalAmount += $realPrice * intval($v);
  323. $totalPv += $realPv * intval($v);
  324. $this->_orderGoods[] = [
  325. 'GOODS_ID' => $goods['ID'],
  326. 'PRICE' => $goods['SELL_PRICE'],
  327. 'PV' => $goods['PRICE_PV'],
  328. 'REAL_PRICE' => $realPrice,
  329. 'REAL_PV' => $realPv,
  330. 'POINT' => $goods['POINT'],
  331. 'BUY_NUMS' => intval($v),
  332. 'SKU_CODE' => $goods['GOODS_NO'],
  333. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  334. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  335. 'PAY_TYPE' => $this->payType,
  336. 'EMAIL' => $this->email,
  337. ];
  338. }
  339. }
  340. }
  341. $this->_decAmount = $totalAmount;
  342. $this->_decPv = $totalPv;
  343. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  344. if($this->_address['PROVINCE']==1){
  345. $this->_freight = 0;
  346. }
  347. $this->_payAmount = $this->_decAmount + $this->_freight;
  348. $db = \Yii::$app->db;
  349. $transaction = $db->beginTransaction();
  350. try {
  351. //写入订单
  352. if (!$orderResult = $this->addOrder()) {
  353. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  354. }
  355. $transaction->commit();
  356. return $orderResult;
  357. }catch (\Exception $e){
  358. $transaction->rollBack();
  359. $this->addError('add', $e->getMessage());
  360. return null;
  361. }
  362. }
  363. /**
  364. * 复销订单
  365. * @throws Exception
  366. */
  367. public function addOrder()
  368. {
  369. $periodObj = Period::instance();
  370. $nowPeriodNum = $periodObj->getNowPeriodNum();
  371. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  372. $userId = \Yii::$app->user->id;
  373. $userName = Info::getUserNameByUserId($userId);
  374. $userRealName = Info::getUserRealNameByUserId($userId);
  375. $userMobile = Info::getUserMobileByUserId($userId);
  376. $userEmail = Info::getUserEmailByUserId($userId);
  377. // 加入订单信息
  378. if ($this->_address['PROVINCE'] != 1) {
  379. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  380. if (!$warehouse) {
  381. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  382. }
  383. }else{
  384. $warehouse = '01';
  385. }
  386. $_hasPV = $this->_decPv;
  387. $ordNo = $this->_generateSn();
  388. $orderModel = new ApproachOrder();
  389. $orderModel->SN = 'OS' . $ordNo;
  390. $orderModel->DEC_SN = 'DS' . $ordNo;
  391. $orderModel->ORDER_TYPE = $this->type;
  392. $orderModel->USER_ID = $userId;
  393. $orderModel->USER_NAME = $userName;
  394. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  395. $orderModel->PV = $_hasPV;
  396. $orderModel->PAY_AMOUNT = $this->_payAmount;
  397. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  398. $orderModel->PAY_AT = 0;
  399. $orderModel->PAY_TYPE = $this->payType;
  400. $orderModel->PERIOD_NUM = $nowPeriodNum;
  401. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  402. $orderModel->FREIGHT = $this->_freight;
  403. $orderModel->PAY_FREIGHT = $this->_freight;
  404. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  405. $orderModel->MOBILE = $this->_address['MOBILE'];
  406. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  407. // $orderModel->CITY = $this->_address['CITY'];
  408. // $orderModel->COUNTY = $this->_address['COUNTY'];
  409. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  410. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  411. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  412. $orderModel->FRONT_REMARK = $this->remark;
  413. $orderModel->WAREHOUSE = $warehouse;
  414. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  415. $orderModel->CREATED_AT = Date::nowTime();
  416. $orderModel->CREATE_USER = $userName;
  417. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
  418. if($this->_address['PROVINCE']==1){
  419. $orderModel->EXPRESS_TYPE = 1;
  420. $orderModel->CONSIGNEE = $userRealName;
  421. $orderModel->MOBILE = $userMobile;
  422. $orderModel->PROVINCE = 1;
  423. $orderModel->CITY = 1;
  424. $orderModel->COUNTY = 1;
  425. $orderModel->ADDRESS = '';
  426. }
  427. if(!$orderModel->save()){
  428. $this->addErrors($orderModel->getErrors());
  429. return false;
  430. }
  431. // 加入商品到订单商品表
  432. foreach($this->_orderGoods as $key=>$value) {
  433. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  434. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  435. }
  436. ApproachOrderGoods::batchInsert($this->_orderGoods);
  437. // TODO: 记录流水
  438. return $orderModel;
  439. }
  440. /**
  441. * 生成流水号
  442. * @return string
  443. */
  444. private function _generateSn() {
  445. return Date::today('Ymd') . $this->_random(10, 1);
  446. }
  447. /**
  448. * 生成随机数
  449. * @param $length
  450. * @param int $numeric
  451. * @return string
  452. */
  453. private function _random($length, $numeric = 0) {
  454. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  455. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  456. $hash = '';
  457. $max = strlen($seed) - 1;
  458. for ($i = 0; $i < $length; $i++) {
  459. $hash .= $seed[mt_rand(0, $max)];
  460. }
  461. return $hash;
  462. }
  463. }