| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519 |
- <?php
- namespace common\models\forms;
- use common\helpers\Cache;
- use common\helpers\Date;
- use common\components\Model;
- use common\helpers\Form;
- use common\helpers\LoggerTool;
- use common\helpers\PayStack;
- use common\helpers\user\Balance;
- use common\helpers\user\Cash;
- use common\helpers\user\Info;
- use common\libs\logging\operate\AdminOperate;
- use common\models\ApproachOrder;
- use common\models\ApproachOrderGoods;
- use common\models\DealType;
- use common\models\Order;
- use common\models\OrderGoods;
- use common\models\Period;
- use common\models\ReceiveAddress;
- use common\models\Region;
- use common\models\ShopGoods;
- use common\models\User;
- use common\models\UserNetwork;
- use yii\base\Exception;
- /**
- * Login form
- */
- class ApproachOrderForm extends Model
- {
- public $sn;
- public $expressCompany;
- public $orderTrackNo;
- public $status;
- public $remark;
- public $note;
- public $type;
- public $addressId;
- public $payType;
- public $goodsId;
- public $goodsNum;
- public $payPassword;
- public $email;
- public $userName;
- public $consignee;
- public $acceptMobile;
- public $province;
- public $city;
- public $county;
- public $lgaName;
- public $cityName;
- public $detailaddress;
- private $_address;
- private $_decAmount;
- private $_decPv;
- private $_freight;
- private $_payAmount;
- private $_orderGoods;
- /**
- * @var ApproachOrder
- */
- private $_model;
- public function init() {
- parent::init();
- $this->adminOperateLogger = new AdminOperate([
- 'fetchClass' => ApproachOrder::class,
- ]);
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
- [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
- [['status'], 'isStatus'],
- [['addressId'], 'isAddress'],
- [['payType'], 'isPayType'],
- [['payPassword'], 'validatePassword'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'sn' => 'Order code',//订单号
- 'expressCompany' => 'ExpressCompany',//快递公司
- 'orderTrackNo' => 'courier number',//快递单号
- 'status' => 'status',//状态
- 'remark' => 'remark',//备注
- 'type' => 'order type',//订单类型
- 'addressId' => 'addressId',//收货地址
- 'payType' => 'payType',//支付方式
- 'goodsId' => 'Product ID',
- 'goodsNum' => 'Product quantity',//
- 'userName' => '复消会员编号',//复消会员编号
- 'consignee' => '收货人',//收货人
- 'acceptMobile' => '收货电话',//收货电话
- 'province' => '省',
- 'city' => '市',
- 'county' => '区',
- 'lgaName' => 'lga name',
- 'cityName' => 'City Name',
- 'detailaddress' => '收货详细地址',
- 'email' => 'Email',
- ];
- }
- /**
- * 指定校验场景
- * @return array
- */
- public function scenarios()
- {
- $parentScenarios = parent::scenarios();
- $customScenarios = [
- // 管理员修改订单状态
- 'adminStatus' => ['sn', 'status'],
- // 校验订单支付
- 'verifyPayStack' => ['sn', 'note', 'status'],
- // 会员下单
- 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
- ];
- return array_merge($parentScenarios, $customScenarios);
- }
- /**
- * 校验之前
- * @return bool
- */
- public function beforeValidate()
- {
- $parentValidate = parent::beforeValidate();
- if ($this->sn) {
- $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
- if (!$this->_model){
- $this->addError('sn', '订单不存在');
- return false;
- }
- }
- if ($this->scenario == 'verifyPayStack'){
- if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
- $this->addError('sn', '订单支付状态错误');
- return false;
- }
- }
- return $parentValidate;
- }
- /**
- * 判断收货地址是否存在
- * @param $attribute
- */
- public function isAddress($attribute){
- if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
- $this->addError($attribute, '收货地址不存在');
- } else {
- $this->_address = $receiveAddress;
- }
- }
- /**
- * 校验支付密码
- * @param $attribute
- * @param $params
- */
- public function validatePassword($attribute, $params) {
- if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
- $this->addError($attribute, '支付密码不正确');
- }
- }
- /**
- * 判断支付方式
- * @param $attribute
- */
- public function isPayType($attribute)
- {
- if ($this->payType != 'pay_stack'){
- $this->addError($attribute, '只允许PayStack方式支付');
- return;
- }
- // 一个订单只能包含一类商品
- $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
- $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
- if (count($goodsCategoryType) != 1) {
- $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
- return;
- }
- // 购买方式
- $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
- if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
- $this->addError($attribute, '不支持PayStack方式支付');
- return;
- }
- // 所选支付方式必须是商品分类支持的类型
- $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
- // 商品类型
- $currCategoryType = $goodsCategoryType[0];
- if (!array_key_exists($currCategoryType, $categoryType)) {
- $this->addError($attribute, '商品分类错误');
- return;
- }
- $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
- if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
- $this->addError($attribute, '支付方式错误3');
- }
- }
- /**
- * 校验类型
- * @param $attribute
- */
- public function isStatus($attribute){
- if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
- $this->addError($attribute, '订单状态类型错误');
- return ;
- }
- if ($this->scenario == 'adminStatus'){
- if ($this->status == $this->_model['STATUS']) {
- $this->addError($attribute, '订单状态没有改变');
- return ;
- }
- if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
- $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
- return ;
- }
- elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
- $this->addError($attribute, '订单已失效不能处理');
- return ;
- }
- elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
- $this->addError($attribute, '订单不能单独处理为物流状态');
- return ;
- }
- elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
- $this->addError($attribute, '订单已失效不能处理');
- return ;
- }
- elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
- if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
- $this->addError($attribute, '订单已完成不能取消');
- return ;
- }
- if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
- $this->addError($attribute, '订单已删除不能取消');
- return ;
- }
- }
- elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
- if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
- $this->addError($attribute, '订单已完成不能删除');
- return ;
- }
- }
- }
- }
- /**
- * 校验PayStack支付,更新订单状态.同步到正式订单.
- * @throws Exception
- */
- public function verifyPayStack(): ?ApproachOrder
- {
- if (!$this->validate()) {
- return null;
- }
- // 调用PayStack支付校验
- LoggerTool::info([$this->note['reference'], $this->note]);
- $payload = PayStack::transactionVerify($this->note['reference']);
- LoggerTool::info($payload);
- if ($payload['status'] !== true) {
- throw new Exception(Form::formatErrorsForApi($payload['message']));
- }
- if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
- throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
- }
- $db = \Yii::$app->db;
- $transaction = $db->beginTransaction();
- try {
- // 更新准订单状态为已支付
- $this->_model->STATUS = $this->status;
- $this->_model->NOTE = json_encode($this->note);
- $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
- $this->_model->EMAIL = $this->note['email'];
- if (!$this->_model->save()) {
- throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
- }
- // 更新订单商品的支付Email
- ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
- // 同步准订单到正式订单
- Order::insertOne($this->_model->toArray());
- // 同步准订单商品到正式订单商品
- $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
- foreach ($approachOrderGoods as &$approachOrderGood) {
- $approachOrderGood['EMAIL'] = $this->email;
- }
- OrderGoods::batchInsert($approachOrderGoods);
- $transaction->commit();
- } catch (Exception $e) {
- $transaction->rollBack();
- $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
- return null;
- }
- return $this->_model;
- }
- /**
- * 复销
- * @throws Exception
- * @throws \yii\db\Exception
- */
- public function add(){
- if(!$this->validate()){
- return null;
- }
- $ids = $this->goodsId;
- $totalAmount = 0;
- $totalPv = 0;
- $goodsType = ShopGoods::GOODS_TYPE;
- foreach ($this->goodsNum as $k => $v) {
- if ($v) {
- $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
- if($goods['STORE_NUMS']>0){
- if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
- $discount = $goodsType[$goods['TYPE']]['discount'];
- $realPrice = $goods['SELL_PRICE'] * $discount/100;
- $realPv = $goods['PRICE_PV'] * $discount/100;
- } else {
- $discount = $goods['SELL_DISCOUNT'];
- $realPrice = $goods['SELL_PRICE'] * $discount;
- $realPv = $goods['PRICE_PV'] * $discount;
- }
- $totalAmount += $realPrice * intval($v);
- $totalPv += $realPv * intval($v);
- $this->_orderGoods[] = [
- 'GOODS_ID' => $goods['ID'],
- 'PRICE' => $goods['SELL_PRICE'],
- 'PV' => $goods['PRICE_PV'],
- 'REAL_PRICE' => $realPrice,
- 'REAL_PV' => $realPv,
- 'POINT' => $goods['POINT'],
- 'BUY_NUMS' => intval($v),
- 'TAX_RATE' => $goods['TAX_RATE'],
- 'SKU_CODE' => $goods['GOODS_NO'],
- 'GOODS_TITLE' => $goods['GOODS_NAME'],
- 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
- 'PAY_TYPE' => $this->payType,
- 'EMAIL' => $this->email,
- ];
- }
- }
- }
- // 汇率
- $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
- // 运费.美元转奈拉
- $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
- // 普通商品免运费阈值.美元转奈拉
- $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
- $this->_decAmount = $totalAmount;
- $this->_decPv = $totalPv;
- $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
- if($this->_address['PROVINCE']==1){
- $this->_freight = 0;
- }
- $this->_payAmount = $this->_decAmount + $this->_freight;
- $db = \Yii::$app->db;
- $transaction = $db->beginTransaction();
- try {
- //写入订单
- if (!$orderResult = $this->addOrder()) {
- throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
- }
- $transaction->commit();
- return $orderResult;
- }catch (\Exception $e){
- $transaction->rollBack();
- $this->addError('add', $e->getMessage());
- return null;
- }
- }
- /**
- * 复销订单
- * @throws Exception
- */
- public function addOrder()
- {
- $periodObj = Period::instance();
- $nowPeriodNum = $periodObj->getNowPeriodNum();
- $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
- $userId = \Yii::$app->user->id;
- $userName = Info::getUserNameByUserId($userId);
- $userRealName = Info::getUserRealNameByUserId($userId);
- $userMobile = Info::getUserMobileByUserId($userId);
- $userEmail = Info::getUserEmailByUserId($userId);
- // 加入订单信息
- if ($this->_address['PROVINCE'] != 1) {
- $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
- if (!$warehouse) {
- // throw new Exception('地区2暂时不支持配送,具体联系客服');
- }
- }else{
- $warehouse = '01';
- }
- $_hasPV = $this->_decPv;
- $ordNo = $this->_generateSn();
- $orderModel = new ApproachOrder();
- $orderModel->SN = 'OS' . $ordNo;
- $orderModel->DEC_SN = 'DS' . $ordNo;
- $orderModel->ORDER_TYPE = $this->type;
- $orderModel->USER_ID = $userId;
- $orderModel->USER_NAME = $userName;
- $orderModel->ORDER_AMOUNT = $this->_decAmount;
- $orderModel->PV = $_hasPV;
- $orderModel->PAY_AMOUNT = $this->_payAmount;
- $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
- $orderModel->PAY_AT = 0;
- $orderModel->PAY_TYPE = $this->payType;
- $orderModel->PERIOD_NUM = $nowPeriodNum;
- $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
- $orderModel->FREIGHT = $this->_freight;
- $orderModel->PAY_FREIGHT = $this->_freight;
- $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
- $orderModel->MOBILE = $this->_address['MOBILE'];
- $orderModel->PROVINCE = $this->_address['PROVINCE'];
- // $orderModel->CITY = $this->_address['CITY'];
- // $orderModel->COUNTY = $this->_address['COUNTY'];
- $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
- $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
- $orderModel->ADDRESS = $this->_address['ADDRESS'];
- $orderModel->FRONT_REMARK = $this->remark;
- $orderModel->WAREHOUSE = $warehouse;
- $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
- $orderModel->CREATED_AT = Date::nowTime();
- $orderModel->CREATE_USER = $userName;
- $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
- if($this->_address['PROVINCE']==1){
- $orderModel->EXPRESS_TYPE = 1;
- $orderModel->CONSIGNEE = $userRealName;
- $orderModel->MOBILE = $userMobile;
- $orderModel->PROVINCE = 1;
- $orderModel->CITY = 1;
- $orderModel->COUNTY = 1;
- $orderModel->ADDRESS = '';
- }
- if(!$orderModel->save()){
- $this->addErrors($orderModel->getErrors());
- return false;
- }
- // 加入商品到订单商品表
- foreach($this->_orderGoods as $key=>$value) {
- $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
- $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
- }
- ApproachOrderGoods::batchInsert($this->_orderGoods);
- // TODO: 记录流水
- return $orderModel;
- }
- /**
- * 生成流水号
- * @return string
- */
- private function _generateSn() {
- return Date::today('Ymd') . $this->_random(10, 1);
- }
- /**
- * 生成随机数
- * @param $length
- * @param int $numeric
- * @return string
- */
- private function _random($length, $numeric = 0) {
- $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
- $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
- $hash = '';
- $max = strlen($seed) - 1;
- for ($i = 0; $i < $length; $i++) {
- $hash .= $seed[mt_rand(0, $max)];
- }
- return $hash;
- }
- }
|