Files
code-bang/backend/application/common/service/MessageService.php
T

95 lines
3.1 KiB
PHP
Raw Normal View History

2026-09-17 16:25:31 +08:00
<?php
namespace app\common\service;
use app\common\model\Messages;
use app\common\traits\ServiceTrait;
use think\Log;
class MessageService
{
use ServiceTrait;
/** @var Messages */
public static $Model = Messages::class;
2026-10-08 16:28:21 +08:00
// 消息类型
const TYPE_SYSTEM = '0'; //系统消息:账户、审核、安全类
const TYPE_NOTICE = '1'; //公告消息:平台运营公告
const TYPE_DEMAND = '2'; //需求消息:需求/工单/合同/订单等业务流程
2026-09-17 16:25:31 +08:00
/**
* @param $to_user_id
* @param $title
* @param $content
* @param $extra_json
* @param $from_user_id
* @return mixed
* @throws \Exception
*/
2026-10-08 16:28:21 +08:00
public static function createData($to_user_id, $title, $content, $extra_json = [], $from_user_id = 0, $message_type = self::TYPE_SYSTEM)
2026-09-17 16:25:31 +08:00
{
$data = [
2026-10-08 16:28:21 +08:00
'message_type' => $message_type,
2026-09-17 16:25:31 +08:00
'from_user_id' => $from_user_id,
'to_user_id' => $to_user_id,
'title' => $title,
'content' => $content,
'extra_json' => $extra_json,
'is_read' => CommonService::STATUS_OFF,
];
$res = self::create($data);
if (!$res) {
Log::info(__METHOD__ . '-写入数据失败失败:' . json_encode($data, JSON_UNESCAPED_UNICODE));
exception('写入数据失败失败');
}
return $res;
}
2026-10-08 16:28:21 +08:00
/**
* 发送订阅消息时同步写入站内消息
* 数据来源:MSG_MAP 中模板的 name / message_type / valueNames / remark / page
* @param int $to_user_id 收件用户
* @param string $template_id 订阅消息模板ID
* @param array $msgData sendMsg 的原始参数 ['values'=>[], 'param'=>[], 'page'=>'']
* @param string $page 打包后的跳转页面(含query),如 pages/demand/list/index?opType=my&demandId=1
* @return mixed
*/
public static function createBySubscribe($to_user_id, $template_id, array $msgData = [], $page = '')
{
$template = SubscribeMessageService::MSG_MAP[$template_id] ?? [];
if (!$template) {
//未定义的模板不写站内消息
return false;
}
//按模板字段名组装可读内容:工单号:xxx;服务项目:xxx;...;备注:xxx
$values = $msgData['values'] ?? [];
$valueNames = $template['valueNames'] ?? [];
$lines = [];
foreach ($valueNames as $key => $name) {
if (isset($values[$key]) && $values[$key] !== '') {
$lines[] = $name . ':' . $values[$key];
}
}
if (!empty($template['remark'])) {
$lines[] = '备注:' . $template['remark'];
}
$content = implode("\n", $lines);
return self::createData(
$to_user_id,
$template['name'] ?? '系统通知',
$content,
[
'page' => $page ?: ($template['page'] ?? ''),
'template_id' => $template_id,
],
0, //系统发出
$template['message_type'] ?? self::TYPE_SYSTEM
);
}
2026-09-17 16:25:31 +08:00
}