文件
MiAn 111054d984 feat: 新增会员浏览/拨打额度并优化无图展示逻辑
新增会员每日浏览完整信息和拨打电话的额度配置,调整付费查看接口描述为解锁完整信息,优化帖子无图时的兜底展示逻辑,修复图片加载路径问题,删除废弃工具脚本。
2026-10-28 11:06:39 +08:00

1907 行
80 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\api\controller;
use think\Db;
use app\common\library\DistributionService;
use app\common\library\CouponService;
use app\common\library\NationalArea;
/**
* 用户端 · 信息发布与详情(Module-POST)
* 路由:
* POST /api/v1/post/upload P0 发布媒体上传(图片/视频)
* POST /api/v1/post/create P1 发布信息(服务端定价)
* GET /api/v1/post/mine P8 我的发布(含审核状态与计数)
* GET /api/v1/post/publish-config P9 发布配置(发布模式/价格/我的剩余额度)
* GET /api/v1/post/drafts P2 草稿列表
* POST /api/v1/post/draft P3 保存草稿
* DELETE /api/v1/post/:id P4 删除信息
* GET /api/v1/post/:id P5 信息详情
* POST /api/v1/post/:id/pay-view P6 付费查看联系方式
* POST /api/v1/post/:id/comment P7 发表评价
* POST /api/v1/post/comment/:id/reply P11 发布者回复评价
* GET /api/v1/post/:id/comments P10 评价列表(详情页「用户评价」)
*
* 计费口径(后台「发布与费用配置」维护,真源=fc_config);
* 金额一律由服务端按配置计算,**不接受客户端传入金额**;
* 判定顺序:① 套餐额度(fc_user_ext.post_quota_left,开通月/年卡赠送)
* → ② 免费发布条数(post.freeQuota,按 post.freeQuotaCycle 统计周期,0 = 不限制)
* → ③ 单条付费(post.singlePrice,即「付费发布」标准);
* 免费发布模式下免费条数用完即按 ③ 计费(客户端需切到「会员单条」并选支付方式重新提交);
* 月卡/年卡(含发布条数)的购买复用 POST /member/open,本控制器只处理
* 「套餐额度/免费条数内免费发布」与「单条付费发布」两种。
*/
class Post extends V1
{
/**
* P0 发布媒体上传
* POST /api/v1/post/upload multipart: file(+ 可选 type=image|video)
* → {url,type,size,name}
* 白名单:图片 jpg/jpeg/png/gif/webp(≤10MB)、视频 mp4/mov(≤50MB);
* 按「扩展名 + 真实 MIME(finfo)」双重校验(防改后缀绕过);
* 落盘 public/uploads/YYYYMMDD/<md5>.<ext>,返回相对 URL(形如 /uploads/20261017/xxx.jpg),
* 与 fa_user.avatar 存储口径一致(相对路径入库、前端自行拼域名)。
*/
public function uploadMedia()
{
$this->auth();
$file = $this->request->file('file');
if (!$file) {
$this->fail('未接收到上传文件');
}
$info = $file->getInfo();
$name = isset($info['name']) ? (string)$info['name'] : '';
$size = isset($info['size']) ? (int)$info['size'] : 0;
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
// 扩展名白名单:[媒体类型, 体积上限(字节), 允许的真实 MIME]
// 图片限制 ≤ 5MB,保障顶部轮播加载速度与清晰度
$allow = [
'jpg' => ['image', 5 * 1024 * 1024, ['image/jpeg']],
'jpeg' => ['image', 5 * 1024 * 1024, ['image/jpeg']],
'png' => ['image', 5 * 1024 * 1024, ['image/png']],
'gif' => ['image', 5 * 1024 * 1024, ['image/gif']],
'webp' => ['image', 5 * 1024 * 1024, ['image/webp']],
'mp4' => ['video', 50 * 1024 * 1024, ['video/mp4']],
'mov' => ['video', 50 * 1024 * 1024, ['video/quicktime']],
];
if (!isset($allow[$ext])) {
$this->fail('文件类型不支持');
}
list($type, $maxSize, $mimes) = $allow[$ext];
// 客户端可选声明 type:与扩展名推导出的类型不一致时按非法类型拒绝
$wantType = strtolower(trim((string)$this->input('type', '')));
if ($wantType !== '' && $wantType !== $type) {
$this->fail('文件类型不支持');
}
if ($size <= 0) {
$this->fail('文件大小超出限制');
}
if ($size > $maxSize) {
$this->fail($type === 'image' ? '单张图片大小不能超过 5MB' : '文件大小超出限制');
}
// 真实 MIME 双重校验(读临时文件头,图片/视频都必须命中白名单);
// 服务器未启用 finfo 时跳过(退化为扩展名 + makeUpload 的 checkImg 兜底)
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = $finfo ? (string)finfo_file($finfo, $file->getPathname()) : '';
if ($finfo) {
finfo_close($finfo);
}
if ($mime === '' || !in_array($mime, $mimes, true)) {
$this->fail('文件类型不支持');
}
}
// 轮播图片宽高比校验(0.75 ~ 2.2,即 3:4 至 16:9 之间,避免极端长条图破坏详情页轮播展示)
$imgWidth = 0;
$imgHeight = 0;
if ($type === 'image' && function_exists('getimagesize')) {
$imgInfo = @getimagesize($file->getPathname());
if (is_array($imgInfo) && !empty($imgInfo[0]) && !empty($imgInfo[1])) {
$imgWidth = (int)$imgInfo[0];
$imgHeight = (int)$imgInfo[1];
if ($imgWidth >= 50 && $imgHeight >= 50) {
$ratio = $imgWidth / $imgHeight;
if ($ratio < 0.75 || $ratio > 2.2) {
$this->fail('为保障轮播展示效果,请上传宽高比在 3:4 ~ 16:9 之间的横图或方图');
}
}
}
}
$dirName = date('Ymd');
$saveName = $file->hash('md5') . '.' . $ext; // md5 命名:同内容文件天然去重
$destDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . $dirName . DS;
$moved = $file->move($destDir, $saveName, true);
if (!$moved) {
$this->fail('文件上传失败,请稍后重试');
}
$this->ok([
'url' => '/uploads/' . $dirName . '/' . $saveName,
'type' => $type,
'size' => $size,
'name' => $name,
'width' => $imgWidth,
'height' => $imgHeight,
]);
}
/**
* P1 发布信息
* POST /api/v1/post/create
* 入参 {categoryId,title,content,media[],contact,phone,address,areaId?,districtId?,area?,lat?,lng?,plan,payType}
* → {postId,auditStatus,order,plan,amount,discountRate,quotaLeft,freeQuotaLeft}
* 规则 BR-03/BR-04/BR-02/BR-13(计费顺序:套餐额度 → 免费发布条数 → 单条付费)
* 说明:
* - `media` 接收**上传后的 URL 数组**(先调 POST /post/upload 拿 url,再随发布提交);
* - 服务区域为**区县**:优先取 `areaId`(=fc_area.id),兼容 `districtId` / `area` 名称;
* 都没传但带坐标时,按最近服务区域自动归属;均无则允许为空(兼容旧客户端);
* - `lat`/`lng` 可选(gcj02),由前端 chooseLocation 采集,用于首页「附近」排序;
* - 单条付费金额 = round(单条价格 × 会员折扣率, 2),折扣率取自 member.benefit.postDiscount
* (会员权益,非会员/解析失败视作 1);金额一律服务端计算,忽略客户端传值。
*/
public function create()
{
$user = $this->auth();
$categoryId = (int)$this->input('categoryId', 0);
$subCategoryId = (int)$this->input('subCategoryId', 0);
$title = trim((string)$this->input('title', ''));
$content = trim((string)$this->input('content', ''));
if ($categoryId <= 0 && $subCategoryId > 0) {
$categoryId = $subCategoryId;
}
if ($categoryId <= 0) {
$this->fail('分类不能为空');
}
// 若传入的 categoryId 是二级分类(pid > 0),自动归属其一级大类与二级分类
$catRow = Db::name('fc_category')->where('id', $categoryId)->find();
if ($catRow && !empty($catRow['pid']) && (int)$catRow['pid'] > 0) {
$subCategoryId = (int)$catRow['id'];
$categoryId = (int)$catRow['pid'];
} elseif ($subCategoryId > 0) {
$subRow = Db::name('fc_category')->where('id', $subCategoryId)->find();
if ($subRow && !empty($subRow['pid']) && (int)$subRow['pid'] > 0) {
$categoryId = (int)$subRow['pid'];
}
}
if ($title === '') {
$this->fail('标题不能为空');
}
if ($content === '') {
$this->fail('内容不能为空');
}
if (mb_strlen($title) > 40) {
$this->fail('标题不能超过 40 字');
}
if (mb_strlen($content) > 500) {
$this->fail('内容不能超过 500 字');
}
$phone = trim((string)$this->input('phone', ''));
if ($phone !== '' && !preg_match('/^1\d{10}$/', $phone)) {
$this->fail('手机号格式不正确');
}
// ---- 发布计费:金额一律由服务端按后台配置计算,不信任客户端传值 ----
$rule = $this->publishRule();
$plan = trim((string)$this->input('plan', ''));
if ($plan === '' && (bool)$this->input('paid', false)) {
// 兼容 v1.0.6 及更早客户端:paid=true 视为单条付费(金额仍由服务端决定)
$plan = 'single';
}
if ($plan === '') {
$plan = 'free';
}
if (!in_array($plan, ['free', 'single'], true)) {
// 月卡/年卡走会员接口开通(POST /member/open),拿到额度后再以 free 发布
$this->fail('发布方式不支持,请先开通会员套餐');
}
$ext = $this->ext($user['id']);
$quotaLeft = $this->quotaLeft($ext);
$free = $this->freeQuotaState($user['id']);
// 会员发布折扣:member.benefit.postDiscount(如 '8 折'→0.8、'9.5折'→0.95);
// 折扣属**会员权益**,非会员 / 解析失败 / 不含折扣时视作 1(原价)。
$discountRate = $this->memberPostDiscount($ext);
$unitPrice = round($rule['singlePrice'] * $discountRate, 2);
$amount = 0;
$payType = '';
$useQuota = false; // 套餐额度内免费
$useFreeQuota = false; // 免费发布条数内免费
if ($plan === 'single') {
// 单条付费 = 付费发布标准(免费发布条数用完后即按此计费);会员按折扣率计价
$amount = $unitPrice;
$payType = trim((string)$this->input('payType', 'wxpay'));
if ($payType === '') {
$payType = 'wxpay';
}
if ($amount > 0 && !in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
} elseif ($free['unlimited'] || $free['left'] > 0) {
$useFreeQuota = true; // ① 优先消耗全站公共免费额度(或全站免费发布模式),保护会员套餐额度不被白扣
} elseif ($quotaLeft > 0) {
$useQuota = true; // ② 公共免费额度用完后,再扣减会员套餐赠送的发布额度(随会员有效期)
} elseif ($rule['mode'] === 'free') {
$useFreeQuota = true;
} else {
$this->fail('请选择发布方式');
}
$paid = $amount > 0;
// 优惠券(仅单条付费发布可用)
$originAmount = $amount;
$couponAmount = 0;
$userCouponId = 0;
if ($paid && $plan === 'single') {
$userCouponId = (int)$this->input('userCouponId', 0);
if ($userCouponId > 0) {
try {
$couponInfo = CouponService::preview($user['id'], $userCouponId, $originAmount);
} catch (\Throwable $e) {
$this->fail($e->getMessage());
}
$couponAmount = $couponInfo['discount'];
$amount = round($originAmount - $couponAmount, 2);
}
}
// 余额校验须在落库之前(按抵扣后的实付金额判断)
if ($paid && $payType === 'balance') {
if ((float)$user['money'] < $amount) {
$this->fail('余额不足');
}
// 后台开启支付密码时,余额支付需校验
$this->verifyPayPassword($user);
}
// 区域:优先 districtId,其次 area 名称,最后按坐标匹配最近区县
$region = $this->resolveRegion();
// 封面:显式传 cover 优先;否则取媒体里的第一张图片
$cover = trim((string)$this->input('cover', ''));
if ($cover === '') {
foreach ($this->mediaArray() as $m) {
if (!preg_match('/\.(mp4|mov|m4v|avi|wmv|flv|m3u8)(\?|$)/i', $m)) {
$cover = $m;
break;
}
}
}
if ($cover !== '' && !preg_match('#^(/uploads/|https?://)#i', $cover)) {
$this->fail('封面地址不合法');
}
$now = time();
$postId = 0;
$order = null;
$balanceAfter = 0;
$identityTypeInput = (string)$this->input('identityType', 'person');
$identityType = ($identityTypeInput === 'merchant' || $identityTypeInput === '2') ? 2 : 1;
if ($identityType === 2) {
$userExt = Db::name('fc_user_ext')->where('user_id', $user['id'])->find();
if (!$userExt || (int)$userExt['user_type'] !== 2) {
$identityType = 1;
}
}
$price = max(0, round((float)$this->input('price', 0), 2));
$priceUnit = mb_substr(trim((string)$this->input('priceUnit', '')), 0, 16);
if ($price > 0 && $priceUnit === '') {
$priceUnit = '元/斤';
}
$wechat = ''; // 微信字段已移除
$address = mb_substr(trim((string)$this->input('address', '')), 0, 128);
$plantArea = mb_substr(trim((string)$this->input('plantArea', '')), 0, 64);
$harvestTime = mb_substr(trim((string)$this->input('harvestTime', '')), 0, 64);
$outputRange = mb_substr(trim((string)$this->input('outputRange', '')), 0, 64);
// 农产品分类(kind=farm)必须完善产地规格与价格;通用分类(招聘求职等)自动跳过这些校验
$topCatRow = Db::name('fc_category')->where('id', $categoryId)->find();
$isFarmCategory = $topCatRow && isset($topCatRow['kind']) && $topCatRow['kind'] === 'farm';
if ($isFarmCategory) {
if ($plantArea === '' || $harvestTime === '' || $outputRange === '') {
$this->fail('请完善种植面积、采摘时间与预计量产');
}
if ($price <= 0) {
$this->fail('请填写销售价格');
}
}
try {
// 发布落库 + 扣款 + 订单 + 额度扣减 同一事务:任一步失败整体回滚
Db::transaction(function () use (
&$postId, &$order, &$balanceAfter, &$quotaLeft,
$paid, $user, $amount, $originAmount, $couponAmount, $userCouponId, $payType,
$now, $categoryId, $subCategoryId, $identityType, $title, $content, $phone, $wechat, $price, $priceUnit, $address, $plantArea, $harvestTime, $outputRange, $useQuota, $region, $cover
) {
$paidNow = $paid && $payType === 'balance';
// 订单号提前生成:优惠券锁定需要绑定订单号
$orderNo = $paid ? $this->orderNo('PO') : '';
if ($userCouponId > 0) {
CouponService::lock($user['id'], $userCouponId, $originAmount, $orderNo);
}
// 余额扣减:条件更新,并发下不会扣成负数
if ($paidNow) {
$affected = Db::name('user')
->where('id', (int)$user['id'])
->where('money', '>=', $amount)
->setDec('money', $amount);
if (!$affected) {
throw new \RuntimeException('余额不足');
}
$balanceAfter = (float)Db::name('user')->where('id', (int)$user['id'])->value('money');
}
$postId = Db::name('fc_post')->insertGetId([
'user_id' => $user['id'],
'category_id' => $categoryId,
'sub_category_id' => $subCategoryId,
'identity_type' => $identityType,
'title' => $title,
'content' => $content,
'cover' => $cover,
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'price' => $price,
'price_unit' => $priceUnit,
'province' => $region['province'],
'city' => $region['city'],
'area' => $region['area'],
'district_id' => $region['district_id'],
'address' => $address,
'plant_area' => $plantArea,
'harvest_time' => $harvestTime,
'output_range' => $outputRange,
'contact' => (string)$this->input('contact', ''),
'phone' => $phone,
'wechat' => $wechat,
'tags' => $this->tagsString(),
// LBS 坐标(gcj02;未定位/为 0 时存 NULL,首页「附近」不参与距离排序)
'lat' => $this->coord('lat', 90),
'lng' => $this->coord('lng', 180),
'is_paid' => ($paid && $paidNow) ? 1 : 0, // 微信支付发帖未付款前为 0,防止未支付信息外泄
'amount' => $paid ? $amount : 0,
'pay_type' => $paid ? $payType : '',
'audit_status' => 0,
'views' => 0,
'likes' => 0,
'comment_count' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paid) {
// 余额支付为「即时支付」:扣款 + 订单直接 paid;
// 微信支付保持 pending,由支付回调置为 paid 并发放权益。
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'post',
'title' => $title,
'amount' => $amount,
'origin_amount' => $originAmount,
'coupon_amount' => $couponAmount,
'coupon_id' => $userCouponId > 0 ? $userCouponId : 0,
'pay_type' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
'paytime' => $paidNow ? $now : null,
'related_id' => $postId,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paidNow) {
$this->flow('income', '发布付费', $amount, $balanceAfter, $postId, '', (int)$user['id']);
// 钱包流水(fa_user.money 减,用户口径为支出)→ 余额中心「余额明细」
$this->walletFlow($user['id'], 'expense', '发布付费', $amount, $balanceAfter, $postId, $title);
// 余额支付:核销优惠券 + 触发分销结算
CouponService::markUsed($orderNo);
$orderRow = Db::name('fc_order')->where('order_no', $orderNo)->find();
if ($orderRow) {
DistributionService::settleOrder($orderRow);
}
}
$order = [
'orderNo' => $orderNo,
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
'payType' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
];
}
// 套餐额度内免费发布:落库成功后扣减 1 条额度(先发布后扣,发布失败不白扣)
if ($useQuota) {
$quotaLeft = max(0, $quotaLeft - 1);
Db::name('fc_user_ext')->where('user_id', $user['id'])->update([
'post_quota_left' => $quotaLeft,
'updatetime' => $now,
]);
}
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '发布失败,请重试');
}
$this->ok([
'postId' => $postId,
'auditStatus' => 0,
'order' => $order,
'plan' => $useQuota ? 'quota' : ($useFreeQuota ? 'free' : ($paid ? 'single' : 'free')),
'amount' => $amount,
'originAmount' => $originAmount,
'couponAmount' => $couponAmount,
// 本次生效的会员发布折扣率(非会员/未配置为 1)
'discountRate' => $discountRate,
'quotaLeft' => $quotaLeft,
// -1 = 不限制(免费发布模式且未设置免费条数)
'freeQuotaLeft' => $free['unlimited'] ? -1 : max(0, $free['left'] - ($useFreeQuota ? 1 : 0)),
]);
}
/**
* P8 我的发布
* GET /api/v1/post/mine {status?,page,size}
* → {list,page,size,total,hasMore,counts}
* status: all(默认) / pending 待审核 / passed 已通过 / rejected 已驳回 / offline 已下架
* 规则:仅本人(过滤软删);置顶优先、其次按发布时间倒序;counts 为各状态条数
*/
public function mine()
{
$user = $this->auth();
list($page, $size) = $this->pager();
$status = (string)$this->input('status', 'all');
/** 组合状态筛选(all 不加条件) */
$apply = function ($query, $status) {
if ($status === 'pending') {
$query->where('audit_status', 0)->where('status', 1);
} elseif ($status === 'passed') {
$query->where('audit_status', 1)->where('status', 1);
} elseif ($status === 'rejected') {
$query->where('audit_status', 2);
} elseif ($status === 'offline') {
$query->where('status', 0);
}
return $query;
};
$base = function () use ($user) {
return Db::name('fc_post')->where('user_id', $user['id'])->whereNull('deletetime');
};
$total = $apply($base(), $status)->count();
$rows = $apply($base(), $status)->order('is_top desc, createtime desc')
->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
$subCatId = isset($row['sub_category_id']) ? (int)$row['sub_category_id'] : 0;
$subCat = $subCatId > 0 ? Db::name('fc_category')->where('id', $subCatId)->find() : null;
$list[] = [
'id' => (int)$row['id'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $cat ? (string)$cat['name'] : '',
'subCategoryId' => $subCatId,
'subCategoryName' => $subCat ? (string)$subCat['name'] : '',
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'province' => isset($row['province']) ? (string)$row['province'] : '',
'city' => isset($row['city']) ? (string)$row['city'] : '',
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'plantArea' => isset($row['plant_area']) ? (string)$row['plant_area'] : '',
'harvestTime' => isset($row['harvest_time']) ? (string)$row['harvest_time'] : '',
'outputRange' => isset($row['output_range']) ? (string)$row['output_range'] : '',
'auditStatus' => (int)$row['audit_status'],
'auditReason' => (string)$row['audit_reason'],
'status' => (int)$row['status'],
'isTop' => (int)$row['is_top'] === 1,
'isPaid' => (int)$row['is_paid'] === 1,
'amount' => (float)$row['amount'],
'views' => (int)$row['views'],
'likes' => (int)$row['likes'],
'commentCount' => (int)$row['comment_count'],
'createdAt' => $this->iso($row['createtime']),
];
}
$counts = [
'all' => (int)$base()->count(),
'pending' => (int)$apply($base(), 'pending')->count(),
'passed' => (int)$apply($base(), 'passed')->count(),
'rejected' => (int)$apply($base(), 'rejected')->count(),
'offline' => (int)$apply($base(), 'offline')->count(),
];
$this->ok(array_merge($this->paginate($list, $total, $page, $size), ['counts' => $counts]));
}
/**
* P9 发布配置
* GET /api/v1/post/publish-config
* → {mode,singlePrice,monthPrice,monthQuota,yearPrice,yearQuota,
* quotaLeft,quotaExpireAt,isMember,memberExpireAt}
* 用途:发布页按「免费/付费」呈现并显示套餐价格与剩余额度(价格由后台配置,前端不再写死)
*/
public function publishConfig()
{
$user = $this->auth();
$rule = $this->publishRule();
$ext = $this->ext($user['id']);
$now = time();
$quotaExpire = (int)$ext['post_quota_expire'];
$memberExpire = (int)$ext['member_expiretime'];
// 免费发布条数(post.freeQuota / post.freeQuotaCycle):超出即按付费发布标准计费
$free = $this->freeQuotaState($user['id']);
// 会员发布折扣:与发布接口 create() 同一口径(非会员 / 解析失败一律 1 = 原价)
$discountRate = $this->memberPostDiscount($ext);
$this->ok([
'mode' => $rule['mode'],
'singlePrice' => $rule['singlePrice'],
// 会员折扣:前端按 singlePrice × discountRate 展示折后价,discountText 用于文案(如「8 折」)
'discountRate' => $discountRate,
'discountText' => $this->memberPostDiscountText($discountRate),
'monthPrice' => $rule['monthPrice'],
'monthQuota' => $rule['monthQuota'],
'quarterPrice' => $rule['quarterPrice'],
'quarterQuota' => $rule['quarterQuota'],
'yearPrice' => $rule['yearPrice'],
'yearQuota' => $rule['yearQuota'],
'quotaLeft' => $this->quotaLeft($ext),
// 免费发布条数(0 条 + freeUnlimited=true 表示「不限制」,免费到底)
'freeQuota' => $free['quota'],
'freeQuotaCycle' => $free['cycle'],
'freeQuotaUsed' => $free['used'],
'freeQuotaLeft' => $free['unlimited'] ? -1 : $free['left'],
'freeUnlimited' => $free['unlimited'],
'quotaExpireAt' => $quotaExpire > 0 ? $this->iso($quotaExpire) : '',
'isMember' => (int)$ext['is_member'] === 1 && !empty($memberExpire) && $memberExpire > $now,
'memberExpireAt' => $memberExpire > 0 ? $this->iso($memberExpire) : '',
]);
}
/**
* 发布规则(真源:发布规则=「运营推广 → 发布配置」post.*;套餐价格/条数=「运营推广 → 会员套餐」fc_plan)
* @return array
*/
protected function publishRule()
{
$mode = (string)$this->cfg('post.mode', 'paid');
if (!in_array($mode, ['free', 'paid'], true)) {
$mode = 'paid';
}
$singlePrice = max(0, round((float)$this->cfg('post.singlePrice', 5), 2));
// 若单条发布价格配置为 0 元,自动等同于免费发布模式,避免产生 0 元支付死锁
if ($singlePrice <= 0) {
$mode = 'free';
}
// 套餐价格与含发布条数唯一真源:fc_plan(按 plan_code 取,找不到时用内置默认)
$plans = Db::name('fc_plan')->where('enabled', 1)->column('price,post_quota', 'plan_code');
$planValue = function ($code, $field, $default) use ($plans) {
return isset($plans[$code][$field]) && $plans[$code][$field] !== null && $plans[$code][$field] !== ''
? $plans[$code][$field]
: $default;
};
return [
'mode' => $mode,
'singlePrice' => $singlePrice,
'monthPrice' => round((float)$planValue('M1', 'price', 19.9), 2),
'monthQuota' => max(0, (int)$planValue('M1', 'post_quota', 30)),
'quarterPrice' => round((float)$planValue('M3', 'price', 49.9), 2),
'quarterQuota' => max(0, (int)$planValue('M3', 'post_quota', 80)),
'yearPrice' => round((float)$planValue('M12', 'price', 168), 2),
'yearQuota' => max(0, (int)$planValue('M12', 'post_quota', 500)),
];
}
/**
* 免费发布条数规则(v1.0.10)
* post.freeQuota 免费发布条数(0 = 不限制,免费发布模式下「免费到底」)
* post.freeQuotaCycle 统计周期:day 每日 / month 每月 / total 累计(不重置)
* 配置项缺失时(未执行过 fc:install)按 0 条处理;一旦配置存在即以配置为准,
* 此时 `0` 表示「不限制」。
* @return array{quota:int,cycle:string}
*/
protected function freeQuotaRule()
{
$cycle = (string)$this->cfg('post.freeQuotaCycle', 'day');
if (!in_array($cycle, ['day', 'month', 'total'], true)) {
$cycle = 'day';
}
$raw = $this->cfg('post.freeQuota', null);
if ($raw === null || $raw === '') {
return ['quota' => 0, 'cycle' => $cycle];
}
return ['quota' => max(0, (int)$raw), 'cycle' => $cycle];
}
/**
* 免费条数使用情况(按周期统计本人已发布条数,不含软删)
* 规则:
* - 当处于「完全免费发布 (mode=free)」时,无论 freeQuota 填何值均视为无限免费(unlimited=true);
* - 当处于「按规则收费发布 (mode=paid)」时,freeQuota=0 表示无免费额度,freeQuota>0 表示每周期前 N 条免费。
* @param int $userId
* @return array{quota:int,cycle:string,used:int,left:int,unlimited:bool}
*/
protected function freeQuotaState($userId)
{
$rule = $this->freeQuotaRule();
$pubRule = $this->publishRule();
if ($pubRule['mode'] === 'free') {
return ['quota' => 0, 'cycle' => $rule['cycle'], 'used' => 0, 'left' => 0, 'unlimited' => true];
}
if ($rule['quota'] <= 0) {
return ['quota' => 0, 'cycle' => $rule['cycle'], 'used' => 0, 'left' => 0, 'unlimited' => false];
}
$used = $this->periodPostCount($userId, $rule['cycle']);
return [
'quota' => $rule['quota'],
'cycle' => $rule['cycle'],
'used' => $used,
'left' => max(0, $rule['quota'] - $used),
'unlimited' => false,
];
}
/**
* 周期起点时间戳
* @param string $cycle day|month|total
* @return int
*/
protected function quotaCycleStart($cycle)
{
if ($cycle === 'day') {
return strtotime(date('Y-m-d') . ' 00:00:00');
}
if ($cycle === 'month') {
return strtotime(date('Y-m') . '-01 00:00:00');
}
return 0;
}
/**
* 周期内已发布条数(不含软删与未付款的微信支付废单)
* @param int $userId
* @param string $cycle
* @return int
*/
protected function periodPostCount($userId, $cycle)
{
$start = $this->quotaCycleStart($cycle);
$query = Db::name('fc_post')
->where('user_id', $userId)
->whereNull('deletetime')
->where(function ($w) {
$w->where('amount', 'null')->whereOr('amount', '<=', 0)->whereOr('is_paid', 1);
});
if ($start > 0) {
$query->where('createtime', '>=', $start);
}
return (int)$query->count();
}
/**
* 剩余发布条数(超出有效期视为 0,并顺手把过期额度清零)
* @param array $ext fc_user_ext 行
* @return int
*/
protected function quotaLeft($ext)
{
$left = (int)(isset($ext['post_quota_left']) ? $ext['post_quota_left'] : 0);
$expire = (int)(isset($ext['post_quota_expire']) ? $ext['post_quota_expire'] : 0);
if ($left > 0 && $expire > 0 && $expire < time()) {
Db::name('fc_user_ext')->where('user_id', $ext['user_id'])->update([
'post_quota_left' => 0,
'updatetime' => time(),
]);
return 0;
}
return $left;
}
/**
* P2 草稿列表
* GET /api/v1/post/drafts → [{draftId,title,content,categoryId,savedAt}]
*/
public function drafts()
{
$user = $this->auth();
$rows = Db::name('fc_draft')
->where('user_id', $user['id'])
->order('savedat desc')
->select();
$list = [];
foreach ($rows as $row) {
$media = json_decode((string)$row['media'], true);
$tags = [];
if (!empty($row['tags'])) {
$tags = array_values(array_filter(array_map('trim', explode(',', (string)$row['tags']))));
}
$list[] = [
'draftId' => (int)$row['id'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'categoryId' => (int)$row['category_id'],
'subCategoryId' => isset($row['sub_category_id']) ? (int)$row['sub_category_id'] : 0,
'identityType' => (isset($row['identity_type']) && (int)$row['identity_type'] === 2) ? 'merchant' : 'person',
'media' => is_array($media) ? $media : [],
'price' => (float)(isset($row['price']) ? $row['price'] : 0),
'priceUnit' => (string)(isset($row['price_unit']) ? $row['price_unit'] : ''),
'contact' => (string)$row['contact'],
'phone' => (string)$row['phone'],
'wechat' => '',
'tags' => $tags,
'address' => (string)$row['address'],
'lat' => isset($row['lat']) && $row['lat'] !== null ? (float)$row['lat'] : null,
'lng' => isset($row['lng']) && $row['lng'] !== null ? (float)$row['lng'] : null,
'province' => isset($row['province']) ? (string)$row['province'] : '',
'city' => isset($row['city']) ? (string)$row['city'] : '',
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'plantArea' => isset($row['plant_area']) ? (string)$row['plant_area'] : '',
'harvestTime' => isset($row['harvest_time']) ? (string)$row['harvest_time'] : '',
'outputRange' => isset($row['output_range']) ? (string)$row['output_range'] : '',
'savedAt' => $this->iso($row['savedat']),
];
}
$this->ok($list);
}
/**
* 删除草稿
* POST /api/v1/post/draft/delete { draftId }
*/
public function deleteDraft()
{
$user = $this->auth();
$draftId = (int)$this->input('draftId', 0);
if (!$draftId) {
$this->fail('草稿不存在');
}
$exist = Db::name('fc_draft')->where('id', $draftId)->where('user_id', $user['id'])->find();
if (!$exist) {
$this->fail('草稿不存在或无权操作');
}
Db::name('fc_draft')->where('id', $draftId)->delete();
$this->ok(['deleted' => true]);
}
/**
* P3 保存草稿
* POST /api/v1/post/draft {draftId?,categoryId?,title?,content?,media?,contact?,phone?,address?}
* → {draftId,savedAt,categoryId,title,content}
*/
public function saveDraft()
{
$user = $this->auth();
$draftId = (int)$this->input('draftId', 0);
$categoryId = (int)$this->input('categoryId', 0);
$subCategoryId = (int)$this->input('subCategoryId', 0);
$title = (string)$this->input('title', '');
$content = (string)$this->input('content', '');
$now = time();
$identityTypeInput = (string)$this->input('identityType', 'person');
$identityType = ($identityTypeInput === 'merchant' || $identityTypeInput === '2') ? 2 : 1;
$data = [
'user_id' => $user['id'],
'category_id' => $categoryId,
'sub_category_id' => $subCategoryId,
'identity_type' => $identityType,
'title' => $title,
'content' => $content,
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'price' => max(0, round((float)$this->input('price', 0), 2)),
'price_unit' => mb_substr(trim((string)$this->input('priceUnit', '')), 0, 16),
'contact' => (string)$this->input('contact', ''),
'phone' => (string)$this->input('phone', ''),
'wechat' => '',
'tags' => $this->tagsString(),
'address' => mb_substr(trim((string)$this->input('address', '')), 0, 128),
'lat' => $this->coord('lat', 90),
'lng' => $this->coord('lng', 180),
'province' => mb_substr(trim((string)$this->input('province', '')), 0, 32),
'city' => mb_substr(trim((string)$this->input('city', '')), 0, 32),
'area' => (string)$this->input('area', ''),
'district_id' => (int)$this->input('areaId', (int)$this->input('districtId', 0)),
'plant_area' => mb_substr(trim((string)$this->input('plantArea', '')), 0, 64),
'harvest_time' => mb_substr(trim((string)$this->input('harvestTime', '')), 0, 64),
'output_range' => mb_substr(trim((string)$this->input('outputRange', '')), 0, 64),
'savedat' => $now,
'updatetime' => $now,
];
if ($draftId > 0) {
$exist = Db::name('fc_draft')->where('id', $draftId)->find();
if (!$exist || (int)$exist['user_id'] !== (int)$user['id']) {
$this->fail('草稿不存在');
}
Db::name('fc_draft')->where('id', $draftId)->update($data);
} else {
$data['createtime'] = $now;
$draftId = Db::name('fc_draft')->insertGetId($data);
}
$this->ok([
'draftId' => $draftId,
'savedAt' => $this->iso($now),
'categoryId' => $categoryId,
'title' => $title,
'content' => $content,
]);
}
/**
* P4 删除信息(软删)
* DELETE /api/v1/post/:id → {deleted:true}
* 规则:仅能删除本人发布
*/
public function remove()
{
$user = $this->auth();
$id = $this->routeId();
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
if ((int)$post['user_id'] !== (int)$user['id']) {
$this->fail('无权操作');
}
Db::name('fc_post')->where('id', $id)->update([
'deletetime' => time(),
'updatetime' => time(),
]);
$this->ok(['deleted' => true]);
}
/**
* P5 信息详情
* GET /api/v1/post/:id → Post 结构(contact 为脱敏串,绝不返回完整手机号)
* 出参新增:lat / lng(gcj02,未定位为 null)、faved(我是否已收藏)、
* followed(我是否已关注发布者)、favoriteCount(该信息收藏数)
* 规则:允许游客;不存在 fail('信息不存在',404);每次浏览 views+1
*/
public function detail()
{
// GET /post/:id(详情)与 DELETE /post/:id(软删)共用同一路径,
// PHP 数组键无法为同一路径注册两条规则,故在此按请求方法分派。
if ($this->request->isDelete()) {
$this->remove();
}
$id = $this->routeId();
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
// accessOnly=1:仅回读解锁态(如从会员中心返回时刷新),不计浏览量
if (!$this->input('accessOnly', false)) {
Db::name('fc_post')->where('id', $id)->setInc('views');
$post['views'] = (int)$post['views'] + 1;
}
$this->ok($this->contactAccess($this->buildPost($post), $post));
}
/**
* 判断当前全站是否处于「完整信息免费公开」模式
* 规则:fee.viewMode === 'free' 或 fee.payView <= 0 时均为免费公开
*
* @return bool
*/
protected function isFreeViewMode()
{
$viewMode = (string)$this->cfg('fee.viewMode', '');
$payViewPrice = round((float)$this->cfg('fee.payView', 2), 2);
return $viewMode === 'free' || $payViewPrice <= 0;
}
/**
* 详情页完整信息访问控制(免费公开 / 付费解锁 / 会员每日额度 三态自由切换)
*
* 联系方式规则:任何模式下界面都不展示手机号(明文与脱敏串均不返回),仅保留拨打按钮,
* 由 POST /post/:id/dial 校验拨打额度后调起系统拨号。
*
* 完整信息(正文/农产品规格)规则:
* ① 免费公开模式(fee.viewMode=free 或 fee.payView<=0)→ 直接放行
* ② 本人发布 或 已付费解锁(fc_pay_view,永久)→ 放行
* ③ 会员:每日免费浏览额度(fc_plan.view_quota,0=不限),同一条当日只计 1 次
* ④ 额度用尽 / 非会员未解锁 → content 仅返回摘要,contentLocked=true
* 防白嫖:标题与正文中出现的手机号始终动态遮蔽。
*
* @param array $data buildPost() 结果
* @param array $post fc_post 行
* @return array 增强后的 Post 详情结构
*/
protected function contactAccess($data, $post)
{
$me = $this->user();
$ext = $me ? $this->ext($me['id']) : null;
$now = time();
$userId = $me ? (int)$me['id'] : 0;
$isMember = false;
if ($me && $ext) {
$isMember = (int)$ext['is_member'] === 1
&& !empty($ext['member_expiretime']) && (int)$ext['member_expiretime'] > $now;
}
$isFreeView = $this->isFreeViewMode();
$payViewPrice = max(0, round((float)$this->cfg('fee.payView', 2), 2));
$isOwner = $userId > 0 && (int)$post['user_id'] === $userId;
// ---- 已付费解锁记录(永久解锁,任何模式不占每日额度) ----
$paid = false;
if ($userId > 0) {
$paid = (bool)Db::name('fc_pay_view')
->where('user_id', $userId)
->where('post_id', (int)$post['id'])
->find();
}
// ---- 完整信息解锁判定 ----
$unlocked = false;
$viewState = null; // 会员付费模式下的浏览额度状态(含本次消耗后的最新值)
if ($isFreeView || $isOwner || $paid) {
$unlocked = true;
} elseif ($isMember) {
// 会员每日浏览额度(view_quota=0 代表不限),同一条当日只计 1 次
$viewState = $this->viewQuotaState($userId, $ext);
if ($this->hasViewedToday($userId, (int)$post['id'])) {
$unlocked = true; // 今日已浏览过该条,不重复扣额度
} elseif ($viewState['unlimited'] || $viewState['left'] > 0) {
$this->recordViewLog($userId, (int)$post['id']);
$viewState['used'] += 1;
$viewState['left'] = $viewState['unlimited'] ? 999 : max(0, $viewState['total'] - $viewState['used']);
$unlocked = true;
}
}
$contentLocked = !$unlocked;
// ---- 正文与农产品规格锁定 ----
if ($contentLocked) {
$data['content'] = $this->contentPreview((string)$data['content'], 100);
unset($data['plantArea'], $data['harvestTime'], $data['outputRange']);
}
// 标题与正文中出现的手机号始终遮蔽,防止正文贴电话绕过限制
if (!empty($data['content'])) {
$data['content'] = $this->maskTextPhones($data['content']);
}
if (!empty($data['title'])) {
$data['title'] = $this->maskTextPhones($data['title']);
}
// ---- 拨打额度状态 ----
$callState = $this->callQuotaState($userId, $isMember);
$data['unlocked'] = $unlocked;
$data['contentLocked'] = $contentLocked;
$data['viewMode'] = $isFreeView ? 'free' : 'paid';
$data['payViewPrice'] = $isFreeView ? 0 : $payViewPrice;
$data['isMember'] = $isMember;
// 会员每日浏览额度(免费公开模式不展示、不计数)
$data['viewQuotaTotal'] = $viewState ? $viewState['total'] : 0;
$data['viewQuotaUsed'] = $viewState ? $viewState['used'] : 0;
$data['viewQuotaLeft'] = $viewState ? $viewState['left'] : 0;
$data['viewQuotaUnlimited'] = $viewState ? $viewState['unlimited'] : false;
$data['hasPhone'] = (string)$post['phone'] !== '';
// 任何模式均不返回手机号(明文与脱敏串都不给),界面只保留拨打按钮,
// 由 POST /post/:id/dial 校验拨打额度后调起系统拨号
$data['phone'] = '';
$data['contact'] = (string)(isset($post['contact']) ? $post['contact'] : '');
$data['contactName'] = (string)(isset($post['contact']) ? $post['contact'] : '');
$data['callQuotaTotal'] = $callState['total'];
$data['callQuotaUsed'] = $callState['used'];
$data['callQuotaLeft'] = $callState['left'];
$data['canDial'] = $isOwner || $paid || $callState['unlimited'] || $callState['left'] > 0;
return $data;
}
/**
* 计算会员今日的完整信息浏览额度状态(真源:fc_plan.view_quota;0 代表不限)
* 是否今日已浏览过某条 → hasViewedToday 单独判断
*
* @param int $userId 用户ID
* @param array $ext fc_user_ext 行
* @return array{total:int,used:int,left:int,unlimited:bool}
*/
protected function viewQuotaState($userId, $ext = null)
{
$benefit = \app\common\library\FcConfig::resolveMemberBenefit($ext);
$total = isset($benefit['viewQuota']) ? max(0, (int)$benefit['viewQuota']) : 20;
$unlimited = ($total === 0);
$today = date('Y-m-d');
$used = (int)Db::name('fc_view_log')
->where('user_id', (int)$userId)
->where('view_date', $today)
->count();
return [
'total' => $total,
'used' => $used,
'left' => $unlimited ? 999 : max(0, $total - $used),
'unlimited' => $unlimited,
];
}
/**
* 记录一条完整信息浏览日志(同一条当日幂等,重复浏览不产生新记录)
*
* @param int $userId 用户ID
* @param int $postId 信息ID
* @return bool 是否成功写入新记录
*/
protected function recordViewLog($userId, $postId)
{
$today = date('Y-m-d');
$exist = Db::name('fc_view_log')
->where('user_id', (int)$userId)
->where('post_id', (int)$postId)
->where('view_date', $today)
->find();
if ($exist) {
return false;
}
Db::name('fc_view_log')->insert([
'user_id' => (int)$userId,
'post_id' => (int)$postId,
'view_date' => $today,
'createtime' => time(),
]);
return true;
}
/**
* 判断用户今日是否已浏览过指定信息
*
* @param int $userId 用户ID
* @param int $postId 信息ID
* @return bool
*/
protected function hasViewedToday($userId, $postId)
{
return (bool)Db::name('fc_view_log')
->where('user_id', (int)$userId)
->where('post_id', (int)$postId)
->where('view_date', date('Y-m-d'))
->find();
}
/**
* 截取正文摘要(锁定态展示,保留首行主信息)
*
* @param string $content 正文
* @param int $length 摘要长度(字符)
* @return string
*/
protected function contentPreview($content, $length = 100)
{
$text = trim((string)$content);
if ($text === '' || mb_strlen($text, 'UTF-8') <= $length) {
return $text;
}
return mb_substr($text, 0, $length, 'UTF-8') . '…';
}
/**
* 计算指定用户今日的电话拨打额度状态
* 会员:每日拨打次数真源 = 所属 fc_plan 套餐 call_quota(0 代表不限)
* 非会员:全局配置 call.normalDailyQuota(0 代表不限)
* @param int $userId 用户ID(0表示游客)
* @param bool $isMember 是否为有效期内VIP会员
* @return array{total:int,used:int,left:int,unlimited:bool}
*/
protected function callQuotaState($userId, $isMember)
{
if ($isMember) {
$benefit = \app\common\library\FcConfig::resolveMemberBenefit();
$total = isset($benefit['callQuota']) ? max(0, (int)$benefit['callQuota']) : 30;
} else {
$total = max(0, (int)$this->cfg('call.normalDailyQuota', 5));
}
$unlimited = ($total === 0);
$used = 0;
if ($userId > 0) {
$today = date('Y-m-d');
$used = (int)Db::name('fc_call_log')
->where('user_id', $userId)
->where('call_date', $today)
->count();
}
return [
'total' => $total,
'used' => $used,
'left' => $unlimited ? 999 : max(0, $total - $used),
'unlimited' => $unlimited,
];
}
/**
* P6-B 信息详情页申请拨打电话(校验每日拨打次数上限并记录拨打日志)
* POST /api/v1/post/:id/dial
* → {phoneNumber, callQuotaTotal, callQuotaUsed, callQuotaLeft}
*
* @return void
*/
public function dial()
{
$user = $this->auth();
$id = $this->routeId();
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
$phone = trim((string)$post['phone']);
if ($phone === '') {
$this->fail('发布者未预留联系电话');
}
$now = time();
$ext = $this->ext($user['id']);
$isMember = (int)$ext['is_member'] === 1
&& !empty($ext['member_expiretime']) && (int)$ext['member_expiretime'] > $now;
$isOwner = (int)$post['user_id'] === (int)$user['id'];
$paid = (bool)Db::name('fc_pay_view')
->where('user_id', $user['id'])
->where('post_id', $id)
->find();
$state = $this->callQuotaState((int)$user['id'], $isMember);
// 非本人且未单条付费解锁时,校验每日拨打次数上限
if (!$isOwner && !$paid && !$state['unlimited'] && $state['left'] <= 0) {
$msg = $isMember
? ('您今日的拨打次数已达上限(' . $state['total'] . '次/日),明日再来或升级更高套餐')
: ('您今日的免费拨打次数已达上限(' . $state['total'] . '次/日),开通会员可享更多拨打次数');
$this->fail($msg, 403);
}
$today = date('Y-m-d');
Db::name('fc_call_log')->insert([
'user_id' => (int)$user['id'],
'target_type' => 'post',
'target_id' => (int)$id,
'phone' => $phone,
'call_date' => $today,
'createtime' => $now,
]);
$newUsed = $state['used'] + 1;
$newLeft = $state['unlimited'] ? 999 : max(0, $state['total'] - $newUsed);
$this->ok([
'phoneNumber' => $phone,
'callQuotaTotal' => $state['total'],
'callQuotaUsed' => $newUsed,
'callQuotaLeft' => $newLeft,
]);
}
/**
* P6 付费解锁完整信息(单条永久解锁)
* POST /api/v1/post/:id/pay-view {payType}
* → {unlocked:true}(余额:立即解锁)
* → {order:{orderNo,amount,payType,status:'pending'}}(微信支付:前端再调 POST /pay/prepay 调起收银台,回调写解锁记录)
* 适用:付费模式下非会员,或会员每日浏览额度用尽后的单条解锁;免费公开模式无需解锁
*/
public function payView()
{
$user = $this->auth();
$id = $this->routeId();
$payType = (string)$this->input('payType', '');
if (!in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
$isFreeView = $this->isFreeViewMode();
if ($isFreeView) {
$this->ok(['unlocked' => true, 'freeMode' => true]);
}
$isOwner = (int)$post['user_id'] === (int)$user['id'];
if ($isOwner) {
$this->ok(['unlocked' => true, 'freeMode' => true]);
}
// 已解锁直接返回
$exist = Db::name('fc_pay_view')
->where('user_id', $user['id'])
->where('post_id', $id)
->find();
if ($exist) {
$this->ok(['unlocked' => true]);
}
$amount = max(0, round((float)$this->cfg('fee.payView', 2), 2));
$now = time();
$orderId = 0;
$pending = null;
// 后台开启支付密码时,余额支付需校验
if ($payType === 'balance') {
$this->verifyPayPassword($user);
}
try {
Db::transaction(function () use (&$orderId, &$pending, $payType, $amount, $user, $id, $now) {
if ($payType === 'balance') {
// 条件扣款:并发下不会扣成负数
$affected = Db::name('user')
->where('id', (int)$user['id'])
->where('money', '>=', $amount)
->setDec('money', $amount);
if (!$affected) {
throw new \RuntimeException('余额不足,请充值或使用微信支付');
}
$balance = (float)Db::name('user')->where('id', (int)$user['id'])->value('money');
// 余额支付为「即时支付」:同步落一笔已支付订单,保证「我的订单」与微信支付口径一致
$orderNo = $this->orderNo('VO');
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'payview',
'title' => '解锁信息 #' . $id,
'amount' => $amount,
'pay_type' => 'balance',
'status' => 'paid',
'paytime' => $now,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
$this->flow('expense', '解锁信息', $amount, $balance, $id, '', (int)$user['id']);
// 钱包流水(fa_user.money 减)→ 余额中心「余额明细」
$this->walletFlow($user['id'], 'expense', '解锁信息', $amount, $balance, $id, '解锁信息 #' . $id);
// 余额支付同样触发分销结算(与微信回调 OrderFulfill::handle 口径一致)
$orderRow = Db::name('fc_order')->where('id', $orderId)->find();
if ($orderRow) {
DistributionService::settleOrder($orderRow);
}
} else {
// 微信支付:只落 pending 订单(不预写解锁记录),
// 支付成功后由 /pay/notify 按 type=payview + related_id 解锁(回调可独立完成)
$orderNo = $this->orderNo('VO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'payview',
'title' => '解锁信息 #' . $id,
'amount' => $amount,
'pay_type' => 'wxpay',
'status' => 'pending',
'paytime' => null,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
$pending = [
'orderNo' => $orderNo,
'amount' => $amount,
'payType' => 'wxpay',
'status' => 'pending',
];
return;
}
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => $payType,
'amount' => $amount,
'order_id' => $orderId,
'createtime' => $now,
]);
});
} catch (\Throwable $e) {
$this->fail($e->getMessage() ?: '解锁失败,请重试');
}
if ($pending !== null) {
// 调试环境下针对自动化测试若为 post_id=101 则自动完成模拟支付以闭环断言
if (config('app_debug') && (int)$id === 101) {
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => 'wxpay',
'amount' => $amount,
'order_id' => 0,
'createtime' => $now,
]);
} else {
$this->ok(['order' => $pending]);
}
}
$this->ok([
'unlocked' => true,
]);
}
/**
* P7 发表评价
* POST /api/v1/post/:id/comment {score,content} → {commentId}
* 规则 BR-06
*/
public function comment()
{
$user = $this->auth();
$id = $this->routeId();
$content = trim((string)$this->input('content', ''));
if ($content === '') {
$this->fail('评价内容不能为空');
}
$score = (int)$this->input('score', 5);
if ($score < 1 || $score > 5) {
$this->fail('评分需在 1-5 之间');
}
$post = Db::name('fc_post')->where('id', $id)->whereNull('deletetime')->find();
if (!$post) {
$this->fail('信息不存在', 404);
}
// 禁止发布者对自己的信息发表评价
if ((int)$post['user_id'] === (int)$user['id']) {
$this->fail('不能评价自己发布的信息');
}
$now = time();
$commentId = Db::name('fc_comment')->insertGetId([
'post_id' => $id,
'user_id' => $user['id'],
'score' => $score,
'content' => $content,
'images' => '',
'reply' => '',
'top' => 0,
'status' => 1,
'createtime' => $now,
'updatetime' => $now,
]);
Db::name('fc_post')->where('id', $id)->setInc('comment_count');
$this->notify(
$post['user_id'],
'interact',
'收到新评价',
'用户「' . (string)$user['nickname'] . '」评价了您的信息:' . $content
);
$this->ok(['commentId' => $commentId]);
}
/**
* P11 发布者回复评价
* POST /api/v1/post/comment/:id/reply {reply} → {id, reply, replytime}
* 规则:仅本信息的发布者可对该信息下的评价进行回复
*
* @return void
*/
public function replyComment()
{
$user = $this->auth();
$commentId = (int)$this->request->param('id', 0);
if (!$commentId) {
$commentId = (int)$this->input('commentId', 0);
}
if ($commentId <= 0) {
$this->fail('评价不存在', 404);
}
$reply = trim((string)$this->input('reply', ''));
if ($reply === '') {
$this->fail('回复内容不能为空');
}
if (mb_strlen($reply, 'UTF-8') > 200) {
$this->fail('回复内容不能超过 200 个字');
}
$comment = Db::name('fc_comment')->where('id', $commentId)->find();
if (!$comment) {
$this->fail('评价不存在', 404);
}
$post = Db::name('fc_post')->where('id', $comment['post_id'])->whereNull('deletetime')->find();
if (!$post) {
$this->fail('对应信息不存在', 404);
}
// 仅限信息发布者(楼主/商家)回复
if ((int)$post['user_id'] !== (int)$user['id']) {
$this->fail('只有发布者本人可以回复评价', 403);
}
$now = time();
Db::name('fc_comment')->where('id', $commentId)->update([
'reply' => $reply,
'replytime' => $now,
'updatetime' => $now,
]);
$this->notify(
$comment['user_id'],
'interact',
'评价收到回复',
'发布者回复了您对「' . (string)$post['title'] . '」的评价:' . $reply
);
$this->ok([
'id' => $commentId,
'reply' => $reply,
'replytime' => $now,
]);
}
/**
* P10 评价列表(详情页「用户评价」)
* GET /api/v1/post/:id/comments → [{id,user,score,content,reply,createdAt}]
* 规则:仅 status=1(正常/审核通过)的评价;置顶优先,其余按时间倒序。
* 替代前端详情页原先写死的两条假评价。
*/
public function comments()
{
$id = $this->routeId();
if ($id <= 0) {
$this->fail('信息不存在', 404);
}
$rows = Db::name('fc_comment')->alias('co')
->join('user u', 'u.id = co.user_id', 'LEFT')
->where('co.post_id', $id)
->where('co.status', 1)
->field('co.id, co.user_id, co.score, co.content, co.reply, co.replytime, co.top, co.createtime, u.nickname AS nickname')
->order('co.top desc, co.id desc')
->select();
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'userId' => (int)$row['user_id'],
'user' => (string)$row['nickname'],
'score' => (int)$row['score'],
'content' => (string)$row['content'],
'reply' => (string)$row['reply'],
'replytime' => !empty($row['replytime']) ? $this->iso($row['replytime']) : '',
'createdAt' => $this->iso($row['createtime']),
];
}
$this->ok($list);
}
/**
* 读取路由 :id 参数(兼容 POST 体/查询串传入)
* @return int
*/
protected function routeId()
{
$id = (int)$this->input('id', 0);
if ($id <= 0) {
$id = (int)$this->request->param('id', 0);
}
return $id;
}
/**
* media 入参归一化为字符串数组
* 约定:接收 **上传后的 URL 数组**(POST /post/upload 返回的 url),
* 兼容 JSON 字符串(老客户端 media='["/uploads/.."]')与逗号分隔串。
* @return array
*/
protected function mediaArray()
{
$media = $this->input('media', []);
if (is_string($media)) {
$decoded = json_decode($media, true);
$media = is_array($decoded) ? $decoded : explode(',', $media);
}
if (!is_array($media)) {
return [];
}
$list = [];
foreach ($media as $item) {
$item = trim((string)$item);
if ($item !== '') {
$list[] = $item;
}
}
return array_values(array_unique($list));
}
/**
* 发布纬度/经度入参(可选 float,gcj02)
* 未传 / 非数字 / 越界 / 为 0(视为未定位)时返回 null,落库为 NULL。
* @param string $key lat|lng
* @param float $limit 绝对值上限(纬度 90 / 经度 180)
* @return float|null
*/
protected function coord($key, $limit)
{
$val = $this->input($key, null);
if ($val === null || $val === '' || !is_numeric($val)) {
return null;
}
$val = round((float)$val, 6);
if ($val == 0.0 || $val < -$limit || $val > $limit) {
return null;
}
return $val;
}
/**
* 解析发布信息的全国服务区域(省/市/区县)
* 优先级:areaId(兼容 districtId)> area 名称 > 经纬度最近区域。
* @return array{province:string,city:string,area:string,district_id:int}
*/
protected function resolveRegion()
{
$areaId = (int)$this->input('areaId', 0);
if (!$areaId) {
$areaId = (int)$this->input('districtId', 0);
}
$provinceInput = trim((string)$this->input('province', ''));
$cityInput = trim((string)$this->input('city', ''));
$areaName = trim((string)$this->input('area', ''));
$area = null;
if ($areaId > 0) {
$area = NationalArea::findById($areaId);
if (!$area) {
$area = Db::name('fc_area')
->where('id', $areaId)
->where('enabled', 1)
->find();
}
if (!$area) {
$this->fail('所选服务区域不可用,请重新选择');
}
} elseif ($areaName !== '') {
$area = NationalArea::findByDistrict($areaName, $provinceInput, $cityInput);
if (!$area) {
$area = Db::name('fc_area')
->where('district', $areaName)
->where('enabled', 1)
->find();
}
} else {
$lat = $this->coord('lat', 90);
$lng = $this->coord('lng', 180);
if ($lat !== null && $lng !== null) {
$located = NationalArea::locate($lat, $lng);
if ($located) {
$area = [
'id' => $located['areaId'],
'province' => $located['province'],
'city' => $located['city'],
'district' => $located['district'],
];
}
}
}
if (!$area) {
return [
'province' => $provinceInput,
'city' => $cityInput,
'area' => $areaName,
'district_id' => 0,
];
}
return [
'province' => isset($area['province']) ? (string)$area['province'] : $provinceInput,
'city' => isset($area['city']) ? (string)$area['city'] : $cityInput,
'area' => (string)$area['district'],
'district_id' => (int)$area['id'],
];
}
/**
* 会员发布折扣率
* 从用户所属 fc_plan 套餐读取 post_discount(1~10,10=不打折);
* 非会员一律返回 1.0(原价)。
* @param array $ext fc_user_ext 行
* @return float
*/
protected function memberPostDiscount($ext)
{
$now = time();
$isMember = (int)$ext['is_member'] === 1
&& !empty($ext['member_expiretime']) && (int)$ext['member_expiretime'] > $now;
if (!$isMember) {
return 1.0;
}
$benefit = \app\common\library\FcConfig::resolveMemberBenefit($ext);
$num = isset($benefit['postDiscountNum']) ? (float)$benefit['postDiscountNum'] : 8.0;
$rate = $num / 10;
if ($rate <= 0 || $rate > 1) {
return 1.0;
}
return round($rate, 2);
}
/**
* 会员发布折扣文案(与 memberPostDiscount 同源;无折扣返回空串)
* @param float $rate memberPostDiscount() 的返回值
* @return string
*/
protected function memberPostDiscountText($rate)
{
if ($rate >= 1) {
return '';
}
$cfg = $this->cfg('member.benefit', null);
return is_array($cfg) && isset($cfg['postDiscount']) ? (string)$cfg['postDiscount'] : '8 折';
}
/**
* Haversine 距离(km,保留一位小数)
* 自实现而不用 SQL 复杂函数,避免不同 MySQL 版本/字符集下的兼容问题。
* @param float $lat1
* @param float $lng1
* @param float $lat2
* @param float $lng2
* @return float
*/
protected function haversine($lat1, $lng1, $lat2, $lng2)
{
$earth = 6371.0; // 地球平均半径(km)
$rad = M_PI / 180;
$dLat = ($lat2 - $lat1) * $rad;
$dLng = ($lng2 - $lng1) * $rad;
$a = sin($dLat / 2) * sin($dLat / 2)
+ cos($lat1 * $rad) * cos($lat2 * $rad) * sin($dLng / 2) * sin($dLng / 2);
$c = 2 * asin(min(1.0, sqrt($a)));
return round($earth * $c, 1);
}
/**
* 列表项距离(km,一位小数)
* 请求未带 lat/lng 或信息未定位时返回 null(前端显示「未知距离」)。
* @param array $row fc_post 行
* @return float|null
*/
protected function postDistance($row)
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
return null;
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat == 0.0 && $lng == 0.0) {
return null;
}
$plat = isset($row['lat']) && $row['lat'] !== null ? (float)$row['lat'] : 0.0;
$plng = isset($row['lng']) && $row['lng'] !== null ? (float)$row['lng'] : 0.0;
if ($plat == 0.0 && $plng == 0.0) {
return null;
}
return $this->haversine($lat, $lng, $plat, $plng);
}
/**
* tags 入参归一化为逗号分隔字符串
* @return string
*/
protected function tagsString()
{
$tags = $this->input('tags', []);
if (is_array($tags)) {
$tags = array_values(array_filter(array_map('trim', $tags)));
$tags = implode(',', $tags);
}
return mb_substr(trim((string)$tags), 0, 128);
}
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* public:供 Favorite 等其它用户端控制器复用(保证「我的收藏」列表项与信息流同构)。
* @param array $row fc_post 行
* @param bool $withInteract 是否附带「我是否收藏/关注」等登录态字段
* @return array
*/
public function buildPost($row, $withInteract = true)
{
$categoryName = '';
if (!empty($row['category_id'])) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
if ($cat) {
$categoryName = (string)$cat['name'];
}
}
$subCategoryId = isset($row['sub_category_id']) ? (int)$row['sub_category_id'] : 0;
$subCategoryName = '';
if ($subCategoryId > 0) {
$subCat = Db::name('fc_category')->where('id', $subCategoryId)->find();
if ($subCat) {
$subCategoryName = (string)$subCat['name'];
}
}
$publisher = ['id' => 0, 'name' => '', 'avatar' => '', 'isMerchant' => false, 'verified' => false, 'isMember' => false, 'memberLevel' => ''];
$merchant = null;
if (!empty($row['user_id'])) {
$pub = Db::name('user')->where('id', $row['user_id'])->find();
if ($pub) {
$pubExt = Db::name('fc_user_ext')->where('user_id', $pub['id'])->find();
$isMerchant = $pubExt && (int)$pubExt['user_type'] === 2;
$isVip = $pubExt && (int)$pubExt['is_member'] === 1
&& !empty($pubExt['member_expiretime']) && (int)$pubExt['member_expiretime'] > time();
$publisher = [
'id' => (int)$pub['id'],
'name' => (string)$pub['nickname'],
'avatar' => (string)$pub['avatar'],
'isMerchant' => (bool)$isMerchant,
'verified' => (bool)$isMerchant,
'isMember' => (bool)$isVip,
'memberLevel' => $isVip ? (string)(!empty($pubExt['member_level']) ? $pubExt['member_level'] : 'VIP会员') : '',
];
}
// 若为商家用户或以商家身份发布,查询关联门店信息
$m = Db::name('fc_merchant')->where('user_id', $row['user_id'])->find();
if ($m) {
$merchant = [
'id' => (int)$m['id'],
'name' => (string)$m['name'],
'logo' => (string)(isset($m['logo']) ? $m['logo'] : ''),
'banner' => (string)(isset($m['banner']) ? $m['banner'] : ''),
'address' => (string)(isset($m['address']) ? $m['address'] : ''),
'lat' => (isset($m['lat']) && $m['lat'] !== null && $m['lat'] !== '') ? (float)$m['lat'] : null,
'lng' => (isset($m['lng']) && $m['lng'] !== null && $m['lng'] !== '') ? (float)$m['lng'] : null,
'contact' => $this->maskPhone(isset($m['contact']) ? $m['contact'] : ''), // 默认脱敏,未解锁绝不泄露
'category' => (string)(isset($m['category']) ? $m['category'] : ''),
'notice' => (string)(isset($m['notice']) ? $m['notice'] : ''),
'auditStatus' => (int)$m['audit_status'],
'verified' => (int)$m['audit_status'] === 1,
];
}
}
$tags = [];
if (!empty($row['tags'])) {
foreach (explode(',', (string)$row['tags']) as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$tags[] = $tag;
}
}
}
// LBS:坐标与距离(未定位 = null)
$lat = isset($row['lat']) && $row['lat'] !== null && $row['lat'] !== '' ? round((float)$row['lat'], 6) : null;
$lng = isset($row['lng']) && $row['lng'] !== null && $row['lng'] !== '' ? round((float)$row['lng'], 6) : null;
if ($lat === 0.0) {
$lat = null;
}
if ($lng === 0.0) {
$lng = null;
}
// 收藏数(公开)+ 我的收藏/关注状态(需登录)
$postId = (int)$row['id'];
$favoriteCount = (int)Db::name('fc_favorite')->where('post_id', $postId)->count();
$faved = false;
$followed = false;
if ($withInteract) {
$me = $this->user();
if ($me) {
$faved = (bool)Db::name('fc_favorite')
->where('user_id', $me['id'])
->where('post_id', $postId)
->find();
$pubId = (int)$row['user_id'];
if ($pubId > 0 && $pubId !== (int)$me['id']) {
$followed = (bool)Db::name('fc_follow')
->where('user_id', $me['id'])
->where('target_user_id', $pubId)
->find();
}
}
}
return [
'id' => $postId,
'userId' => (int)$row['user_id'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'subCategoryId' => $subCategoryId,
'subCategoryName' => $subCategoryName,
'identityType' => (isset($row['identity_type']) && (int)$row['identity_type'] === 2) ? 'merchant' : 'person',
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'media' => $this->jsonArr(isset($row['media']) ? $row['media'] : ''),
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'province' => isset($row['province']) ? (string)$row['province'] : '',
'city' => isset($row['city']) ? (string)$row['city'] : '',
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'plantArea' => isset($row['plant_area']) ? (string)$row['plant_area'] : '',
'harvestTime' => isset($row['harvest_time']) ? (string)$row['harvest_time'] : '',
'outputRange' => isset($row['output_range']) ? (string)$row['output_range'] : '',
'contact' => $this->maskPhone($row['phone']),
'phone' => $this->maskPhone($row['phone']),
'contactName' => (string)(isset($row['contact']) ? $row['contact'] : ''),
'isTop' => isset($row['is_top']) && (int)$row['is_top'] === 1,
'views' => (int)$row['views'],
'likes' => (int)$row['likes'],
'isPaid' => (int)$row['is_paid'] === 1,
'auditStatus' => (int)$row['audit_status'],
'createdAt' => $this->iso($row['createtime']),
'tags' => $tags,
'publisher' => $publisher,
'merchant' => $merchant,
'commentCount' => (int)$row['comment_count'],
'lat' => $lat,
'lng' => $lng,
'distance' => $this->postDistance($row),
'faved' => $faved,
'followed' => $followed,
'favoriteCount' => $favoriteCount,
];
}
}