ApproachOrderForm.php 17 KB

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