'上午', 1 => '下午', 2 => '晚上'];
//优惠金额
public static $randDiscount = [
50 => [1, 3],
100 => [5, 9],
300 => [10, 15],
500 => [16, 18],
1000 => [18, 30],
20000 => [90, 100],
];
//因为开负数订单时引导库存变化 ssh 20250731
public static function shPayChange($order, $shop, $staff, $originOrder = null)
{
$forward = $order['forward'] ?? 0;
if ($forward == 0) {
return false;
}
$forwardStock = $order['forwardStock'] ?? 0;
$orderSn = $order['orderSn'] ?? '';
$orderItemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
$orderGoodsList = OrderGoodsClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
if (empty($orderItemList) && empty($orderGoodsList)) {
return false;
}
$shopId = $shop->id ?? 0;
$sjId = $shop->sjId ?? 0;
$adminId = $staff->adminId;
$staffName = $staff->name ?? '';
$mainId = $shop->mainId;
if (!empty($orderItemList)) {
$itemInfo = [];
$ids = array_column($orderItemList, 'itemId');
$infoList = ProductClass::getAllByCondition(['id' => ['in', $ids]], null, '*', 'id');
foreach ($orderItemList as $orderItem) {
$unitType = $orderItem['unitType'] ?? 0;
$num = $orderItem['num'] ?? 0;
$productId = $orderItem['itemId'] ?? 0;
$info = $infoList[$productId] ?? [];
$stock = $info['stock'] ?? 0;
$ratio = $info['ratio'] ?? 20;
$map = ProductClass::formatStock($stock, $ratio);
$bigNum = $map['bigNum'] ?? 0;
$smallNum = $map['smallNum'] ?? 0;
$num = $forwardStock == 0 ? $num * 2 : $num;
if ($unitType == 0) {
$bigNum = $bigNum + $num;
} else {
$smallNum = $smallNum + $num;
}
$itemInfo[] = ['productId' => $productId, 'bigNum' => $bigNum, 'smallNum' => $smallNum];
}
$remark = $forwardStock == 0 ? '开售后付款单,退货并退款' : '开售后付款单,只退款';
$itemData = [
'remark' => $remark,
'itemInfo' => $itemInfo,
'sjId' => $sjId,
'shopId' => $shopId,
'adminId' => $adminId,
'staffName' => $staffName,
];
CheckOrderClass::opOrder($itemData);
}
if (!empty($orderGoodsList)) {
foreach ($orderGoodsList as $orderGoods) {
$goodsId = $orderGoods['goodsId'] ?? 0;
$num = $orderGoods['num'] ?? 0;
$num = $forwardStock == 0 ? $num * 2 : $num;
$ret = \bizHd\goods\classes\GoodsClass::addStock($goodsId, $mainId, $num);
$oldStock = $ret['oldStock'] ?? 0;
$newStock = $ret['newStock'] ?? 0;
$recordData = [];
$recordData['sjId'] = $sjId;
$recordData['shopId'] = $shopId;
$recordData['mainId'] = $mainId;
$recordData['orderSn'] = '';
$recordData['goodsId'] = $goodsId;
$recordData['goodsNum'] = $num;
$recordData['oldStock'] = $oldStock;
$recordData['newStock'] = $newStock;
$recordData['relateName'] = $staffName;
GoodsStockRecordClass::pdGoods($recordData);
}
}
if (is_object($order) && !empty($originOrder)) {
//建立关系
$originOrder->hasForward = 1;
$originOrder->save();
$orderId = $originOrder->id ?? 0;
$orderSn = $originOrder->orderSn ?? '';
$shOrderId = $order->id ?? 0;
$shOrderSn = $order->orderSn ?? '';
$map = ['orderId' => $orderId, 'orderSn' => $orderSn, 'shOrderId' => $shOrderId, 'shOrderSn' => $shOrderSn];
OrderForwardClass::add($map, true);
}
return true;
}
/**
* @param $order
* @param $mainId
* @return array
* $shAddPay 0走正常流程售后,1走售后付款单
* $shAddPayReason 走售后付款单的原因:0、售后金额大于剩余欠款(剩余欠款可能没有了,可能还有);1、可售后时间到了
*/
public static function ifShPay($order, $main, $refundAmount = 0)
{
$shAddPay = 0;
$shAddPayReason = 0;
$payStatus = $order['payStatus'] ?? 0;
if ($payStatus == 1) {
if ($order['payWay'] == 3) {
if ($order['remainDebtPrice'] <= 0) {
//不管是否要售后,没有剩余欠款了,只能走开负数订单模式
$shAddPay = 1;
} else {
if ($refundAmount > 0 && $refundAmount > $order['remainDebtPrice']) {
//如果需要售后,并且售后金额大于剩余欠款,走开负数订单模式
$shAddPay = 1;
}
}
}
$cRet = OrderClass::couldRefund($order, $main);
$could = $cRet['could'];
if (!$could) {
//可售后时间到了
$shAddPay = 1;
$shAddPayReason = 1;
}
}
return ['shAddPay' => $shAddPay, 'shAddPayReason' => $shAddPayReason];
}
//订单是否过了可以售后的时间 ssh 20250730
// $could false 过了售后时间,不能售后,true可以
public static function couldRefund($order, $main)
{
$refundLimit = $main->refundLimit ?? 0;
$payTime = $order['payTime'];
$currentPayTime = strtotime($payTime);
$addDateTime = $refundLimit * 86400;
$couldRefundTime = $currentPayTime + $addDateTime;
$now = time();
$could = $couldRefundTime > $now;
return ['could' => $could];
}
public static function valid($order, $mainId)
{
if (!isset($order->mainId) || $order->mainId != $mainId) {
Yii::info(json_encode($order));
Yii::info('mainId: ' . $mainId);
util::fail('无法访问的订单');
}
return true;
}
//添加订单 ssh 2019.12.5
public static function addOrder($data)
{
$data['orderSn'] = $data['orderSn'] ?? orderSn::getOrderSn();
$data['payStatus'] = $data['payStatus'] ?? 0;
$shopId = $data['shopId'] ?? 0;
//累计订单增加
$shop = ShopClass::getLockById($shopId);
if (empty($shop)) {
util::fail('没有找到门店信息54');
}
$mainId = $shop->mainId ?? 0;
$main = MainClass::getLockById($mainId);
if (empty($main)) {
util::fail('没有找到main信息');
}
$main->unPayOrder += 1;
$main->totalOrder += 1;
$main->save();
$address = $data['address'] ?? '';
$floor = $data['floor'] ?? '';
if (empty($data['fullAddress'])) {
$data['fullAddress'] = $address . $floor;
}
$sendType = $data['sendType'] ?? 0;
if ($sendType == 1) {
//到店自取,客户自己下单,不会有到店自取时间,但是如果是花店后台接单,会填到店自取时间,重要!!!!!!!!阿东那边已经出问题了!!!
if (empty($data['reachDate'])) {
$data['reachDate'] = date("Y-m-d");
}
if (empty($data['reachPeriod'])) {
$data['reachPeriod'] = '22:00';
}
} else {
//如果不是到店自取的,则必须要有配送时间,默认当天
$data['reachDate'] = !empty($data['reachDate']) ? $data['reachDate'] : date("Y-m-d");
if (empty($data['reachPeriod'])) {
util::fail('请选择配送时间');
}
}
$data['reachTime'] = strtotime($data['reachDate'] . ' ' . $data['reachPeriod']);
$book = $data['book'] ?? 0;
if ($book == 0) {
$actPrice = $data['actPrice'];
$meetNum = $shop->meetNum ?? 0;
$meetAmount = $shop->meetAmount ?? 0;
$cutOption = $shop->cutAmount ?? 0;
$cutStyle = $shop->cutStyle ?? 0;
if ($cutStyle == 0) {
$cutAmount = $cutOption;
} else {
$miniOption = bcsub(1, $cutOption, 2);
$cutAmount = bcmul($actPrice, $miniOption, 2);
}
if ($cutAmount > 0 && $meetNum >= 0 && $meetAmount > 0) {
if (isset($data['bigNum']) && $data['bigNum'] >= $meetNum && $data['actPrice'] >= $meetAmount) {
if ($cutAmount < $actPrice) {
$actPrice = bcsub($actPrice, $cutAmount, 2);
$data['orderReachDiscountPrice'] = $cutAmount;
$data['actPrice'] = $actPrice;
$data['realPrice'] = $actPrice;
$data['mainPay'] = $actPrice;
} else {
noticeUtil::push('订单金额不足满减金额,customId:' . $data['customId'], '15280215347');
}
}
}
}
//将花店每月的总订单数作为编号
$riseNum = StatOrderCountClass::addOrder($shop, $main);
$data['sendNum'] = date("j") . $riseNum;
$data['totalFlow'] = OrderClass::ORDER_TOTAL_FLOW;
$salt = stringUtil::charsShuffleLowerCase(10);
$data['salt'] = $salt;
return self::add($data, true);
}
public static function getByOrderSn($orderSn)
{
return self::getByCondition(['orderSn' => $orderSn]);
}
//评价 ssh 2019.12.16
public static function comment($data)
{
$id = $data['id'];
unset($data['id']);
return self::updateById($id, $data);
}
public static function getFullInfo($id)
{
$order = self::getById($id);
if (empty($order)) {
return [];
}
$sn = $order['orderSn'] ?? '';
$order['goodsInfoList'] = OrderGoodsClass::getListBySn($sn);
$order['itemInfoList'] = OrderItemClass::getListBySn($sn);
$workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*');
if (!empty($workList)) {
foreach ($workList as $key => $work) {
$shortCover = $work['cover'] ?? '';
$workList[$key]['shortCover'] = $shortCover;
$workList[$key]['smallCover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
}
}
$order['workList'] = $workList;
$debtPrice = $order['debtPrice'] ?? 0;
$remainDebtPrice = $order['remainDebtPrice'] ?? 0;
$orderId = $order['id'] ?? 0;
$osList = [];
if ($debtPrice > $remainDebtPrice) {
$osList = OrderSettleClass::getAllByCondition(['orderId' => $orderId, 'status' => 1], null, '*', null, true);
}
//结账记录关系
$order['orderSettleList'] = $osList;
$order['today'] = date("Y-m-d");
$order['tomorrow'] = date("Y-m-d", strtotime("+1 day"));
return $order;
}
//订单
public static function getOrderById($id)
{
$order = self::getById($id);
if (empty($order)) {
return [];
}
$sn = $order['orderSn'] ?? '';
$order['goodsInfoList'] = OrderGoodsClass::getListBySn($sn);
return $order;
}
//根据订单查询 ssh 2020.1.4
public static function getOrderBySn($orderSn)
{
$order = self::getByCondition(['orderSn' => $orderSn]);
if (empty($order)) {
return [];
}
$id = $order['id'];
$order['goodsInfoList'] = OrderGoodsClass::getGoodsListById($id);
return $order;
}
//返回随机优惠金额 ssh 2019.9.12
public static function getRandDiscount($amount)
{
if ($amount <= 0) {
return 0;
}
$randDiscount = self::$randDiscount;
krsort($randDiscount);
$rand = 0;
foreach ($randDiscount as $currentAmount => $val) {
if ($amount >= $currentAmount) {
$rand = rand($val[0], $val[1]);
break;
}
}
return $rand / 10;
}
//第三方支付后回调处理流程 ssh 2021.4.30
public static function thirdPay($payWay, $orderSn, $totalFee, $attach, $transactionId)
{
$order = self::getByCondition(['orderSn' => $orderSn], true);
if (empty($order)) {
noticeUtil::push('散客下单,付款成功,支付回调,单号:' . $orderSn . ' 金额:' . $totalFee . ' 回调id:' . $transactionId . ' 附件:' . $attach . ',没有找到订单', '15280215347');
$msg = "没有找到零售订单 orderSn:{$orderSn}";
Yii::info($msg);
util::fail($msg);
}
if ($order->mainPay != $totalFee) {
noticeUtil::push("散客下单,付款成功,支付回调错误,零售订单金额与回调通知金额不一致 orderSn:{$orderSn} {$order->mainPay} {$totalFee} 附件:{$attach}", '15280215347');
$msg = "零售订单金额与回调通知金额不一致 orderSn:{$orderSn} {$order->mainPay} {$totalFee}";
Yii::info($msg);
util::fail($msg);
}
$id = $order->id;
$order = self::getLockById($id);
$date = date("Y-m-d H:i:s");
$order->payTime = $date;
$order->thirdNo = $transactionId;
$order->onlinePay = dict::getDict('onlinePay', 'yes');
$order->save();
$params = [];
self::payAfter($order, $payWay, $params);
}
//订单完成 ssh 2021.4.20
public static function payAfter($order, $payWay, $params = [])
{
if (empty($order)) {
util::fail('没有找到订单');
}
if (!isset($order->status)) {
util::fail('没有找到订单的状态');
}
$orderSn = $order->orderSn ?? '';
if ($order->status == self::ORDER_STATUS_CANCEL) {
$shopId = $order->shopId;
$shop = ShopClass::getById($shopId, true);
if (empty($shop)) {
noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功但订单已取消,没有找到门店,关键词 cancel_get_money', '15280215347');
util::stop("SUCCESS");
}
Yii::$app->params['errorReport'] = 1;
try {
//恢复取消的订单
self::recoverOrderToPay($order);
noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功,取消的订单,已恢复 SUCCESS', '15280215347');
} catch (\Exception $exception) {
$ret = HdRefundClass::onlyRefundAmount($shop, $order);
if ($ret['status'] == 0) {
$errMsg = $exception->getMessage();
noticeUtil::push('注意,零售订单:' . $orderSn . ',付款成功但订单取消。订单没有恢复成功,原因' . $errMsg . ',也没有退款成功。请手动处理。关键词 cancel_get_money', '15280215347');
}
util::stop("SUCCESS");
}
}
if ($order->payStatus == 1) {
noticeUtil::push('注意,零售订单:' . $orderSn . ',已经付过款了,无需重复请求和操作', '15280215347');
util::fail('订单已经付过款了');
}
$orderId = $order->id ?? 0;
$customId = $order->customId ?? 0;
$order->status = self::ORDER_STATUS_UN_SEND; // 付款后,订单状态设置为:已付款(待配送)
$order->payWay = $payWay;
$order->payStatus = 1;
if (!empty($params['historyDate'])) {
$order->payTime = $params['historyDate'] . ' ' . date("H:i:s");
} else {
$order->payTime = date("Y-m-d H:i:s");
}
$order->stockChange = 1;
$order->save();
$myCustom = CustomClass::getLockById($customId);
if (!empty($myCustom)) {
$customName = $myCustom->name ?? $order->customName ?? '';
$orderSnText = $order->orderSn ?? '';
$shopAdminId = $order->shopAdminId ?? 0;
$shopAdminName = $order->shopAdminName ?? '';
$eventPrefix = $customName;
if ($eventPrefix === '' && $orderSnText !== '') {
$eventPrefix = '客户';
}
if ($order->forward == 0) { //0 常规订单
$myCustom->recentExpend = date("Y-m-d H:i:s");
$myCustom->visitTime = date("Y-m-d H:i:s");
if ($payWay == dict::getDict('payWay', 'balancePay')) {
$myCustom->recordGrowthAndIntegral = false;
}
$myCustom->buyAmount = bcadd($myCustom->buyAmount, $order->realPrice, 2);
$myCustom->eventRemark = trim($eventPrefix . '下单' . $orderSnText);
} elseif ($order->forward == 1) { //1 售后付款单(红冲)
$myCustom->buyAmount = bcsub($myCustom->buyAmount, $order->realPrice, 2);
$myCustom->eventRemark = trim($eventPrefix . '红冲' . $orderSnText);
} else {
util::fail('订单类型不存在');
}
$myCustom->relateId = $orderId;
$myCustom->relateType = 1; //关联的表或类别:0.无关联 1.零售订单
$myCustom->staffId = $shopAdminId;
$myCustom->staffName = $shopAdminName;
$myCustom->mainId = $order->mainId;
$myCustom->save();
$hd = HdClass::getLockById($myCustom->hdId);
//$hd = HdClass::getByCondition(['shopId'=>$order->shopId, 'userId'=>$order->userId], true, false, 'id,customId,expendAmount');
if (!empty($hd)) {
if ($order->forward == 0) { //0 常规订单
$hd->expendAmount = bcadd($hd->expendAmount, $order->realPrice, 2);
} elseif ($order->forward == 1) { //1 售后付款单(红冲)
$hd->expendAmount = bcsub($hd->expendAmount, $order->realPrice, 2);
} else {
util::fail('订单类型不存在');
}
$hd->save();
}
}
$realPrice = $order->realPrice ?? 0;
$shopId = $order->shopId;
$shop = ShopClass::getLockById($shopId);
if (empty($shop)) {
util::fail('没有找到门店,编号5115');
}
$mainId = $shop->mainId ?? 0;
$main = MainClass::getLockById($mainId);
if (empty($main)) {
util::fail('没有main信息,编号3096');
}
$main->unSendOrder += 1;
$main->unPayOrder -= 1;
$currentTotalIncome = bcadd($main->totalIncome, $realPrice, 2);
$main->totalIncome = $currentTotalIncome;
$main->save();
$capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
$shopAdminId = $order->shopAdminId ?? 0;
$shopAdminName = $order->shopAdminName ?? '';
$sjId = $order->sjId;
$fromType = $order->fromType ?? 1;
$event = !empty($shopAdminId) ? '员工开单' : '客户下单';
$capital = [
'capitalType' => $capitalType,
'relateId' => $orderId,
'io' => 1,
'totalIncome' => $currentTotalIncome,
'payWay' => $payWay,
'event' => $event,
'sjId' => $sjId,
'shopId' => $shopId,
'shopAdminId' => $shopAdminId,
'shopAdminName' => $shopAdminName,
'amount' => $realPrice,
'fromType' => $fromType,
'mainId' => $mainId,
];
ShopCapitalClass::addCapital($capital);
//每天和每月收入增加
//StatIncomeClass::updateOrInsert($main, $shop, $realPrice);
//今日订单+1
//StatOrderClass::updateOrInsert($main, $shop);
//销售收入增加
//StatSaleClass::replace($main, $shop, $realPrice);
//各渠道收入金额统计
//StatKdClass::replace($shop, $realPrice, $payWay);
//当天同个人同地址的订单汇总
$sameDate = date("Y_m_d");
$sameAddress = $order->showAddress ?? '';
$addressMd5 = md5($sameAddress);
$sameKey = $customId . '_' . $addressMd5 . '_' . $sameDate . '_retail';
$sameString = Yii::$app->redis->executeCommand('GET', [$sameKey]);
if (!empty($sameString)) {
$newString = $sameString . ',' . $orderId;
$newIdsArray = explode(',', $newString);
if (count($newIdsArray) <= 90) {
Yii::$app->redis->executeCommand('SETEX', [$sameKey, 186400, $newString]);
foreach ($newIdsArray as $currentOrderId) {
OrderClass::updateById($currentOrderId, ['sameTimeIds' => $newString]);
}
//noticeUtil::push($sameKey . '' . $sameAddress . " 花掌柜当天汇总ids:" . $newString, '15280215347');
}
} else {
Yii::$app->redis->executeCommand('SETEX', [$sameKey, 186400, $orderId]);
$order->sameTimeIds = $orderId;
$order->save();
//noticeUtil::push($sameKey . '' . $sameAddress . " 花掌柜当天汇总ids:" . $orderId, '15280215347');
}
//客户在线支付下单增加商家可提现余额
if (isset($order->onlinePay) && $order->onlinePay == dict::getDict('onlinePay', 'yes')) {
$amount = $order->mainPay;
ShopClass::customKdAddBalance($main, $shop, $amount, $order, $capitalType);
}
//客户使用余额付款
if ($payWay == dict::getDict('payWay', 'balancePay')) {
CustomClass::payToChangeBalance($order);
}
//有欠款时
if ($payWay == dict::getDict('payWay', 'debtPay')) {
if (isset($order->remainDebtPrice) && $order->remainDebtPrice > 0) {
CustomClass::skCgDebtAmountAdd($myCustom, $order);
}
}
//全部现金付款余额增加
if ($payWay == dict::getDict('payWay', 'cash')) {
$moneyBalance = bcadd($main->money, $order->mainPay, 2);
$main->money = $moneyBalance;
$main->save();
$moneyEvent = "客户现金下单" . floatval($order->mainPay) . "元(单号 {$order->orderSn})";
$moneyRemark = '';
$change = [
'relateId' => $orderId,
'amount' => $order->mainPay,
'balance' => $moneyBalance,
'io' => 1,
'mainId' => $mainId,
'capitalType' => $capitalType,
'ptStyle' => dict::getDict('ptStyle', 'hd'),
'event' => $moneyEvent,
'remark' => $moneyRemark,
];
ShopMoneyChangeClass::addData($change);
} else {
//部分现金付款
$orderCash = $order->cash ?? 0;
$orderCash = floatval($orderCash);
if ($orderCash > 0) {
$moneyBalance = bcadd($main->money, $orderCash, 2);
$main->money = $moneyBalance;
$main->save();
$moneyEvent = "客户部分现金付款{$orderCash}元(单号 {$order->orderSn})";
$moneyRemark = '';
$change = [
'relateId' => $orderId,
'amount' => $orderCash,
'balance' => $moneyBalance,
'io' => 1,
'mainId' => $mainId,
'capitalType' => $capitalType,
'ptStyle' => dict::getDict('ptStyle', 'hd'),
'event' => $moneyEvent,
'remark' => $moneyRemark,
];
ShopMoneyChangeClass::addData($change);
}
}
}
//转化出送到时间 ssh 2020.3.15
public static function getReachTime($order)
{
$reachTime = '';
if (isset($order['reachDate']) && !empty($order['reachDate'])) {
$prev = date("n-j", strtotime($order['reachDate']));
$periodData = self::$reachPeriod;
$periodKey = $order['reachPeriod'];
$period = isset($periodData[$periodKey]) ? $periodData[$periodKey] : '上午';
$reachTime = $prev . ' ' . $period;
}
return $reachTime;
}
//支付成功获取unionId ssh 2020.5.12
public static function payToUpdateUnionId($merchant, $merchantExtend, $orderSn, $user)
{
$mcId = $merchantExtend['wxPayMerchantId'];
$miniOpenId = isset($user['miniOpenId']) ? $user['miniOpenId'] : '';
$unionId = isset($user['unionId']) ? $user['unionId'] : '';
$userId = $user['id'];
if (empty($unionId)) {
$unionId = miniUtil::getPaidUnionId($merchant, $miniOpenId, $mcId, (string)$orderSn, 0);
if (!empty($unionId)) {
$findUser = UserClass::getByUnionId($unionId);
if (empty($findUser)) {
UserClass::updateByCondition(['id' => $userId], ['unionId' => $unionId]);
} else {
UserClass::mergeUser($findUser, $user);
}
}
}
}
//订单取消 ssh 20220516
public static function setExpire($order, $force = false, $staff = null)
{
$now = time();
if ($order->deadline > $now && $force == false) {
return false;
}
if ($order->status != 1) {
return false;
}
// 红包退回
HbClass::hbBack($order);
$order->status = 5;
$order->cancelTime = date("Y-m-d H:i:s");
$order->save();
$orderSn = $order->orderSn ?? '';
$relateName = $staff->name ?? '系统';
$itemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
if (!empty($itemList)) {
foreach ($itemList as $item) {
$ptItemId = $item->ptItemId ?? 0;
$sjId = $item->sjId ?? 0;
$shopId = $item->shopId ?? 0;
$mainId = $item->mainId ?? 0;
$ratio = $item->ratio ?? 20;
$unitType = $item->unitType ?? 0;
if ($unitType == 0) {
$bigNum = $item->num;
$smallNum = 0;
} else {
$bigNum = 0;
$smallNum = $item->num;
}
$itemId = $item->itemId ?? 0;
$stockInfo = ProductClass::addStock($itemId, $bigNum, $smallNum);
$recordData = [];
$recordData['sjId'] = $sjId;
$recordData['shopId'] = $shopId;
$recordData['mainId'] = $mainId;
$recordData['itemId'] = $ptItemId;
$recordData['itemNum'] = ProductClass::mergeItemNum($bigNum, $smallNum, $ratio);
$recordData['oldStock'] = $stockInfo['oldStock'];
$recordData['newStock'] = $stockInfo['newStock'];
$recordData['productId'] = $itemId;
$recordData['orderSn'] = $orderSn;
$recordData['relateName'] = $relateName;
StockRecordClass::addSellStockOrderCancelRecord($recordData);
}
}
$goodsList = OrderGoodsClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
if (!empty($goodsList)) {
foreach ($goodsList as $goods) {
$goodsId = $goods->goodsId ?? 0;
$num = $goods->num ?? 0;
$mainId = $goods->mainId ?? 0;
$orderSn = $goods->orderSn ?? '';
$shopId = $goods->shopId ?? 0;
$sjId = $goods->sjId ?? 0;
$params = ['reduceSale' => 1];
$respond = \bizHd\goods\classes\GoodsClass::addStock($goodsId, $mainId, $num, $params);
$oldStock = $respond['oldStock'] ?? 0;
$newStock = $respond['newStock'] ?? 0;
$data = [];
$data['sjId'] = $sjId;
$data['shopId'] = $shopId;
$data['mainId'] = $mainId;
$data['orderSn'] = $orderSn;
$data['goodsId'] = $goodsId;
$data['goodsNum'] = $num;
$data['oldStock'] = $oldStock;
$data['newStock'] = $newStock;
$data['relateName'] = $relateName;
GoodsStockRecordClass::cancelOrder($data);
}
}
$shopId = $order->shopId ?? 0;
$shop = ShopClass::getById($shopId, true);
if (!empty($shop)) {
$merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
$lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
$params = [
'appid' => 'OP00002119',
'serial_no' => '018b08cfddbd',
'merchant_no' => $shop->lklSjNo,
'term_no' => $shop->lklScanTermNo,
'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
'lklCertificatePath' => $lklCertificatePath,
];
$laResource = new Lakala($params);
$closeParams = [
'orderSn' => $orderSn,
];
$response = $laResource->close($closeParams);
if (isset($response['code']) == false || $response['code'] != 'BBS00000') {
//noticeUtil::push('零售订单:' . $orderSn . ',关单没有成功。', '15280215347');
} else {
//noticeUtil::push('零售订单:' . $orderSn . ',关单成功。', '15280215347');
}
}
//清理限购缓存
$customId = $order->customId ?? 0;
if (!empty($customId) && !empty($itemList)) {
foreach ($itemList as $item) {
$productId = $item['itemId'];
$num = floor($item['num']);
if (!empty($productId) && $num > 0) {
\bizHd\product\classes\ProductClass::baseClearLimitBuy($productId, $customId, $num);
}
}
}
}
// 恢复订单 -- 即:把订单的状态从取消状态变成待付款状态
public static function recoverOrderToPay($order)
{
$now = time();
$order->status = 1;
$order->deadline = $now + 86400;
$order->save();
// 重新占用库存(与取消订单时的库存回滚相反)
$itemList = OrderItemClass::getAllByCondition(['orderSn' => $order->orderSn], null, '*', null, true);
if (!empty($itemList)) {
foreach ($itemList as $item) {
$ptItemId = $item->ptItemId ?? 0;
$sjId = $item->sjId ?? 0;
$shopId = $item->shopId ?? 0;
$mainId = $item->mainId ?? 0;
$ratio = $item->ratio ?? 20;
$unitType = $item->unitType ?? 0;
if ($unitType == 0) {
$bigNum = $item->num;
$smallNum = 0;
} else {
$bigNum = 0;
$smallNum = $item->num;
}
$itemId = $item->itemId ?? 0;
// 重新扣减库存(占用库存)
$stockInfo = ProductClass::decreaseStock($itemId, $bigNum, $smallNum, true);
$recordData = [];
$recordData['sjId'] = $sjId;
$recordData['shopId'] = $shopId;
$recordData['mainId'] = $mainId;
$recordData['itemId'] = $ptItemId;
$recordData['itemNum'] = ProductClass::mergeItemNum($bigNum, $smallNum, $ratio);
$recordData['oldStock'] = $stockInfo['oldStock'];
$recordData['newStock'] = $stockInfo['newStock'];
$recordData['productId'] = $itemId;
$recordData['orderSn'] = $order->orderSn;
$recordData['relateName'] = $order->customName ?? '';
StockRecordClass::hdKdAddRecord($recordData);
}
}
return true;
}
// 扣库存
protected static function decGoodsStock($orderGoods)
{
foreach ($orderGoods as $goods) {
GoodsClass::counters([
'stock' => -$goods['num']
], [
'and',
['id' => $goods['goodsId']],
['<>', 'stock', Goods::FULL_STOCK]
]);
}
}
//云打印 ssh 20210709
public static function onlinePrint($order, $must = false, $port = 'front')
{
if (empty($order)) {
return false;
}
if (!$must) {
if ($order->needPrint != dict::getDict('needPrint', 'need')) {
return false;
}
if ($order->payStatus != 1) {
return false;
}
}
if ($order->forward == 1) {
//售后付款单暂时不能打印
return false;
}
$shopId = $order->shopId ?? 0;
$shop = ShopClass::getById($shopId, true);
$sjId = $shop->sjId ?? 0;
$sj = SjClass::getById($sjId, true);
$sjName = $sj->name ?? '';
$shopName = $shop->shopName ?? '';
$currentName = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
$ext = ShopExtClass::getByCondition(['shopId' => $shopId]);
$printSn = $ext['printSn'] ?? '';
if ($port == 'make') {
$printSn = $ext['makePrintSn'] ?? '';
if ($order->fromType == 4) {
$printSn = $ext['mtPrintSn'] ?? '';
}
$workList = WorkClass::getAllByCondition(['orderId' => $order->id], null, '*', null, true);
$hasSh = 0;
if (!empty($workList)) {
foreach ($workList as $work) {
$sh = $work->sh ?? 0;
if ($sh == 1) {
$hasSh = 1;
}
}
}
if ($hasSh == 1) {
$printSn = $ext['printSn'] ?? '';
}
}
if (empty($printSn)) {
return false;
}
$order->printNum += 1;
$order->save();
$customId = $order->customId ?? 0;
$custom = CustomClass::getById($customId);
$debtAmount = $custom['debtAmount'] ?? 0;
$respond = self::getPrintData($order, $debtAmount);
$fromType = $order->fromType ?? dict::getDict('fromType', 'shop');
$fromTypeMap = dict::getDict('fromTypeMap');
$fromTypeName = $fromTypeMap[$fromType] ?? '门店';
//客服下的单则显示客服号和客户名称
if ($fromType == dict::getDict('fromType', 'friend')) {
$staffName = $order->shopAdminName ?? '';
$bookName = $order->bookName ?? '';
$fromTypeName = $staffName . ' ' . $bookName;
}
$content = '';
//$content .= "【零售】
";
if ($fromType == dict::getDict('fromType', 'mt')) {
$content .= '美团 ' . $order->thirdSn . '
';
if (isset($order->goodsNum) && $order->goodsNum > 1) {
$content .= '美团 ' . $order->thirdSn . ' (' . $order->goodsNum . '份)
';
}
$content .= '--------------------------------
';
$content .= date("Y-m-d", strtotime($order->addTime)) . '
';
} else {
$content .= '' . $currentName . '
';
$content .= '销售单
';
$content .= '' . $fromTypeName . ' ' . $respond['sendNum'] . '
';
$content .= '--------------------------------
';
}
$readPeriod = $order->reachPeriod ?? 0;
if ($order->sendType == 1) {
if (!empty($order->reachDate) && $order->reachDate != '0000-00-00') {
$currentReachDate = date("m-d", strtotime($order->reachDate));
$content .= '' . $currentReachDate . ' ' . $readPeriod . '前
';
$content .= '到店自取
';
} else {
$content .= '到店自取
';
}
} else {
if ($order->sendType == 0) {
$content .= '送货上门
';
} else if ($order->sendType == 2) {
$content .= '请跑腿送
';
} else if ($order->sendType == 3) {
$content .= '物流到付
';
} else if ($order->sendType == 4) {
$content .= '快递到付
';
} else {
$content .= '';
}
if (!empty($order->reachDate) && $order->reachDate != '0000-00-00') {
$currentReachDate = date("m-d", strtotime($order->reachDate));
$content .= '' . $currentReachDate . ' ' . $readPeriod . '前
';
}
}
$defaultCustomId = $shop->defaultCustomId ?? 0;
$fastOrder = $defaultCustomId == $customId ? 1 : 0;
//快捷开单不需要显示这些东西
if ($fastOrder == 0) {
if (!empty($order->receiveUserName)) {
$content .= '收花人:
';
$content .= '' . $order->receiveUserName . '
';
}
if (!empty($order->receiveMobile)) {
$content .= '' . $order->receiveMobile . '
';
}
if (!empty($order->fullAddress)) {
$content .= '' . $order->fullAddress . '(' . $order->showAddress . ')' . '
';
}
if (!empty($order->cardInfo)) {
$content .= '贺卡内容:' . $order->cardInfo . '
';
}
if ($order->anonymity == 1) {
$content .= '匿名派送!!
';
} else {
if (!empty($order->bookMobile)) {
$bookName = $order->bookName ?? '';
$bookMobile = $order->bookMobile;
$content .= '订花人:
';
if (!empty($bookName)) {
$content .= '' . $bookName . '
';
}
$content .= '' . $bookMobile . '
';
}
}
}
if (!empty($respond['remark'])) {
$content .= '
';
$content .= '备注:
';
$content .= '' . $respond['remark'] . '
';
}
$content .= '
';
$content .= '商品 数量/单价 金额
';
$content .= '--------------------------------
';
if (!empty($respond['product'])) {
foreach ($respond['product'] as $current) {
$content = self::printGroup($current, $content);
}
$content .= '--------------------------------
';
}
if (!empty($respond['refund'])) {
$content .= '已退款:
';
foreach ($respond['refund'] as $current) {
//58mm的机器,一行打印16个汉字,32个字母
$name = $current['name'] ?? '';
$content .= $name . '
';
$name = str_repeat(' ', 10);
$productNum = $current['num'] ?? '';
$blankNum = bcsub(12, strlen($productNum));
if ($blankNum > 0) {
$productNum = $productNum . str_repeat(' ', $blankNum);
}
$productPrice = $current['price'] ?? '';
$blankNum = bcsub(7, strlen($productPrice));
if ($blankNum > 0) {
$productPrice = $productPrice . str_repeat(' ', $blankNum);
}
$content .= $name . " " . $productNum . ' ' . $productPrice . '
';
}
$content .= '--------------------------------
';
}
if (isset($order->goodsPrice) && $order->goodsPrice > 0) {
$content .= '商品合计:' . floatval($order->goodsPrice) . '
';
}
if (isset($respond['sendCost']) && $respond['sendCost'] > 0 && $order->sendType == 2) {
$content .= '运费:' . floatval($respond['sendCost']) . '
';
}
if (isset($order->serviceFee) && $order->serviceFee > 0) {
$content .= '手续费:' . floatval($order->serviceFee) . '
';
}
if (isset($order->labourCost) && $order->labourCost > 0) {
$content .= '包装费:' . floatval($order->labourCost) . '
';
}
if (isset($order->prePrice) && $order->prePrice > 0) {
$content .= '总计:' . floatval($order->prePrice) . '
';
}
if (!empty($respond['discountAmount']) && $respond['discountAmount'] > 0) {
$content .= '优惠扣除:-' . floatval($respond['discountAmount']) . '
';
}
$content .= '订单金额:' . floatval($respond['orderPrice']) . '
';
if (isset($respond['refundPrice']) && $respond['refundPrice'] > 0) {
$content .= '退款金额:' . floatval($respond['refundPrice']) . '
';
}
if (isset($respond['debt']) && $respond['debt'] == 1) {
$content .= '实付金额:0
';
} else {
$content .= '实付金额:' . floatval($respond['realPrice']) . '
';
}
if (isset($order->remainDebtPrice) && $order->remainDebtPrice > 0) {
$content .= '待付尾款:' . floatval($order->remainDebtPrice) . '
';
}
$content .= '--------------------------------
';
$balance = $custom['balance'] ?? 0;
$balance = floatval($balance);
if ($balance > 0) {
$content .= '当前账户余额:' . $balance . '元
';
}
$content .= '订单日期:' . $order->addTime . '
';
$content .= '订单编号:' . $respond['orderSn'] . '
';
$content .= '门店名称:' . $currentName . '
';
$content .= "
";
//noticeUtil::push($content, '15280215347');
$p = new printUtil($printSn);
$orderSn = $order->orderSn ?? '';
$workList = WorkClass::getAllByCondition(['orderSn' => $orderSn], null, '*', null, true);
if (!empty($workList)) {
$content .= "
";
$content .= '--------------------------------
';
foreach ($workList as $work) {
$goodsSn = $work->goodsSn ?? '';
$sn = $work->sn ?? '';
$content .= '制作号:' . $sn . '';
// 1-523 有-特殊符号,使用飞鹅自带的函数处理
$content .= $p->bar_code($goodsSn);
$content .= "
";
}
}
$p->printMsg($content);
}
//打印数据 ssh 20210702
public static function getPrintData($order, $debtAmount)
{
$orderSn = $order->orderSn ?? '';
$printProduct = [];
$orderItemList = OrderItemClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
if (!empty($orderItemList)) {
foreach ($orderItemList as $itemKey => $itemVal) {
$unitName = $itemVal['unitName'] ?? '';
$unitPrice = $itemVal['unitPrice'] ? floatval($itemVal['unitPrice']) : 0;
$printProduct[] = [
'name' => $itemVal['name'] ?? '',
'num' => $itemVal['num'] . $unitName . '*' . $unitPrice,
'price' => floatval($itemVal['price']),
'sn' => '',
];
}
}
$orderGoodsList = OrderGoodsClass::getAllByCondition(['orderSn' => $orderSn], null, '*');
if (!empty($orderGoodsList)) {
foreach ($orderGoodsList as $itemKey => $itemVal) {
$unitName = $itemVal['unitName'] ?? '份';
$unitPrice = $itemVal['unitPrice'] ? floatval($itemVal['unitPrice']) : 0;
$sn = $itemVal['sn'] ?? '';
$printProduct[] = [
'name' => $itemVal['name'] ?? '',
'num' => $itemVal['num'] . $unitName . '*' . $unitPrice,
'price' => floatval($itemVal['price']),
'sn' => $sn,
];
}
}
$sendNum = $order['sendNum'] ?? '';
//退款记录
$refundList = [];
$printData = [
'address' => '',
'sendCost' => $order->sendCost ?? '0.00',
'prePrice' => $order->prePrice ?? '0.00',
'orderPrice' => $order->orderPrice ?? '0',
'discountAmount' => $order->discountAmount ?? '0.00',
'realPrice' => $order->realPrice ?? '0.00',
'refundPrice' => $order->refundPrice ?? '0.00',
'debt' => $order->debt ?? 0,
'orderSn' => $order->orderSn ?? '',
'date' => $order->addTime ?? '',
'remark' => $order->remark ?? '',
'custom' => [
'customName' => $order->customName ?? '',
'customMobile' => $order->customMobile ?? '',
'fullAddress' => $order->fullAddress ?? '',
],
'product' => $printProduct,
'refund' => $refundList,
'sendNum' => $sendNum,
'debtAmount' => $debtAmount,
];
return $printData;
}
public static function printGroup($current, $content)
{
//58mm的机器,一行打印16个汉字,32个字母
$name = $current['name'] ?? '';
if (!empty($current['sn'])) {
$name = '#' . $current['sn'] . ' ' . $name;
}
$content .= $name . '
';
$name = str_repeat(' ', 10);
$productNum = $current['num'] ?? '';
$blankNum = bcsub(12, strlen($productNum));
if ($blankNum > 0) {
$productNum = $productNum . str_repeat(' ', $blankNum);
}
$productPrice = $current['price'] ?? '';
$blankNum = bcsub(7, strlen($productPrice));
if ($blankNum > 0) {
$productPrice = $productPrice . str_repeat(' ', $blankNum);
}
$content .= $name . " " . $productNum . ' ' . $productPrice . '
';
return $content;
}
//扫码收款的,减少库存 ssh 20250822
public static function reduceMyStock($data, $shop, $custom)
{
$mainId = $shop->mainId;
$customId = $custom->id;
$orderId = $data['orderId'] ?? '';
$sjId = $shop->sjId;
$hdId = $custom->hdId;
$shopId = $shop->id;
$order = self::getById($orderId, true);
if (empty($order)) {
util::fail('没有找到订单');
}
if ($order->mainId != $shop->mainId) {
util::fail('并不是你的订单');
}
if ($order->repeat == 0) {
util::fail('已经扣过了');
}
if ($order->tkPrice > 0) {
util::fail('已经发生退款,无法操作');
}
if ($order->customId != $customId) {
util::fail('订单对应客户有问题,无法扣库存,编号:' . $customId . ' ' . $order->customId);
}
$orderSn = $order->orderSn ?? '';
$product = $data['product'] ?? [];
if (empty($product)) {
util::fail('请选择商品呢');
}
$orderItemList = OrderItemClass::getAllbyCondition(['orderSn' => $orderSn], null, '*', null, true);
if (!empty($orderItemList)) {
foreach ($orderItemList as $orderItem) {
$orderItem->unitPrice = 0;
$orderItem->save();
}
}
$actPrice = $order->actPrice ?? 0;
if ($actPrice <= 0) {
util::fail('订单金额为0');
}
$ids = array_column($product, 'productId');
$productInfo = ItemClass::getByIds($ids, null, 'id');
$goodsPrice = 0;
foreach ($product as $key => $val) {
$property = $val['property'] ?? 0;
if ($property != 1) {
util::fail('暂时只支持花材');
}
$unitPrice = $val['unitPrice'] ?? 0;
$unitType = $val['unitType'] ?? 0;
$currentId = $val['productId'] ?? 0;
$num = $val['num'] ?? 0;
$currentInfo = $productInfo[$currentId] ?? [];
if (empty($currentInfo)) {
util::fail('存在无效花材,编号:' . $currentId);
}
$name = $currentInfo['name'] ?? '';
$cover = $currentInfo['cover'] ?? '';
$ratio = $currentInfo['ratio'] ?? 20;
$itemMainId = $currentInfo['mainId'] ?? 0;
if ($itemMainId != $mainId) {
util::fail('不是您的花材,请勿使用,编号:' . $mainId . ' ' . $itemMainId);
}
if ($unitType == 0) {
$unitName = $currentInfo['bigUnit'] ?? '';
$unitId = $currentInfo['bigUnitId'] ?? 0;
$totalNum = $num;
} else {
$unitName = $currentInfo['smallUnit'] ?? '';
$unitId = $currentInfo['smallUnitId'] ?? 0;
$totalNum = bcdiv($num, $ratio, 2);
}
$ptItemId = $currentInfo['itemId'] ?? 0;
$classId = $currentInfo['classId'] ?? 0;
$belongCost = $currentInfo['belongCost'] ?? 0;
$currentPrice = bcmul($unitPrice, $num, 2);
$goodsPrice = bcadd($goodsPrice, $currentPrice, 2);
$currentItemData = [
'name' => $name,
'cover' => $cover,
'ratio' => $ratio,
'unitType' => $unitType,
'unitName' => $unitName,
'unitId' => $unitId,
'unitPrice' => $unitPrice,
'num' => $num,
'orderSn' => $orderSn,
'itemId' => $currentId,
'ptItemId' => $ptItemId,
'totalNum' => $totalNum,
'totalPrice' => 0,
'customId' => $customId,
'hdId' => $hdId,
'sjId' => $sjId,
'shopId' => $shopId,
'mainId' => $mainId,
'classId' => $classId,
'price' => $currentPrice,
'belongCost' => $belongCost,
];
//库存变化在这里
OrderItemClass::addData($currentItemData, $custom);
}
$labourCost = 0;
$discountType = 0;
$discountAmount = 0;
if ($goodsPrice > $actPrice) {
$prePrice = $goodsPrice;
$discountAmount = bcsub($goodsPrice, $actPrice, 2);
if ($discountAmount > 0) {
$discountType = 3;
}
} else {
$prePrice = $actPrice;
$labourCost = bcsub($actPrice, $goodsPrice, 2);
}
$order->goodsPrice = $goodsPrice;
$order->prePrice = $prePrice;
$order->labourCost = $labourCost;
$order->discountAmount = $discountAmount;
$order->discountType = $discountType;
$order->repeat = 0;
$order->save();
return $order;
}
public static function debtCount($mainId)
{
$debtAmount = 0;
$orders = self::getAllByCondition(['mainId' => $mainId, 'status' => 4, 'debt' => 1], null, 'remainDebtPrice', null, true);
foreach ($orders as $order) {
$remainDebtPrice = $order->remainDebtPrice ?? 0;
$debtAmount = bcadd($debtAmount, $remainDebtPrice, 2);
}
return $debtAmount;
}
}