ApproachOrderForm.php 19 KB

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