落地合伙股东收益体系,并纳入 sheep 用户端源码。

Co-authored-by: Cursor <cursoragent@cursor.com>
这个提交包含在:
chen
2026-09-17 07:47:35 +08:00
父节点 7747dfaa82
当前提交 251d62296e
共有 595 个文件被更改,包括 90234 次插入 和 105 次删除

查看文件

@@ -134,6 +134,18 @@ class Agent
return $this->parentUserId;
}
/**
* 支付后更新本人最近合格订单时间
*/
public function touchLastSelfOrderTime($time = null)
{
if (empty($this->agent)) {
return false;
}
$this->agent->last_self_order_time = $time ?: time();
return $this->agent->save();
}
/**
* 创建分销商
*/

查看文件

@@ -23,7 +23,9 @@ class Config
public function getInviteLockEvent()
{
$becomeAgentEvent = $this->getBecomeAgentEvent();
if($becomeAgentEvent === 'user') {
$becomeType = is_array($becomeAgentEvent) ? ($becomeAgentEvent['type'] ?? '') : $becomeAgentEvent;
// 合伙股东模式下 become=user 仍尊重 invite_lock,避免注册即绑丢掉分享关系
if ($becomeType === 'user' && empty($this->config['partner_mode'])) {
return 'agent';
}
return $this->config['invite_lock'];

查看文件

@@ -171,6 +171,9 @@ class Order
*/
public function runCommissionPlan($commissionOrder, $currentAgent = null, $currentCommissionLevel = 1)
{
if (sheep_config('shop.commission.partner_mode')) {
return true;
}
// 超出分佣层级
if ($this->commissionLevel < $currentCommissionLevel) {
return true;

查看文件

@@ -63,6 +63,11 @@ class OrderCreate
*/
protected $coupon_id = 0;
/**
* 用户选择的兑换券抵扣金额
*/
protected $voucher_fee = 0;
/**
* 用户备注
*/
@@ -102,6 +107,8 @@ class OrderCreate
'goods_old_amount' => '0', // 商品不参与活动时的总价
'goods_amount' => '0', // 商品总价
'coupon_discount_fee' => '0', // 优惠券优惠金额
'voucher_fee' => '0', // 兑换券抵扣
'voucher_available' => '0', // 当前可用兑换券
'promo_discount_fee' => 0, // 当前促销优惠总金额 (包含满包邮的邮费)
'total_discount_fee' => 0, // 当前订单,总优惠金额(优惠券 + 活动优惠)
'coupon' => null, // 所使用的优惠券
@@ -151,6 +158,7 @@ class OrderCreate
$this->invoice_id = $params['invoice_id'] ?? 0;
$this->coupon_id = $params['coupon_id'] ?? 0;
$this->voucher_fee = isset($params['voucher_fee']) ? floatval($params['voucher_fee']) : 0;
$this->remark = $params['remark'] ?? '';
$this->money = (isset($params['money']) && $params['money'] > 0) ? $params['money'] : 0;
@@ -593,6 +601,29 @@ class OrderCreate
}
}
/**
* 兑换券抵扣:先商城券,再兑换券;不超过可用额和应付
*/
public function calcVoucher()
{
$available = 0;
if ($this->user && $this->user->id && $this->order_type !== 'score') {
$available = (new \addons\shopro\service\partner\VoucherService())->available($this->user->id);
}
$this->orderData['voucher_available'] = $available;
$want = $this->order_type === 'score' ? 0 : max(0, round((float) $this->voucher_fee, 2));
$apply = min($want, (float) $available, (float) $this->orderData['pay_fee']);
$apply = $apply > 0 ? $apply : 0;
$this->orderData['voucher_fee'] = $apply;
if ($apply > 0) {
$this->orderData['pay_fee'] = bcsub((string) $this->orderData['pay_fee'], (string) $apply, 2);
$this->orderData['total_discount_fee'] = bcadd((string) $this->orderData['total_discount_fee'], (string) $apply, 2);
if ($this->orderData['pay_fee'] < 0) {
$this->orderData['pay_fee'] = 0;
}
}
}
/**
* 获取用户的优惠券列表,可用和不可用的做区分
@@ -969,6 +1000,8 @@ class OrderCreate
'temp_remain_pay_fee' => $temp_remain_pay_fee >= 0 ? $temp_remain_pay_fee : 0, // 临时剩余应支付金额,订单确认页面显示
'total_discount_fee' => $this->orderData['total_discount_fee'],
'coupon_discount_fee' => $this->orderData['coupon_discount_fee'],
'voucher_fee' => $this->orderData['voucher_fee'],
'voucher_available' => $this->orderData['voucher_available'],
'promo_discount_fee' => $this->orderData['promo_discount_fee'], // 包含包邮的运费优惠
'money' => $this->money, // 余额支付部分
"invoice_amount" => $this->orderData[$this->invoiceConfig['amount_type']] // 可开票金额
@@ -1042,6 +1075,7 @@ class OrderCreate
$this->orderData['total_discount_fee'] = bcadd($this->orderData['coupon_discount_fee'], $this->orderData['promo_discount_fee'], 2);
$this->orderData['pay_fee'] = bcsub($this->orderData['order_amount'], $this->orderData['total_discount_fee'], 2);
$this->orderData['pay_fee'] = $this->orderData['pay_fee'] < 0 ? 0 : $this->orderData['pay_fee'];
$this->calcVoucher();
return $this->calcReturn();
}
@@ -1074,6 +1108,12 @@ class OrderCreate
$order = Order::with('items')->where('id', $order->id)->find();
$pay_money = floatval($result['money']);
if ($order->status == Order::STATUS_UNPAID && bccomp((string) $order->pay_fee, '0', 2) === 0) {
$order = Db::transaction(function () use ($order) {
$payOper = new PayOper();
return $payOper->checkAndPaid($order, 'order');
});
}
if ($order->status == Order::STATUS_UNPAID && $pay_money > 0) {
// 如果订单未支付,并且使用了余额混合支付 (支付失败,不影响订单状态)
$order = Db::transaction(function () use ($order, $pay_money) {
@@ -1129,6 +1169,7 @@ class OrderCreate
}
$ext['offline_status'] = $result['offline_status'];
$ext['need_address'] = $result['need_address']; // 后台判断是否有 编辑收货地址按钮
$ext['voucher_fee'] = $result['voucher_fee'] ?? 0;
// 发票开具状态
$invoice_status = 0; // 没有申请

查看文件

@@ -0,0 +1,65 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\order\Order as OrderModel;
/**
* 30 日活跃:含今天共 N 个自然日有本人合格订单
*/
class ActiveService
{
public function windowStart($endTime = null)
{
$days = PartnerConfig::activeDays();
$end = $endTime ?: time();
$endDay = strtotime(date('Y-m-d 00:00:00', $end));
return $endDay - ($days - 1) * 86400;
}
public function isActive($agent, $atTime = null)
{
if (!$agent) {
return false;
}
$last = is_array($agent) ? ($agent['last_self_order_time'] ?? null) : ($agent->last_self_order_time ?? null);
$userId = is_array($agent) ? ($agent['user_id'] ?? 0) : ($agent->user_id ?? 0);
$at = $atTime ?: time();
$start = $this->windowStart($at);
if ($last) {
return intval($last) >= $start;
}
if (!$userId) {
return false;
}
return $this->hasQualifiedOrder($userId, $start, $at);
}
public function hasQualifiedOrder($userId, $start, $end)
{
$order = OrderModel::where('user_id', $userId)
->where('type', '<>', 'score')
->where('pay_fee', '>', 0)
->paid()
->where('paid_time', '>=', $start)
->where('paid_time', '<=', $end)
->find();
return (bool) $order;
}
public function activeUserIds($start, $end, $extraWhere = [])
{
$query = \think\Db::name('shopro_commission_agent')
->where('status', 'in', ['normal', 'freeze'])
->where('level', '>=', 1)
->where(function ($q) use ($start, $end) {
$q->where('last_self_order_time', '>=', $start)
->where('last_self_order_time', '<=', $end);
});
foreach ($extraWhere as $field => $value) {
$query->where($field, $value);
}
return $query->column('user_id');
}
}

查看文件

@@ -0,0 +1,74 @@
<?php
namespace addons\shopro\service\partner;
use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 从买家向上走关系链
*/
class ChainService
{
/**
* @param int $buyerId
* @param bool $includeSelf 是否把买家自己放进链头(酒道馆自购)
* @return array
*/
public function collect($buyerId, $includeSelf = false)
{
$nodes = [];
$max = PartnerConfig::chainMaxDepth();
$visited = [];
if ($includeSelf) {
$self = $this->node($buyerId);
if ($self) {
$nodes[] = $self;
$visited[$buyerId] = true;
}
}
$currentId = $buyerId;
for ($i = 0; $i < $max; $i++) {
$agent = new AgentService($currentId);
$parentId = $agent->getParentUserId();
if (!$parentId || isset($visited[$parentId])) {
break;
}
$node = $this->node($parentId);
if (!$node) {
break;
}
$nodes[] = $node;
$visited[$parentId] = true;
$currentId = $parentId;
}
return $nodes;
}
public function node($userId)
{
if (!$userId) {
return null;
}
$agent = AgentModel::where('user_id', $userId)
->where('status', 'in', ['normal', 'freeze'])
->find();
if (!$agent) {
return null;
}
return [
'user_id' => intval($agent->user_id),
'level' => intval($agent->level),
'is_venue' => intval($agent->is_venue),
'is_county' => intval($agent->is_county),
'county_code' => (string) $agent->county_code,
'last_self_order_time' => $agent->last_self_order_time ? intval($agent->last_self_order_time) : 0,
'direct_order_seq' => intval($agent->direct_order_seq),
'status' => $agent->status,
'agent' => $agent,
];
}
}

查看文件

@@ -0,0 +1,201 @@
<?php
namespace addons\shopro\service\partner;
use think\Db;
use addons\shopro\service\Wallet;
use app\admin\model\shopro\partner\DailyReport;
use app\admin\model\shopro\partner\Reward as RewardModel;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 日结:马豆 / 馆县均分 / 券释放
*/
class DailySettleService
{
public function run($date = null, $rerun = false)
{
$settleDate = $date ?: date('Y-m-d', strtotime('-1 day'));
$lockDir = RUNTIME_PATH . 'lock';
if (!is_dir($lockDir)) {
@mkdir($lockDir, 0755, true);
}
$lockFile = $lockDir . '/partner_settle_' . date('Ymd', strtotime($settleDate)) . '.lock';
$fp = fopen($lockFile, 'c');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
throw new \Exception('日结正在执行,请稍后再试');
}
try {
$exist = DailyReport::where('settle_date', $settleDate)->where('status', 1)->find();
if ($exist && !$rerun) {
return $exist;
}
if ($rerun) {
$this->clearDaily($settleDate);
}
Db::transaction(function () use ($settleDate) {
$this->settle($settleDate);
});
return DailyReport::where('settle_date', $settleDate)->find();
} catch (\Exception $e) {
DailyReport::create([
'settle_date' => $settleDate,
'status' => 0,
'error_msg' => mb_substr($e->getMessage(), 0, 500),
'createtime' => time(),
'updatetime' => time(),
]);
throw $e;
} finally {
flock($fp, LOCK_UN);
fclose($fp);
}
}
protected function settle($settleDate)
{
$start = strtotime($settleDate . ' 00:00:00');
$end = strtotime($settleDate . ' 23:59:59');
$rateService = new RateService();
$active = new ActiveService();
$orders = $rateService->qualifiedOrderQuery($start, $end)->field('o.id,o.pay_fee')->select();
$orderCount = count($orders);
$gmv = 0;
foreach ($orders as $order) {
$gmv = bcadd((string) $gmv, (string) $order['pay_fee'], 2);
}
$windowStart = strtotime($settleDate . ' 00:00:00') - (PartnerConfig::activeDays() - 1) * 86400;
$tasterIds = $active->activeUserIds($windowStart, $end);
$venueIds = $active->activeUserIds($windowStart, $end, ['is_venue' => 1]);
$countyIds = $active->activeUserIds($windowStart, $end, ['is_county' => 1]);
$madow = (new MadowService())->share($settleDate, $gmv, $tasterIds);
$venuePer = (float) PartnerConfig::get('partner_venue_share_per_order', 100);
$countyPer = (float) PartnerConfig::get('partner_county_share_per_order', 50);
$venuePool = round($orderCount * $venuePer, 2);
$countyPool = round($orderCount * $countyPer, 2);
$this->cashShare($settleDate, $venueIds, $venuePool, 'venue_share', 'venue', '酒道馆');
$this->cashShare($settleDate, $countyIds, $countyPool, 'county_share', 'county', '区县');
$voucherTotal = (new VoucherService())->releaseByDate($settleDate);
$rateLog = $rateService->snapshot($settleDate, $gmv, [
'madow_pool' => $madow['pool'],
'share_user_count' => $madow['count'],
'venue_pool' => $venuePool,
'county_pool' => $countyPool,
]);
DailyReport::create([
'settle_date' => $settleDate,
'order_count' => $orderCount,
'order_count_n' => $rateLog->order_count_n ?? $rateService->countN(),
'gmv' => $gmv,
'rate' => $rateLog->rate ?? 0,
'madow_pool' => $madow['pool'],
'share_user_count' => $madow['count'],
'venue_pool' => $venuePool,
'venue_user_count' => count($venueIds),
'county_pool' => $countyPool,
'county_user_count' => count($countyIds),
'voucher_release_total' => $voucherTotal,
'status' => 1,
'error_msg' => '',
'createtime' => time(),
'updatetime' => time(),
]);
}
protected function cashShare($settleDate, $userIds, $pool, $type, $role, $label)
{
$count = count($userIds);
$orderId = PartnerRewardService::dailyOrderId($settleDate);
if ($pool <= 0) {
return;
}
if ($count <= 0) {
PartnerRewardService::write([
'order_id' => $orderId,
'user_id' => 0,
'role' => 'system',
'reward_type' => $type,
'amount' => $pool,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "{$label}分母为0,奖池 {$pool} 进平台"],
'status' => 1,
]);
return;
}
$each = function_exists('bcdiv') ? bcdiv((string) $pool, (string) $count, 2) : number_format($pool / $count, 2, '.', '');
$distributed = 0;
foreach ($userIds as $userId) {
PartnerRewardService::write([
'order_id' => $orderId,
'user_id' => $userId,
'role' => $role,
'reward_type' => $type,
'amount' => $each,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "{$label}奖池 {$pool} / {$count} = {$each}", 'share_user_count' => $count],
'status' => 1,
]);
if ((float) $each > 0) {
Wallet::change($userId, 'commission', $each, $type, [
'settle_date' => $settleDate,
]);
AgentModel::where('user_id', $userId)->setInc('total_income', $each);
}
$distributed = bcadd((string) $distributed, (string) $each, 2);
}
$tail = bcsub((string) $pool, (string) $distributed, 2);
if ((float) $tail > 0) {
PartnerRewardService::write([
'order_id' => $orderId,
'user_id' => 0,
'role' => 'system',
'reward_type' => $type,
'amount' => $tail,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "{$label}尾差 {$tail} 进平台"],
'status' => 1,
]);
}
}
public function clearDaily($settleDate)
{
(new VoucherService())->rollbackRelease($settleDate);
(new MadowService())->rollback($settleDate);
$cashRows = RewardModel::where('settle_date', $settleDate)
->whereIn('reward_type', ['venue_share', 'county_share'])
->where('status', 1)
->where('user_id', '>', 0)
->select();
foreach ($cashRows as $row) {
if ((float) $row->amount > 0) {
Wallet::change($row->user_id, 'commission', -$row->amount, 'reward_back', [
'settle_date' => $settleDate,
'rerun' => 1,
], '日结重跑扣回');
AgentModel::where('user_id', $row->user_id)->setDec('total_income', $row->amount);
}
}
RewardModel::where('settle_date', $settleDate)
->whereIn('reward_type', PartnerConfig::dailyTypes())
->delete();
DailyReport::where('settle_date', $settleDate)->delete();
\app\admin\model\shopro\partner\RateLog::where('settle_date', $settleDate)->delete();
}
}

查看文件

@@ -0,0 +1,171 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 身份文案:品酒师 / 创客V{n} / 酒道馆 / 区县
*/
class IdentityService
{
public static function build($agent)
{
$empty = [
'identities' => [],
'identity_text' => '',
'is_partner' => false,
'maker_level_name' => '',
];
if (!$agent) {
return $empty;
}
$level = intval(is_array($agent) ? ($agent['level'] ?? 0) : ($agent->level ?? 0));
$isVenue = intval(is_array($agent) ? ($agent['is_venue'] ?? 0) : ($agent->is_venue ?? 0));
$isCounty = intval(is_array($agent) ? ($agent['is_county'] ?? 0) : ($agent->is_county ?? 0));
$identities = [];
$parts = [];
$makerLevelName = '';
if ($level == 1) {
$identities[] = 'taster';
} elseif ($level >= 2) {
$identities[] = 'maker';
$makerLevelName = '创客V' . ($level - 1);
}
if ($isVenue) {
$identities[] = 'venue';
}
if ($isCounty) {
$identities[] = 'county';
}
$isPartner = in_array('maker', $identities) || in_array('venue', $identities) || in_array('county', $identities);
if ($isPartner) {
$parts[] = '合伙股东';
if ($makerLevelName) {
$parts[] = $makerLevelName;
}
if ($isVenue) {
$parts[] = '酒道馆';
}
if ($isCounty) {
$parts[] = '区县代理';
}
} elseif ($level == 1) {
$parts[] = '品酒师';
}
return [
'identities' => $identities,
'identity_text' => implode(' · ', $parts),
'is_partner' => $isPartner,
'maker_level_name' => $makerLevelName,
];
}
public static function formatMoney($value, $scale = 2)
{
return number_format((float) $value, $scale, '.', '');
}
public static function formatMadow($value)
{
return number_format((float) $value, 8, '.', '');
}
public static function formatRate($value)
{
if ($value === null || $value === '') {
$value = PartnerConfig::get('partner_madow_base_rate', '0.00000075');
}
return number_format((float) $value, 8, '.', '');
}
public static function attachAgent($agent, $rate = null)
{
if (!$agent) {
return null;
}
$identity = self::build($agent);
$madow = is_array($agent) ? ($agent['madow'] ?? 0) : ($agent->madow ?? 0);
$released = is_array($agent) ? ($agent['voucher_released'] ?? 0) : ($agent->voucher_released ?? 0);
$used = is_array($agent) ? ($agent['voucher_used'] ?? 0) : ($agent->voucher_used ?? 0);
$total = is_array($agent) ? ($agent['voucher_total'] ?? 0) : ($agent->voucher_total ?? 0);
$last = is_array($agent) ? ($agent['last_self_order_time'] ?? 0) : ($agent->last_self_order_time ?? 0);
if ($rate === null) {
$rate = (new RateService())->currentRate();
}
$available = max(0, (float) $released - (float) $used);
$data = is_object($agent) ? $agent->toArray() : $agent;
return array_merge($data, $identity, [
'is_venue' => intval($data['is_venue'] ?? 0),
'is_county' => intval($data['is_county'] ?? 0),
'county_code' => (string) ($data['county_code'] ?? ''),
'direct_order_seq' => intval($data['direct_order_seq'] ?? 0),
'madow' => self::formatMadow($madow),
'madow_rate' => self::formatRate($rate),
'madow_value' => self::formatMoney((float) $madow * (float) $rate),
'voucher_total' => self::formatMoney($total),
'voucher_released' => self::formatMoney($released),
'voucher_used' => self::formatMoney($used),
'voucher_available' => self::formatMoney($available),
'active_30d' => (new ActiveService())->isActive($agent),
'last_self_order_time' => $last ? intval($last) : 0,
]);
}
public static function attachProfile($agent, $rate = null)
{
if (!$agent) {
$baseRate = PartnerConfig::get('partner_madow_base_rate', '0.00000075');
return [
'identity_text' => '',
'identities' => [],
'is_partner' => false,
'maker_level_name' => '',
'madow' => '0.00000000',
'madow_rate' => self::formatRate($baseRate),
'madow_value' => '0.00',
'voucher_available' => '0.00',
'active_30d' => true,
'agent_form' => self::agentFormEnabled(),
'partner_mode' => PartnerConfig::isPartnerMode(),
];
}
$full = self::attachAgent($agent, $rate);
return [
'identity_text' => $full['identity_text'],
'identities' => $full['identities'],
'is_partner' => $full['is_partner'],
'maker_level_name' => $full['maker_level_name'],
'madow' => $full['madow'],
'madow_rate' => $full['madow_rate'],
'madow_value' => $full['madow_value'],
'voucher_available' => $full['voucher_available'],
'active_30d' => $full['active_30d'],
'agent_form' => self::agentFormEnabled(),
'partner_mode' => PartnerConfig::isPartnerMode(),
];
}
protected static function agentFormEnabled()
{
$form = sheep_config('shop.commission.agent_form');
if (is_array($form)) {
return !empty($form['status']) && $form['status'] !== '0';
}
return false;
}
public static function findAgent($userId)
{
if (!$userId) {
return null;
}
return AgentModel::where('user_id', $userId)->find();
}
}

查看文件

@@ -0,0 +1,90 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 马豆日结 1:1 GMV 均分
*/
class MadowService
{
public function share($settleDate, $gmv, $userIds)
{
$count = count($userIds);
$pool = (float) $gmv;
if ($pool <= 0) {
return ['pool' => 0, 'count' => $count, 'each' => 0];
}
if ($count <= 0) {
PartnerRewardService::write([
'order_id' => PartnerRewardService::dailyOrderId($settleDate),
'buyer_id' => 0,
'user_id' => 0,
'role' => 'system',
'reward_type' => 'madow_share',
'amount' => 0,
'madow' => $pool,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "分母为0,马豆池 {$pool} 进平台", 'skip_reason' => ''],
'status' => 1,
]);
return ['pool' => $pool, 'count' => 0, 'each' => 0];
}
$each = function_exists('bcdiv') ? bcdiv((string) $pool, (string) $count, 8) : number_format($pool / $count, 8, '.', '');
$distributed = 0;
foreach ($userIds as $userId) {
AgentModel::where('user_id', $userId)->setInc('madow', $each);
PartnerRewardService::write([
'order_id' => PartnerRewardService::dailyOrderId($settleDate),
'buyer_id' => 0,
'user_id' => $userId,
'role' => 'taster',
'reward_type' => 'madow_share',
'amount' => 0,
'madow' => $each,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "GMV {$pool} / {$count} = {$each}", 'share_user_count' => $count, 'gmv' => $pool],
'status' => 1,
]);
$distributed = function_exists('bcadd') ? bcadd((string) $distributed, (string) $each, 8) : ($distributed + $each);
}
$tail = function_exists('bcsub') ? bcsub((string) $pool, (string) $distributed, 8) : round($pool - $distributed, 8);
if ((float) $tail > 0) {
PartnerRewardService::write([
'order_id' => PartnerRewardService::dailyOrderId($settleDate),
'buyer_id' => 0,
'user_id' => 0,
'role' => 'system',
'reward_type' => 'madow_share',
'amount' => 0,
'madow' => $tail,
'base_amount' => $pool,
'settle_date' => $settleDate,
'ext' => ['formula' => "尾差 {$tail} 进平台"],
'status' => 1,
]);
}
return ['pool' => $pool, 'count' => $count, 'each' => $each];
}
public function rollback($settleDate)
{
$rows = \app\admin\model\shopro\partner\Reward::where('settle_date', $settleDate)
->where('reward_type', 'madow_share')
->where('status', 1)
->where('user_id', '>', 0)
->select();
foreach ($rows as $row) {
$agent = AgentModel::where('user_id', $row->user_id)->find();
if ($agent && (float) $row->madow > 0) {
$agent->madow = max(0, (float) $agent->madow - (float) $row->madow);
$agent->save();
}
}
}
}

查看文件

@@ -0,0 +1,48 @@
<?php
namespace addons\shopro\service\partner;
/**
* 创客极差:水位差,不活跃不抬 seen
*/
class MakerDiffReward
{
public function run($order, $buyerId, $chain, ActiveService $active)
{
$bonus = PartnerConfig::makerBonus();
$seen = 0;
$paid = [];
foreach ($chain as $node) {
if (intval($node['level']) < 2) {
continue;
}
$role = 'maker';
$cap = (float) ($bonus[$node['level']] ?? 0);
if (!$active->isActive($node['agent'] ?? $node)) {
PartnerRewardService::writeSkip($order, $buyerId, $node['user_id'], 'maker_diff', $role, 'inactive_30d', '创客 30 日无自购,不占水位');
continue;
}
if ($cap <= $seen) {
PartnerRewardService::writeSkip($order, $buyerId, $node['user_id'], 'maker_diff', $role, 'cap_not_higher', "水位 {$seen},等级基数 {$cap}");
continue;
}
$pay = round($cap - $seen, 2);
PartnerRewardService::account($order, $buyerId, $node['user_id'], 'maker_diff', $role, $pay, $cap, [
'formula' => "极差 {$cap} - {$seen} = {$pay}",
'seen_before' => $seen,
'cap' => $cap,
'level' => $node['level'],
]);
$seen = $cap;
$paid[] = [
'user_id' => $node['user_id'],
'level' => $node['level'],
'cap' => $cap,
'amount' => $pay,
];
}
return ['seen' => $seen, 'paid' => $paid];
}
}

查看文件

@@ -0,0 +1,82 @@
<?php
namespace addons\shopro\service\partner;
/**
* 创客平级 10% / 被超越 5%,只一层
*/
class MakerPeerReward
{
public function run($order, $buyerId, $chain, $diffResult, ActiveService $active)
{
$bonus = PartnerConfig::makerBonus();
$peerRate = (float) PartnerConfig::get('partner_maker_peer_rate', 0.10);
$overRate = (float) PartnerConfig::get('partner_maker_overtaken_rate', 0.05);
$paid = $diffResult['paid'] ?? [];
$indexByUser = [];
foreach ($chain as $i => $node) {
$indexByUser[$node['user_id']] = $i;
}
foreach ($paid as $item) {
$from = $indexByUser[$item['user_id']] ?? -1;
if ($from < 0) {
continue;
}
$peer = $this->findUp($chain, $from + 1, function ($node) use ($item) {
return intval($node['level']) === intval($item['level']);
});
if (!$peer) {
continue;
}
$levelBonus = (float) ($bonus[$item['level']] ?? 0);
$amount = round($levelBonus * $peerRate, 2);
if (!$active->isActive($peer['agent'] ?? $peer)) {
PartnerRewardService::writeSkip($order, $buyerId, $peer['user_id'], 'maker_peer', 'maker', 'inactive_30d', '平级创客 30 日无自购');
continue;
}
if ($amount <= 0) {
continue;
}
PartnerRewardService::account($order, $buyerId, $peer['user_id'], 'maker_peer', 'maker', $amount, $levelBonus, [
'formula' => "平级 {$levelBonus} × " . ($peerRate * 100) . "% = {$amount}",
'from_user_id' => $item['user_id'],
'level' => $item['level'],
]);
}
if (empty($paid)) {
return;
}
$highest = $paid[count($paid) - 1];
$from = $indexByUser[$highest['user_id']] ?? -1;
$lower = $this->findUp($chain, $from + 1, function ($node) use ($highest) {
return intval($node['level']) >= 2 && intval($node['level']) < intval($highest['level']);
});
if (!$lower) {
return;
}
$amount = round((float) $highest['cap'] * $overRate, 2);
if (!$active->isActive($lower['agent'] ?? $lower)) {
PartnerRewardService::writeSkip($order, $buyerId, $lower['user_id'], 'maker_overtaken', 'maker', 'inactive_30d', '被超越创客 30 日无自购');
return;
}
if ($amount <= 0) {
return;
}
PartnerRewardService::account($order, $buyerId, $lower['user_id'], 'maker_overtaken', 'maker', $amount, $highest['cap'], [
'formula' => "超越奖 最高水位 {$highest['cap']} × " . ($overRate * 100) . "% = {$amount}",
'from_user_id' => $highest['user_id'],
]);
}
protected function findUp($chain, $start, $matcher)
{
for ($i = $start; $i < count($chain); $i++) {
if ($matcher($chain[$i])) {
return $chain[$i];
}
}
return null;
}
}

查看文件

@@ -0,0 +1,145 @@
<?php
namespace addons\shopro\service\partner;
/**
* 合伙股东配置读取
*/
class PartnerConfig
{
public static function get($key, $default = null)
{
$code = strpos($key, 'shop.commission.') === 0 ? $key : 'shop.commission.' . $key;
$value = sheep_config($code);
if ($value === null || $value === '') {
return $default;
}
return $value;
}
public static function isPartnerMode()
{
return (bool) self::get('partner_mode', 0);
}
public static function isEnabled()
{
$enable = self::get('partner_enable', 1);
return $enable === null ? true : (bool) $enable;
}
public static function activeDays()
{
$days = intval(self::get('partner_active_days', 30));
return $days > 0 ? $days : 30;
}
public static function chainMaxDepth()
{
$depth = intval(self::get('partner_chain_max_depth', 50));
return $depth > 0 ? $depth : 50;
}
public static function push3Amounts()
{
$amounts = self::get('partner_push3_amounts', [398, 400, 600]);
if (!is_array($amounts) || count($amounts) < 3) {
return [398, 400, 600];
}
return array_map('floatval', array_values($amounts));
}
public static function makerBonus()
{
$bonus = self::get('partner_maker_bonus', [2 => 20, 3 => 40, 4 => 60, 5 => 80, 6 => 100, 7 => 120]);
if (!is_array($bonus)) {
return [2 => 20, 3 => 40, 4 => 60, 5 => 80, 6 => 100, 7 => 120];
}
$map = [];
foreach ($bonus as $level => $amount) {
$map[intval($level)] = floatval($amount);
}
return $map;
}
public static function rewardTypeText($type)
{
$map = self::rewardTypeMap();
return $map[$type] ?? $type;
}
public static function rewardTypeMap()
{
return [
'push3' => '推三返一',
'maker_diff' => '创客极差奖',
'maker_peer' => '创客平级奖',
'maker_overtaken' => '创客超越奖',
'team_venue' => '酒道馆团队奖',
'team_county' => '区县团队奖',
'venue_peer' => '酒道馆平级奖',
'county_peer' => '区县平级奖',
'venue_share' => '酒道馆平台均分',
'county_share' => '区县平台均分',
'madow_share' => '每日分红马豆',
'voucher_grant' => '兑换券发放',
'voucher_release' => '兑换券释放',
];
}
public static function skipReasonText($code, $forUser = false)
{
$inner = [
'no_parent' => '无直推上级',
'self_buy' => '自购',
'inactive_30d' => '受益人 30 日无自购',
'not_maker' => '不是创客',
'not_venue' => '不是酒道馆',
'not_county' => '不是区县代理',
'cap_not_higher' => '等级未超过水位',
'already_settled' => '幂等跳过',
'partner_goods_off' => '商品未参与',
'partner_off' => '结算未开启',
];
$user = [
'no_parent' => '暂无推荐人,不产生推三返一',
'self_buy' => '自己下单不产生推三返一',
'inactive_30d' => '需 30 日内有本人订单才能领取',
'not_maker' => '',
'not_venue' => '',
'not_county' => '',
'cap_not_higher' => '平级不发极差,走平级奖',
'already_settled' => '',
'partner_goods_off' => '',
'partner_off' => '',
];
if ($forUser) {
return $user[$code] ?? '';
}
return $inner[$code] ?? $code;
}
public static function statusText($status)
{
$map = [
0 => '待入账',
1 => '已入账',
-1 => '已取消',
-2 => '已退回',
];
return $map[intval($status)] ?? '';
}
public static function instantTypes()
{
return [
'push3', 'maker_diff', 'maker_peer', 'maker_overtaken',
'team_venue', 'team_county', 'venue_peer', 'county_peer',
];
}
public static function dailyTypes()
{
return ['venue_share', 'county_share', 'madow_share', 'voucher_release'];
}
}

查看文件

@@ -0,0 +1,220 @@
<?php
namespace addons\shopro\service\partner;
use think\Db;
use addons\shopro\service\Wallet;
use app\admin\model\shopro\partner\Reward as RewardModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\commission\CommissionGoods;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 订单即时奖入口 + 退款回滚
*/
class PartnerRewardService
{
public function settleOrder($orderId)
{
if (!PartnerConfig::isEnabled()) {
return false;
}
$order = OrderModel::with(['items'])->where('id', $orderId)->lock(true)->find();
if (!$order) {
return false;
}
if (!$this->isQualified($order)) {
return false;
}
$exists = RewardModel::where('order_id', $orderId)->where('order_id', '>', 0)->find();
if ($exists) {
return true;
}
$buyerId = intval($order['user_id']);
$active = new ActiveService();
$chainService = new ChainService();
$parentChain = $chainService->collect($buyerId, false);
$selfChain = $chainService->collect($buyerId, true);
$parent = $parentChain[0] ?? null;
(new Push3Reward())->run($order, $buyerId, $parent, $active);
$diff = (new MakerDiffReward())->run($order, $buyerId, $parentChain, $active);
(new MakerPeerReward())->run($order, $buyerId, $parentChain, $diff, $active);
$team = (new TeamSplitReward())->run($order, $buyerId, $selfChain, $active);
(new PeerShareReward())->run($order, $buyerId, $selfChain, $team, $active);
(new VoucherService())->grant($order, $buyerId);
return true;
}
public function refund($orderId)
{
$rewards = RewardModel::where('order_id', $orderId)
->where('order_id', '>', 0)
->where('status', 1)
->whereIn('reward_type', array_merge(PartnerConfig::instantTypes(), ['voucher_grant']))
->lock(true)
->select();
$order = OrderModel::where('id', $orderId)->find();
if ($order) {
(new VoucherService())->refundConsume($order);
}
if (!$rewards || count($rewards) == 0) {
(new VoucherService())->closeByOrder($orderId);
return;
}
foreach ($rewards as $reward) {
if (in_array($reward->reward_type, PartnerConfig::instantTypes()) && (float) $reward->amount > 0 && $reward->user_id > 0) {
Wallet::change($reward->user_id, 'commission', -$reward->amount, 'reward_back', [
'partner_reward_id' => $reward->id,
'order_id' => $orderId,
], '合伙股东收益退回');
AgentModel::where('user_id', $reward->user_id)->setDec('total_income', $reward->amount);
}
if ($reward->reward_type === 'push3' && $reward->user_id > 0) {
(new Push3Reward())->rollbackSeq($reward->user_id);
}
$reward->status = -2;
$reward->save();
}
(new VoucherService())->closeByOrder($orderId);
}
public function isQualified($order)
{
if (!$order || ($order['type'] ?? '') === 'score') {
return false;
}
if ((float) ($order['pay_fee'] ?? 0) <= 0) {
return false;
}
$status = $order['status'] ?? '';
if (!in_array($status, [OrderModel::STATUS_PAID, OrderModel::STATUS_COMPLETED])) {
return false;
}
$items = $order['items'] ?? [];
if (empty($items) && !empty($order['id'])) {
$fresh = OrderModel::with(['items'])->where('id', $order['id'])->find();
if ($fresh) {
$order = $fresh;
$items = $fresh['items'] ?? [];
}
}
foreach ($items as $item) {
if (isset($item['ext']['is_commission']) && !$item['ext']['is_commission']) {
continue;
}
$goods = CommissionGoods::where('goods_id', $item['goods_id'])
->where('status', CommissionGoods::GOODS_COMMISSION_STATUS_ON)
->find();
if ($goods) {
return true;
}
}
return false;
}
public function touchSelfOrder($userId, $time = null)
{
$agent = AgentModel::where('user_id', $userId)->find();
if ($agent) {
$agent->last_self_order_time = $time ?: time();
$agent->save();
}
}
public static function dailyOrderId($settleDate)
{
return -intval(date('Ymd', strtotime($settleDate)));
}
public static $lastWriteCreated = false;
public static function write($data)
{
self::$lastWriteCreated = false;
$now = time();
$payload = array_merge([
'order_id' => 0,
'buyer_id' => 0,
'user_id' => 0,
'role' => '',
'reward_type' => '',
'amount' => 0,
'madow' => 0,
'base_amount' => 0,
'rate' => 0,
'ext' => [],
'settle_date' => null,
'status' => 0,
'createtime' => $now,
'updatetime' => $now,
], $data);
try {
$row = RewardModel::create($payload);
self::$lastWriteCreated = true;
return $row;
} catch (\Exception $e) {
$msg = $e->getMessage();
if (stripos($msg, 'Duplicate') !== false || stripos($msg, '1062') !== false) {
return RewardModel::where('order_id', $payload['order_id'])
->where('user_id', $payload['user_id'])
->where('reward_type', $payload['reward_type'])
->find();
}
throw $e;
}
}
public static function writeSkip($order, $buyerId, $userId, $type, $role, $reason, $formula = '')
{
$orderId = is_array($order) || $order instanceof \think\Model ? ($order['id'] ?? 0) : intval($order);
return self::write([
'order_id' => $orderId,
'buyer_id' => $buyerId,
'user_id' => $userId,
'role' => $role,
'reward_type' => $type,
'amount' => 0,
'base_amount' => 0,
'ext' => [
'skip_reason' => $reason,
'formula' => $formula ?: PartnerConfig::skipReasonText($reason),
],
'status' => -1,
]);
}
public static function account($order, $buyerId, $userId, $type, $role, $amount, $base, $ext = [])
{
$orderId = is_array($order) || $order instanceof \think\Model ? ($order['id'] ?? 0) : intval($order);
$row = self::write([
'order_id' => $orderId,
'buyer_id' => $buyerId,
'user_id' => $userId,
'role' => $role,
'reward_type' => $type,
'amount' => $amount,
'base_amount' => $base,
'ext' => $ext,
'status' => 1,
]);
if ($row && self::$lastWriteCreated && (float) $amount > 0 && $userId > 0 && $row->status == 1 && in_array($type, PartnerConfig::instantTypes())) {
Wallet::change($userId, 'commission', $amount, $type, [
'partner_reward_id' => $row->id,
'order_id' => $orderId,
]);
AgentModel::where('user_id', $userId)->setInc('total_income', $amount);
}
return $row;
}
}

查看文件

@@ -0,0 +1,50 @@
<?php
namespace addons\shopro\service\partner;
/**
* 酒道馆 / 区县平级 10%,基数为本单该下级的团队奖
*/
class PeerShareReward
{
public function run($order, $buyerId, $chain, $teamResult, ActiveService $active)
{
$venueRate = (float) PartnerConfig::get('partner_venue_peer_rate', 0.10);
$countyRate = (float) PartnerConfig::get('partner_county_peer_rate', 0.10);
if (!empty($teamResult['venue'])) {
$this->peer($order, $buyerId, $chain, $teamResult['venue'], 'is_venue', 'venue_peer', 'venue', $venueRate, $active, '酒道馆');
}
if (!empty($teamResult['county'])) {
$this->peer($order, $buyerId, $chain, $teamResult['county'], 'is_county', 'county_peer', 'county', $countyRate, $active, '区县');
}
}
protected function peer($order, $buyerId, $chain, $from, $flag, $type, $role, $rate, ActiveService $active, $label)
{
$start = intval($from['index']) + 1;
$peer = null;
for ($i = $start; $i < count($chain); $i++) {
if (intval($chain[$i][$flag] ?? 0)) {
$peer = $chain[$i];
break;
}
}
if (!$peer) {
return;
}
$base = (float) $from['amount'];
$amount = round($base * $rate, 2);
if (!$active->isActive($peer['agent'] ?? $peer)) {
PartnerRewardService::writeSkip($order, $buyerId, $peer['user_id'], $type, $role, 'inactive_30d', "{$label}平级 30 日无自购");
return;
}
if ($amount <= 0) {
return;
}
PartnerRewardService::account($order, $buyerId, $peer['user_id'], $type, $role, $amount, $base, [
'formula' => "{$label}平级 {$base} × " . ($rate * 100) . "% = {$amount}",
'from_user_id' => $from['user_id'],
]);
}
}

查看文件

@@ -0,0 +1,56 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 推三返一:398/400/600 循环,计到直推上级,自购不发
*/
class Push3Reward
{
public function run($order, $buyerId, $parent, ActiveService $active)
{
if (!$parent) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'push3', 'taster', 'no_parent', '无直推上级');
return;
}
if (intval($parent['user_id']) === intval($buyerId)) {
PartnerRewardService::writeSkip($order, $buyerId, $parent['user_id'], 'push3', 'taster', 'self_buy', '自购不产生推三返一');
return;
}
if (intval($parent['level']) < 1) {
PartnerRewardService::writeSkip($order, $buyerId, $parent['user_id'], 'push3', 'taster', 'no_parent', '直推上级不是品酒师/创客');
return;
}
if (!$active->isActive($parent['agent'] ?? $parent)) {
PartnerRewardService::writeSkip($order, $buyerId, $parent['user_id'], 'push3', 'taster', 'inactive_30d', '直推上级 30 日无自购');
return;
}
$agent = AgentModel::where('user_id', $parent['user_id'])->lock(true)->find();
if (!$agent) {
return;
}
$agent->direct_order_seq = intval($agent->direct_order_seq) + 1;
$agent->save();
$amounts = PartnerConfig::push3Amounts();
$seq = intval($agent->direct_order_seq);
$amount = $amounts[($seq - 1) % 3];
PartnerRewardService::account($order, $buyerId, $agent->user_id, 'push3', 'taster', $amount, $amount, [
'formula' => "直推第{$seq}单,循环第" . ((($seq - 1) % 3) + 1) . "档 +{$amount}",
'seq' => $seq,
]);
}
public function rollbackSeq($userId)
{
$agent = AgentModel::where('user_id', $userId)->lock(true)->find();
if ($agent && $agent->direct_order_seq > 0) {
$agent->direct_order_seq = $agent->direct_order_seq - 1;
$agent->save();
}
}
}

查看文件

@@ -0,0 +1,81 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\partner\RateLog;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\commission\CommissionGoods;
/**
* 马豆汇率:rate = base * floor(N / n)
*/
class RateService
{
public function currentRate()
{
$latest = RateLog::order('id', 'desc')->find();
if ($latest && (float) $latest->rate > 0) {
return (float) $latest->rate;
}
return $this->calcRate($this->countN());
}
public function calcRate($n = null)
{
$n = $n === null ? $this->countN() : intval($n);
$base = (float) PartnerConfig::get('partner_madow_base_rate', 0.00000075);
$step = intval(PartnerConfig::get('partner_madow_step_orders', 1));
$step = $step > 0 ? $step : 1;
return $base * floor($n / $step);
}
public function countN()
{
return $this->qualifiedOrderQuery()->count();
}
public function snapshot($settleDate, $gmv = 0, $extra = [])
{
$n = $this->countN();
$rate = $this->calcRate($n);
$row = RateLog::where('settle_date', $settleDate)->find();
$data = array_merge([
'settle_date' => $settleDate,
'order_count_n' => $n,
'rate' => $rate,
'gmv' => $gmv,
'createtime' => time(),
], $extra);
if ($row) {
$row->save($data);
return $row;
}
return RateLog::create($data);
}
public function qualifiedOrderQuery($start = null, $end = null)
{
$goodsTable = (new CommissionGoods())->getQuery()->getTable();
$orderTable = (new OrderModel())->getQuery()->getTable();
$itemTable = \think\Db::name('shopro_order_item')->getTable();
$query = OrderModel::alias('o')
->where('o.type', '<>', 'score')
->where('o.pay_fee', '>', 0)
->whereIn('o.status', [OrderModel::STATUS_PAID, OrderModel::STATUS_COMPLETED])
->whereExists(function ($q) use ($orderTable, $itemTable, $goodsTable) {
$q->table($itemTable)->alias('oi')
->join($goodsTable . ' cg', 'cg.goods_id = oi.goods_id')
->whereRaw('oi.order_id = o.id')
->where('cg.status', CommissionGoods::GOODS_COMMISSION_STATUS_ON);
});
if ($start !== null) {
$query->where('o.paid_time', '>=', $start);
}
if ($end !== null) {
$query->where('o.paid_time', '<=', $end);
}
return $query;
}
}

查看文件

@@ -0,0 +1,88 @@
<?php
namespace addons\shopro\service\partner;
/**
* 团队拆 100:无馆有县=100;有馆有县=50+50;有馆无县=50
*/
class TeamSplitReward
{
public function run($order, $buyerId, $chain, ActiveService $active)
{
$venueSplit = (float) PartnerConfig::get('partner_venue_split', 50);
$countyFull = (float) PartnerConfig::get('partner_county_full', 100);
$result = ['venue' => null, 'county' => null];
$venue = $this->nearest($chain, 'is_venue', $active);
$county = $this->nearestCounty($chain, $venue, $active);
if (!$venue && !$county) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_venue', 'system', 'not_venue', '链上无酒道馆且无区县');
return $result;
}
if ($venue) {
if ($venue['inactive']) {
PartnerRewardService::writeSkip($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', 'inactive_30d', '酒道馆 30 日无自购');
} else {
PartnerRewardService::account($order, $buyerId, $venue['user_id'], 'team_venue', 'venue', $venueSplit, $venueSplit, [
'formula' => "酒道馆团队拆分 {$venueSplit}",
]);
$result['venue'] = ['user_id' => $venue['user_id'], 'amount' => $venueSplit, 'index' => $venue['index']];
}
}
if ($county) {
$amount = $venue ? $venueSplit : $countyFull;
if ($county['inactive']) {
PartnerRewardService::writeSkip($order, $buyerId, $county['user_id'], 'team_county', 'county', 'inactive_30d', '区县 30 日无自购');
} else {
PartnerRewardService::account($order, $buyerId, $county['user_id'], 'team_county', 'county', $amount, $amount, [
'formula' => $venue ? "区县团队拆分 {$amount}(馆上)" : "无馆区县全额 {$amount}",
]);
$result['county'] = ['user_id' => $county['user_id'], 'amount' => $amount, 'index' => $county['index']];
}
} elseif ($venue && !$county) {
PartnerRewardService::writeSkip($order, $buyerId, 0, 'team_county', 'system', 'not_county', '有馆无区县');
}
return $result;
}
protected function nearest($chain, $flag, ActiveService $active)
{
foreach ($chain as $i => $node) {
if (!intval($node[$flag] ?? 0)) {
continue;
}
return [
'user_id' => $node['user_id'],
'index' => $i,
'inactive' => !$active->isActive($node['agent'] ?? $node),
'node' => $node,
];
}
return null;
}
protected function nearestCounty($chain, $venue, ActiveService $active)
{
$start = $venue ? ($venue['index'] + 1) : 0;
for ($i = $start; $i < count($chain); $i++) {
if (!intval($chain[$i]['is_county'] ?? 0)) {
continue;
}
return [
'user_id' => $chain[$i]['user_id'],
'index' => $i,
'inactive' => !$active->isActive($chain[$i]['agent'] ?? $chain[$i]),
'node' => $chain[$i],
];
}
// 无馆时从链头找区县(含自购区县)
if (!$venue) {
return $this->nearest($chain, 'is_county', $active);
}
return null;
}
}

查看文件

@@ -0,0 +1,281 @@
<?php
namespace addons\shopro\service\partner;
use app\admin\model\shopro\partner\VoucherPlan;
use app\admin\model\shopro\partner\Reward as RewardModel;
use app\admin\model\shopro\commission\Agent as AgentModel;
/**
* 兑换券 1.5 倍 / 365 天释放
*/
class VoucherService
{
public function available($userId)
{
$agent = AgentModel::where('user_id', $userId)->find();
if (!$agent) {
return 0;
}
return max(0, round((float) $agent->voucher_released - (float) $agent->voucher_used, 2));
}
public function consume($userId, $amount, $orderId = 0)
{
$amount = round((float) $amount, 2);
if ($amount <= 0) {
return true;
}
$agent = AgentModel::where('user_id', $userId)->lock(true)->find();
if (!$agent) {
error_stop('兑换券账户不存在');
}
$available = max(0, round((float) $agent->voucher_released - (float) $agent->voucher_used, 2));
if (bccomp((string) $available, (string) $amount, 2) < 0) {
error_stop('兑换券可用额度不足');
}
$agent->setInc('voucher_used', $amount);
return true;
}
public function refundConsume($order)
{
$ext = $order['ext'] ?? [];
if (is_string($ext)) {
$ext = json_decode($ext, true) ?: [];
}
$fee = round((float) ($ext['voucher_fee'] ?? 0), 2);
if ($fee <= 0 || empty($ext['voucher_consumed'])) {
return;
}
$userId = intval($order['user_id'] ?? 0);
$agent = AgentModel::where('user_id', $userId)->lock(true)->find();
if ($agent) {
$agent->voucher_used = max(0, round((float) $agent->voucher_used - $fee, 2));
$agent->save();
}
}
public function consumeByOrder($order)
{
$ext = $order['ext'] ?? [];
if (is_string($ext)) {
$ext = json_decode($ext, true) ?: [];
}
$fee = round((float) ($ext['voucher_fee'] ?? 0), 2);
if ($fee <= 0 || !empty($ext['voucher_consumed'])) {
return;
}
$this->consume(intval($order['user_id']), $fee, intval($order['id'] ?? 0));
if (is_object($order) && method_exists($order, 'save')) {
$ext['voucher_consumed'] = 1;
$order->ext = $ext;
$order->save();
}
}
public function grant($order, $buyerId)
{
$exists = VoucherPlan::where('order_id', $order['id'])->find();
if ($exists) {
return $exists;
}
$times = (float) PartnerConfig::get('partner_voucher_times', 1.5);
$days = intval(PartnerConfig::get('partner_voucher_days', 365));
$days = $days > 0 ? $days : 365;
$total = round((float) $order['pay_fee'] * $times, 2);
if ($total <= 0) {
return null;
}
$daily = round($total / $days, 2);
$startDate = date('Y-m-d', strtotime('+1 day', $this->orderTime($order)));
$plan = VoucherPlan::create([
'user_id' => $buyerId,
'order_id' => $order['id'],
'total_amount' => $total,
'daily_amount' => $daily,
'released_amount' => 0,
'released_days' => 0,
'total_days' => $days,
'start_date' => $startDate,
'status' => 1,
'createtime' => time(),
]);
$agent = AgentModel::where('user_id', $buyerId)->find();
if ($agent) {
$agent->setInc('voucher_total', $total);
}
PartnerRewardService::write([
'order_id' => $order['id'],
'buyer_id' => $buyerId,
'user_id' => $buyerId,
'role' => 'taster',
'reward_type' => 'voucher_grant',
'amount' => 0,
'base_amount' => $total,
'ext' => ['formula' => "实付{$order['pay_fee']} × {$times} = {$total},{$days}天释放"],
'status' => 1,
]);
return $plan;
}
public function releaseByDate($settleDate)
{
$plans = VoucherPlan::where('status', 1)
->where('start_date', '<=', $settleDate)
->select();
$byUser = [];
foreach ($plans as $plan) {
$amount = $this->releaseOne($plan, $settleDate);
if ($amount <= 0) {
continue;
}
$uid = intval($plan->user_id);
if (!isset($byUser[$uid])) {
$byUser[$uid] = ['amount' => 0, 'plans' => []];
}
$byUser[$uid]['amount'] = bcadd((string) $byUser[$uid]['amount'], (string) $amount, 2);
$byUser[$uid]['plans'][] = $plan->id;
}
$totalReleased = 0;
foreach ($byUser as $userId => $info) {
PartnerRewardService::write([
'order_id' => PartnerRewardService::dailyOrderId($settleDate),
'buyer_id' => $userId,
'user_id' => $userId,
'role' => 'taster',
'reward_type' => 'voucher_release',
'amount' => $info['amount'],
'base_amount' => $info['amount'],
'settle_date' => $settleDate,
'ext' => [
'formula' => "兑换券释放 {$info['amount']}",
'plan_ids' => $info['plans'],
],
'status' => 1,
]);
$totalReleased = bcadd((string) $totalReleased, (string) $info['amount'], 2);
}
return (float) $totalReleased;
}
public function releaseOne($plan, $settleDate)
{
if ($plan->status != 1) {
return 0;
}
if ($plan->released_days >= $plan->total_days) {
$plan->status = 2;
$plan->save();
return 0;
}
if ($plan->start_date > $settleDate) {
return 0;
}
$leftDays = $plan->total_days - $plan->released_days;
if ($leftDays <= 1) {
$amount = round((float) $plan->total_amount - (float) $plan->released_amount, 2);
$plan->status = 2;
} else {
$amount = (float) $plan->daily_amount;
}
if ($amount <= 0) {
$plan->status = 2;
$plan->save();
return 0;
}
$plan->released_amount = round((float) $plan->released_amount + $amount, 2);
$plan->released_days += 1;
$plan->save();
$agent = AgentModel::where('user_id', $plan->user_id)->find();
if ($agent) {
$agent->setInc('voucher_released', $amount);
}
return $amount;
}
public function closeByOrder($orderId)
{
$plan = VoucherPlan::where('order_id', $orderId)->find();
if (!$plan || $plan->status == 0) {
return;
}
$plan->status = 0;
$plan->save();
$agent = AgentModel::where('user_id', $plan->user_id)->find();
if ($agent) {
$unusedReleased = max(0, (float) $plan->released_amount);
$newReleased = max(0, (float) $agent->voucher_released - $unusedReleased);
$newTotal = max(0, (float) $agent->voucher_total - (float) $plan->total_amount);
if ($newReleased < (float) $agent->voucher_used) {
$newReleased = (float) $agent->voucher_used;
}
$agent->voucher_released = $newReleased;
$agent->voucher_total = $newTotal;
$agent->save();
}
}
public function rollbackRelease($settleDate)
{
$rows = RewardModel::where('settle_date', $settleDate)
->where('reward_type', 'voucher_release')
->where('status', 1)
->select();
foreach ($rows as $row) {
$planIds = $row->ext['plan_ids'] ?? [];
if (!$planIds && !empty($row->ext['plan_id'])) {
$planIds = [$row->ext['plan_id']];
}
foreach ($planIds as $planId) {
$plan = VoucherPlan::get($planId);
if (!$plan) {
continue;
}
$daily = (float) $plan->daily_amount;
$plan->released_amount = max(0, (float) $plan->released_amount - $daily);
$plan->released_days = max(0, $plan->released_days - 1);
if ($plan->status == 2 && $plan->released_days < $plan->total_days) {
$plan->status = 1;
}
$plan->save();
}
$agent = AgentModel::where('user_id', $row->user_id)->find();
if ($agent) {
$agent->voucher_released = max(0, (float) $agent->voucher_released - (float) $row->amount);
$agent->save();
}
}
}
protected function orderTime($order)
{
$paid = $order['paid_time'] ?? 0;
if (is_numeric($paid) && $paid > 0) {
return intval($paid);
}
if (is_string($paid) && $paid !== '') {
$ts = strtotime($paid);
if ($ts) {
return $ts;
}
}
return time();
}
protected function dailyOrderId($settleDate, $planId)
{
// 避免 uk_order_user_type 日结撞车:负日期 + 计划尾巴
return -intval(date('Ymd', strtotime($settleDate))) * 100 + intval($planId) % 100;
}
}