文件
fenleixinxi/application/api/controller/Post.php
linda 043227dee7 feat(admin): 信息置顶 + 发布与费用配置(免费/付费开关、单条与月年卡价格含条数)
需求落地:
- 置顶:fc/post 新增 top 动作(批量置顶/取消置顶 + 站内消息通知),列表加「置顶/取消置顶」工具栏按钮、
  行内按钮与置顶状态徽章;置顶信息在用户端首页与「我的发布」中优先展示(Home::feed 按 is_top desc)
- 发布与费用配置(新增页面:同城业务 → 基础数据 → 发布与费用配置,fc/publish):
  发布模式(免费发布 / 付费发布)、会员单条发布价格、按月(价格 + 含条数)、按年(价格 + 含条数);
  真源为 fc_config 的 post.*,保存时同步 fc_plan 的月卡(M1)/年卡(M12) 价格与 post_quota
- FcInstall:新增 post.* 六项配置(默认免费发布,避免上线即撞付费墙);fc_user_ext 加 post_quota_left /
  post_quota_expire(套餐额度与有效期)、fc_plan 加 post_quota;新增 upgradePublish() 幂等升级老库并同步月/年卡
- tools/verify-api.mjs:新增 P9 发布配置 / P8 我的发布 契约校验,P1 发布改为「免费模式/额度内发布」并按付费模式容错
- 语言包与视图同步中文,均通过 php -l 与 node --check
2026-10-15 23:24:03 +08:00

729 行
27 KiB
PHP

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

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

<?php
namespace app\api\controller;
use think\Db;
/**
* 用户端 · 信息发布与详情(Module-POST)
* 路由:
* 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 发表评价
*
* 计费口径(后台「发布与费用配置」维护,真源=fc_config);
* 金额一律由服务端按配置计算,**不接受客户端传入金额**;
* 月卡/年卡(含发布条数)的购买复用 POST /member/open,本控制器只处理
* 「套餐额度内免费发布」与「单条付费发布」两种。
*/
class Post extends V1
{
/**
* P1 发布信息
* POST /api/v1/post/create
* 入参 {categoryId,title,content,media[],contact,phone,address,area,price,priceUnit,tags,paid,amount,payType}
* → {postId,auditStatus,order}
* 规则 BR-03/BR-04/BR-02
*/
public function create()
{
$user = $this->auth();
$categoryId = (int)$this->input('categoryId', 0);
$title = trim((string)$this->input('title', ''));
$content = trim((string)$this->input('content', ''));
if ($categoryId <= 0) {
$this->fail('分类不能为空');
}
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);
$amount = 0;
$payType = '';
$useQuota = false; // 套餐额度内免费
$useFreeQuota = false; // 每日免费额度内免费
if ($rule['mode'] === 'paid') {
if ($plan === 'free') {
if ($quotaLeft > 0) {
$useQuota = true; // 套餐额度内免费发布
} else {
// 每日免费额度(fee.freePostPerDay,0 = 不提供)内同样允许免费发布,
// 避免「付费发布」一开启就变成硬付费墙
$freePerDay = max(0, (int)$this->cfg('fee.freePostPerDay', 0));
$usedToday = $freePerDay > 0 ? $this->todayPostCount($user['id']) : 0;
if ($freePerDay > 0 && $usedToday < $freePerDay) {
$useFreeQuota = true;
} else {
$this->fail('请选择发布方式');
}
}
} else {
$amount = $rule['singlePrice'];
$payType = (string)$this->input('payType', '');
if ($amount > 0 && !in_array($payType, ['wxpay', 'balance'], true)) {
$this->fail('支付方式不支持');
}
// 余额校验须在落库之前:否则余额不足时会残留一条 is_paid=1 的无效发布
if ($amount > 0 && $payType === 'balance' && (float)$user['money'] < $amount) {
$this->fail('余额不足');
}
}
}
$paid = $amount > 0;
$now = time();
$postId = Db::name('fc_post')->insertGetId([
'user_id' => $user['id'],
'category_id' => $categoryId,
'title' => $title,
'content' => $content,
'cover' => '',
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'price' => round((float)$this->input('price', 0), 2),
'price_unit' => (string)$this->input('priceUnit', ''),
'area' => (string)$this->input('area', ''),
'address' => (string)$this->input('address', ''),
'contact' => (string)$this->input('contact', ''),
'phone' => $phone,
'wechat' => '',
'tags' => $this->tagsString(),
'is_paid' => $paid ? 1 : 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,
]);
$order = null;
if ($paid) {
// 余额支付为「即时支付」:下单即扣款、订单直接置为已支付;
// 微信支付需要前端调起收银台,保持 pending 由支付回调置为 paid。
$paidNow = $payType === 'balance';
$orderNo = $this->orderNo('PO');
Db::name('fc_order')->insert([
'order_no' => $orderNo,
'user_id' => $user['id'],
'type' => 'post',
'title' => $title,
'amount' => $amount,
'pay_type' => $payType,
'status' => $paidNow ? 'paid' : 'pending',
'paytime' => $paidNow ? $now : null,
'related_id' => $postId,
'createtime' => $now,
'updatetime' => $now,
]);
if ($paidNow) {
$balance = round((float)$user['money'] - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
$this->flow('income', '发布付费', $amount, $balance, $postId);
}
$order = [
'orderNo' => $orderNo,
'amount' => $amount,
'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,
]);
}
$this->ok([
'postId' => $postId,
'auditStatus' => 0,
'order' => $order,
'plan' => $rule['mode'] === 'free' ? 'free' : ($useQuota ? 'quota' : ($useFreeQuota ? 'free' : 'single')),
'amount' => $amount,
'quotaLeft' => $rule['mode'] === 'paid' ? $quotaLeft : 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();
$list[] = [
'id' => (int)$row['id'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $cat ? (string)$cat['name'] : '',
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'address' => (string)$row['address'],
'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'];
// 每日免费额度(付费模式下仍保留的免费次数)
$freePerDay = max(0, (int)$this->cfg('fee.freePostPerDay', 0));
$usedToday = $freePerDay > 0 ? $this->todayPostCount($user['id']) : 0;
$this->ok([
'mode' => $rule['mode'],
'singlePrice' => $rule['singlePrice'],
'monthPrice' => $rule['monthPrice'],
'monthQuota' => $rule['monthQuota'],
'yearPrice' => $rule['yearPrice'],
'yearQuota' => $rule['yearQuota'],
'quotaLeft' => $this->quotaLeft($ext),
'freePerDay' => $freePerDay,
'freeUsedToday' => $usedToday,
'freeLeftToday' => max(0, $freePerDay - $usedToday),
'quotaExpireAt' => $quotaExpire > 0 ? $this->iso($quotaExpire) : '',
'isMember' => (int)$ext['is_member'] === 1 && ($memberExpire === 0 || $memberExpire > $now),
'memberExpireAt' => $memberExpire > 0 ? $this->iso($memberExpire) : '',
]);
}
/**
* 发布规则(后台「发布与费用配置」维护;配置缺失时回落旧 fee.* 再回落内置默认)
* @return array
*/
protected function publishRule()
{
$mode = (string)$this->cfg('post.mode', 'paid');
if (!in_array($mode, ['free', 'paid'], true)) {
$mode = 'paid';
}
return [
'mode' => $mode,
'singlePrice' => round((float)$this->cfg('post.singlePrice', $this->cfg('fee.singlePost', 5)), 2),
'monthPrice' => round((float)$this->cfg('post.monthPrice', $this->cfg('fee.memberMonth', 19.9)), 2),
'monthQuota' => max(0, (int)$this->cfg('post.monthQuota', 30)),
'yearPrice' => round((float)$this->cfg('post.yearPrice', $this->cfg('fee.memberYear', 168)), 2),
'yearQuota' => max(0, (int)$this->cfg('post.yearQuota', 500)),
];
}
/**
* 今日已发布条数(每日免费额度判定用,不含软删)
* @param int $userId
* @return int
*/
protected function todayPostCount($userId)
{
$start = strtotime(date('Y-m-d') . ' 00:00:00');
return (int)Db::name('fc_post')->where('user_id', $userId)
->where('createtime', '>=', $start)->whereNull('deletetime')->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) {
$list[] = [
'draftId' => (int)$row['id'],
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'categoryId' => (int)$row['category_id'],
'savedAt' => $this->iso($row['savedat']),
];
}
$this->ok($list);
}
/**
* 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);
$title = (string)$this->input('title', '');
$content = (string)$this->input('content', '');
$now = time();
$data = [
'user_id' => $user['id'],
'category_id' => $categoryId,
'title' => $title,
'content' => $content,
'media' => json_encode($this->mediaArray(), JSON_UNESCAPED_UNICODE),
'contact' => (string)$this->input('contact', ''),
'phone' => (string)$this->input('phone', ''),
'address' => (string)$this->input('address', ''),
'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 为脱敏串,绝不返回完整手机号)
* 规则:允许游客;不存在 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);
}
Db::name('fc_post')->where('id', $id)->setInc('views');
$post['views'] = (int)$post['views'] + 1;
$this->ok($this->buildPost($post));
}
/**
* P6 付费查看联系方式
* POST /api/v1/post/:id/pay-view {payType}
* → {unlocked:true,contact:{phone,wechat}}
* 规则 BR-05;金额取 fee.payView;会员或已解锁免费
*/
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);
}
$contact = [
'phone' => (string)$post['phone'],
'wechat' => $post['wechat'] !== '' ? (string)$post['wechat'] : ('tongcheng_' . $id),
];
// 已解锁直接返回
$exist = Db::name('fc_pay_view')
->where('user_id', $user['id'])
->where('post_id', $id)
->find();
if ($exist) {
$this->ok(['unlocked' => true, 'contact' => $contact]);
}
$amount = round((float)$this->cfg('fee.payView', 2), 2);
$now = time();
$ext = $this->ext($user['id']);
$isMember = (int)$ext['is_member'] === 1
&& (!$ext['member_expiretime'] || $ext['member_expiretime'] > $now);
$orderId = 0;
if ($isMember) {
// 会员免费解锁
$amount = 0;
$payType = 'free';
} elseif ($payType === 'balance') {
$balance = (float)$user['money'];
if ($balance < $amount) {
$this->fail('余额不足');
}
$balance = round($balance - $amount, 2);
Db::name('user')->where('id', $user['id'])->update([
'money' => $balance,
'updatetime' => $now,
]);
$this->flow('expense', '付费查看', $amount, $balance, $id);
} else {
// 微信支付:创建已支付订单
$orderId = Db::name('fc_order')->insertGetId([
'order_no' => $this->orderNo('VO'),
'user_id' => $user['id'],
'type' => 'post',
'title' => '付费查看 #' . $id,
'amount' => $amount,
'pay_type' => $payType,
'status' => 'paid',
'paytime' => $now,
'related_id' => $id,
'createtime' => $now,
'updatetime' => $now,
]);
}
Db::name('fc_pay_view')->insert([
'user_id' => $user['id'],
'post_id' => $id,
'pay_type' => $payType,
'amount' => $amount,
'order_id' => $orderId,
'createtime' => $now,
]);
$this->ok(['unlocked' => true, 'contact' => $contact]);
}
/**
* 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);
}
$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]);
}
/**
* 读取路由 :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 入参归一化为数组
* @return array
*/
protected function mediaArray()
{
$media = $this->input('media', []);
if (is_string($media)) {
$decoded = json_decode($media, true);
$media = is_array($decoded) ? $decoded : [];
}
return is_array($media) ? array_values($media) : [];
}
/**
* tags 入参归一化为逗号分隔字符串
* @return string
*/
protected function tagsString()
{
$tags = $this->input('tags', []);
if (is_array($tags)) {
$tags = implode(',', $tags);
}
return (string)$tags;
}
/**
* 组装 Post 结构(与前端 mock 数据字段严格对齐)
* @param array $row fc_post 行
* @return array
*/
protected function buildPost($row)
{
$categoryName = '';
if (!empty($row['category_id'])) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
if ($cat) {
$categoryName = (string)$cat['name'];
}
}
$publisher = ['id' => 0, 'name' => '', 'avatar' => '', 'isMerchant' => false, 'verified' => false];
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;
$publisher = [
'id' => (int)$pub['id'],
'name' => (string)$pub['nickname'],
'avatar' => (string)$pub['avatar'],
'isMerchant' => (bool)$isMerchant,
'verified' => (bool)$isMerchant,
];
}
}
$tags = [];
if (!empty($row['tags'])) {
foreach (explode(',', (string)$row['tags']) as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$tags[] = $tag;
}
}
}
return [
'id' => (int)$row['id'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'area' => (string)$row['area'],
'address' => (string)$row['address'],
'contact' => $this->maskPhone($row['phone']),
'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,
'commentCount' => (int)$row['comment_count'],
'distance' => (int)$row['distance'],
];
}
}