Browse Source

feat: 增加消息处理

igb 4 months ago
parent
commit
be34b55ab4

+ 154 - 0
app/Admin/Controllers/DistMessageController.php

@@ -0,0 +1,154 @@
+<?php
+
+namespace App\Admin\Controllers;
+
+use App\Admin\Repositories\DistMessage;
+use Dcat\Admin\Form;
+use Dcat\Admin\Grid;
+use Dcat\Admin\Show;
+use Dcat\Admin\Http\Controllers\AdminController;
+use Dcat\Admin\Layout\Content;
+use Dcat\Admin\Admin;
+
+use App\Distributor\Repositories\DistAdminDistributor;
+
+class DistMessageController extends AdminController
+{
+    /**
+     * page index
+     */
+    public function index(Content $content)
+    {
+        return $content
+            ->header('列表')
+            ->description('全部')
+            ->breadcrumb(['text'=>'列表','url'=>''])
+            ->body($this->grid());
+    }
+
+    /**
+     * Make a grid builder.
+     *
+     * @return Grid
+     */
+    protected function grid()
+    {
+        return Grid::make(new DistMessage(), function (Grid $grid) {
+            $grid->column('id')->sortable();
+            $grid->column('title', 'message Title');
+            $grid->column('content');
+            $grid->column('sender_id');
+            $grid->column('target_type');
+            //$grid->column('target_ids');
+            $grid->column('created_at');
+            $grid->column('updated_at')->sortable();
+
+            $grid->filter(function (Grid\Filter $filter) {
+                $filter->equal('id');
+
+            });
+        });
+    }
+
+    /**
+     * Make a show builder.
+     *
+     * @param mixed $id
+     *
+     * @return Show
+     */
+    protected function detail($id)
+    {
+        return Show::make($id, new DistMessage(), function (Show $show) use ($id) {
+            $show->field('id');
+            $show->field('title');
+            $show->field('content');
+            $show->field('sender_id');
+            $show->field('target_type');
+            //$show->field('target_ids');
+//            $show->field('target_ids');
+            // 获取 target_ids 并显示对应的 company_name
+            $message = DistMessage::find($id);
+            $targetIds = json_decode($message->target_ids, true);
+
+            if ($targetIds) {
+                $companyNames = DistAdminDistributor::getCompanyNamesByIds($targetIds);
+                $show->field('target_ids')->as(function () use ($companyNames) {
+                    return implode(', ', $companyNames);
+                });
+            } else {
+               // $show->field('target_ids', 'Target IDs')->as('No specified users');
+            }
+            $show->field('created_at');
+            $show->field('updated_at');
+        });
+    }
+
+    /**
+     * Make a form builder.
+     *
+     * @return Form
+     */
+    protected function form()
+    {
+        //插入JS
+        Admin::script(
+            <<<JS
+    $(document).ready(function() {
+                var targetType = $('select[name="target_type"]');
+                var targetIds = $('div.form-group.row.form-field:has(select[name="target_ids[]"])');
+
+                // 初始化时根据 target_type 的值显示或隐藏 target_ids
+                toggleTargetIds(targetType.val());
+
+                // 监听 target_type 的变化
+                targetType.change(function() {
+                    toggleTargetIds($(this).val());
+                });
+
+                function toggleTargetIds(value) {
+                   // alert(value);
+                    if (value === 'users') {
+                        targetIds.show();
+                    } else {
+                        targetIds.hide();
+                    }
+                }
+            });
+
+JS
+        );
+
+        return Form::make(new DistMessage(), function (Form $form) {
+            $form->display('id')->rules('required');;
+            $form->text('title')->rules('required');;
+            $form->textarea('content')->rules('required');;
+//            $form->text('sender_id')->rules('required');
+
+// 检查当前操作是创建还是编辑
+            if ($form->isEditing()) {
+                // 如果是编辑操作,设置 target_type 为只读
+                $form->select('target_type')->options([
+                    'all' => 'all Users',
+                    'users' => 'specified Users',
+                ])->rules('required')->readonly();
+            } else {
+                // 如果是创建操作,正常显示 target_type
+                $form->select('target_type')->options([
+                    'all' => 'all Users',
+                    'users' => 'specified Users',
+                ])->rules('required');
+            }
+
+            $form->multipleSelect('target_ids')
+               ->options(DistAdminDistributor::tags_all())
+                ->saving(function ($value) {
+                    // 转化成json字符串保存到数据库
+                    return json_encode($value);
+                });
+
+            $form->display('created_at');
+            $form->display('updated_at');
+        });
+    }
+}

+ 21 - 0
app/Admin/Repositories/DistMessage.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Admin\Repositories;
+
+use App\Models\DistMessage as Model;
+use Dcat\Admin\Repositories\EloquentRepository;
+
+class DistMessage extends EloquentRepository
+{
+    /**
+     * Model.
+     *
+     * @var string
+     */
+    protected $eloquentClass = Model::class;
+
+    public static function find($id)
+    {
+        return Model::find($id);
+    }
+}

+ 2 - 0
app/Admin/routes.php

@@ -40,6 +40,8 @@ Route::group([
     //模板变量
     $router->resource('dist-template-var', 'DistAppearanceVariableController');
 
+    $router->resource('messages', 'DistMessageController');
+
     // 定义切换语言的路由
     $router->get('language-switch','LanguageController@index');
 

+ 152 - 0
app/Distributor/Controllers/DistMessageController.php

@@ -0,0 +1,152 @@
+<?php
+
+namespace App\Distributor\Controllers;
+
+use App\Distributor\Repositories\DistCustomMessage;
+use App\Distributor\Repositories\DistMessage;
+use App\Distributor\Repositories\DistReadStatus;
+use Dcat\Admin\Admin;
+use Dcat\Admin\Form;
+use Dcat\Admin\Grid;
+use Dcat\Admin\Http\Controllers\AdminController;
+use Dcat\Admin\Layout\Content;
+use Dcat\Admin\Show;
+
+class DistMessageController extends AdminController
+{
+    /**
+     * page index
+     */
+    public function index(Content $content)
+    {
+        return $content
+            ->header('列表')
+            ->description('全部')
+            ->breadcrumb(['text'=>'列表','url'=>''])
+            ->body($this->grid());
+    }
+
+    /**
+     * Make a grid builder.
+     *
+     * @return Grid
+     */
+    protected function grid()
+    {
+
+        //插入JS
+        Admin::script(
+            <<<JS
+   $(document).ready(function() {
+                    $('.grid-row-clickable').on('click', function() {
+                        var id = $(this).data('id');
+                        if (id) {
+                            window.location.href = '/dist/messages/' + id;
+                        }
+                    });
+                });
+JS
+        );
+
+        return Grid::make(new DistCustomMessage(), function (Grid $grid)  {
+
+            $grid->setActionClass(Grid\Displayers\Actions::class);
+            // 添加“查看”按钮
+            $grid->actions(function (Grid\Displayers\Actions $actions) {
+                $actions->append('<a href="/dist/messages/'.  $actions->row->id.'" class="btn btn-sm btn-primary">View Detail</a>');
+            });
+            // 设置数据源
+            //$grid->model()->setData($messagesArray);
+
+            //$grid->column('id');//->sortable();
+            $grid->column('created_at','time');
+//            $grid->column('title','message_title');
+
+            $grid->column('title','message_title')->display(function ($title) {
+                $isRead = $this->is_read;
+                $style = $isRead == 0 ? 'font-weight: bold;' : '';
+                $label = $isRead == 0 ? '(未读)' : '';
+                return "<span style='{$style}'>{$title} {$label}</span>";
+            });
+            $grid->column('content');
+            //$grid->column('sender_id');
+            $grid->column('is_read');
+
+            $grid->disableCreateButton();
+            $grid->disableDeleteButton();
+            $grid->disableEditButton();
+            // 添加查看按钮
+
+            // 添加点击事件,点击一行进入详情页
+
+
+//            $grid->filter(function (Grid\Filter $filter) {
+//                $filter->equal('id');
+//            });
+        });
+    }
+
+    /**
+     * Make a show builder.
+     *
+     * @param mixed $id
+     *
+     * @return Show
+     */
+    protected function detail($id)
+    {
+        $this->markAsRead($id);
+        return Show::make($id, new DistMessage(), function (Show $show) {
+            //$show->field('id');
+
+            //$show->field('sender_id');
+            $show->field('created_at');
+            $show->field('title');
+            $show->field('content');
+            // Disable all toolbar actions and buttons
+            $show->panel()
+                ->tools(function (Show\Tools $tools) {
+                    $tools->disableEdit();   // Disable edit button
+                    $tools->disableDelete(); // Disable delete button
+                });
+        });
+    }
+//
+//    /**
+//     * Make a form builder.
+//     *
+//     * @return Form
+//     */
+//    protected function form()
+//    {
+//        return Form::make(new DistMessage(), function (Form $form) {
+//            $form->display('id');
+//            $form->text('title');
+//            $form->text('content');
+//            $form->text('sender_id');
+//            $form->text('target_type');
+//            $form->text('target_ids');
+//
+//            $form->display('created_at');
+//            $form->display('updated_at');
+//        });
+//    }
+
+
+    /**
+     * 标记消息为已读
+     */
+    public function markAsRead($messageId)
+    {
+        $userId = getDistributorId();
+
+
+        if (DistReadStatus::markAsRead($messageId, $userId)) {
+            return true;
+        }
+
+        return false;
+    }
+
+
+}

+ 1 - 0
app/Distributor/Controllers/HomeController.php

@@ -5,6 +5,7 @@ namespace App\Distributor\Controllers;
 use App\Distributor\Metrics\Examples;
 use App\Http\Controllers\Controller;
 use App\Distributor\Controllers\Dashboard;
+use Dcat\Admin\Admin;
 use Dcat\Admin\Layout\Column;
 use Dcat\Admin\Layout\Content;
 use Dcat\Admin\Layout\Row;

+ 22 - 0
app/Distributor/Repositories/DistAdminDistributor.php

@@ -111,5 +111,27 @@ class DistAdminDistributor extends EloquentRepository
     }
 
 
+    public static function all()
+    {
+
+        $result =  Model::all();
+        return $result;
+    }
+    public static function tags_all()
+    {
+        $result = Model::all();
+
+        // 遍历结果并返回数组
+        $tags = [];
+        foreach ($result as $item) {
+            $tags[$item->id] = $item->company_name; // 假设 company_name 是你想要显示的字段
+        }
+
+        return $tags;
+    }
 
+    public static function getCompanyNamesByIds(array $ids)
+    {
+        return Model::whereIn('id', $ids)->pluck('company_name')->toArray();
+    }
 }

+ 101 - 0
app/Distributor/Repositories/DistCustomMessage.php

@@ -0,0 +1,101 @@
+<?php
+
+namespace App\Distributor\Repositories;
+
+use App\Models\DistMessage as DistMessageModel;
+use Dcat\Admin\Grid;
+use Dcat\Admin\Repositories\Repository;
+use Illuminate\Pagination\LengthAwarePaginator;
+
+class DistCustomMessage extends Repository
+{
+    protected $eloquentClass = DistMessageModel::class;
+
+    /**
+     * 定义主键字段名称
+     *
+     * @return string
+     */
+    public function getPrimaryKeyColumn()
+    {
+        return 'id';
+    }
+
+
+    /**
+     * 重写 get 方法
+     *
+     * @param Grid\Model $model
+     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection|array
+     */
+    public function get(Grid\Model $model)
+    {
+        // 当前页数
+        $currentPage = $model->getCurrentPage();
+        // 每页显示行数
+        $perPage = $model->getPerPage();
+
+        // 获取排序字段
+        [$orderColumn, $orderType] = $model->getSort();
+
+        // 获取当前登录用户的 ID
+        $userId = getDistributorId();
+
+        // 使用 getMessagesForUser 方法获取消息列表
+        $messages = $this->getMessagesForUser($userId);
+
+        // 获取总记录数
+        $total = $messages->count();
+
+        // 分页数据
+        $data = $messages->slice(($currentPage - 1) * $perPage, $perPage)->values();
+
+
+        foreach ($data as $value) {
+
+
+            $value['created_at']=$value['created_at']->toDateTimeString();
+
+            $data_out[]=$value;
+        }
+
+
+        return $model->makePaginator(
+            $total, // 传入总记录数
+            $data_out
+        );
+    }
+
+
+
+    public function getMessagesForUser($userId)
+    {
+        return DistMessageModel::where('target_type', 'all')
+            ->orWhere(function ($query) use ($userId) {
+                $query->where('target_type', 'users')
+                    ->whereJsonContains('target_ids', $userId);
+            })
+            ->with(['readStatuses' => function ($query) use ($userId) {
+                $query->where('user_id', $userId);
+            }])
+            ->orderBy('created_at', 'desc')
+            ->get()
+            ->map(function ($message) use ($userId) {
+                $isRead = $message->readStatuses->isNotEmpty() && $message->readStatuses->first()->is_read;
+                if(!$isRead)
+                {
+                    $isRead=0;
+                }
+                return [
+                    'id' => $message->id,
+                    'title' => $message->title,
+                    'content' => $message->content,
+                    'sender_id' => $message->sender_id,
+                    'created_at' => $message->created_at,
+                    'is_read' => $isRead,
+                ];
+            });
+    }
+
+
+}

+ 21 - 0
app/Distributor/Repositories/DistMessage.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Distributor\Repositories;
+
+use App\Models\DistMessage as Model;
+use Dcat\Admin\Repositories\EloquentRepository;
+
+class DistMessage extends EloquentRepository
+{
+    /**
+     * Model.
+     *
+     * @var string
+     */
+    protected $eloquentClass = Model::class;
+
+    public static function find($id)
+    {
+        return Model::find($id);
+    }
+}

+ 43 - 0
app/Distributor/Repositories/DistReadStatus.php

@@ -0,0 +1,43 @@
+<?php
+namespace App\Distributor\Repositories;
+
+use App\Models\DistReadStatus as Model;
+use Dcat\Admin\Repositories\EloquentRepository;
+
+class DistReadStatus extends EloquentRepository
+{
+    /**
+     * Model.
+     *
+     * @var string
+     */
+    protected $eloquentClass = Model::class;
+
+    /**
+     * 标记消息为已读
+     *
+     * @param int $messageId 消息ID
+     * @param int $userId 用户ID
+     * @return bool
+     */
+    public static function markAsRead($messageId, $userId)
+    {
+        $readStatus = Model::where('message_id', $messageId)
+            ->where('user_id', $userId)
+            ->first();
+
+        if (!$readStatus) {
+            // 如果记录不存在,创建新记录并标记为已读
+            $readStatus = Model::create([
+                'message_id' => $messageId,
+                'user_id' => $userId,
+                'is_read' => true,
+            ]);
+
+            return $readStatus->save();
+        }
+
+// 如果记录已存在,不做任何操作
+        return false;
+    }
+}

+ 3 - 0
app/Distributor/routes.php

@@ -65,6 +65,9 @@ Route::group([
     $router->get('language-switch','LanguageController@index');
     // 不需要登录的路由
     $router->get('captcha','CaptchaController@generate');
+
+    $router->resource('messages', 'DistMessageController');
+    //配置
 });
 
 /*

+ 1 - 0
app/Models/DistAdminDistributor.php

@@ -55,4 +55,5 @@ class DistAdminDistributor extends Model
         }
         return $domain;
     }
+
 }

+ 50 - 0
app/Models/DistMessage.php

@@ -0,0 +1,50 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class DistMessage extends Model
+{
+    use HasFactory;
+
+    protected $table = 'dist_messages';
+    protected $fillable = ['title', 'content', 'sender_id', 'target_type', 'target_ids', 'created_at', 'updated_at'];
+
+    protected $casts = [
+        'target_ids' => 'json',
+        'created_at' => 'datetime:Y-m-d H:i:s',
+        'updated_at' => 'datetime:Y-m-d H:i:s',
+    ];
+
+
+
+    // 消息的发送者
+    public function sender()
+    {
+        return $this->belongsTo(DistAdminDistributor::class, 'sender_id');
+    }
+
+    // 消息的阅读状态
+    public function readStatuses()
+    {
+        return $this->hasMany(DistReadStatus::class, 'message_id');
+    }
+
+    // 检查消息是否针对某用户
+    public function isForUser($userId)
+    {
+        if ($this->target_type === 'all') {
+            return true;
+        }
+
+        if ($this->target_type === 'users' && is_array($this->target_ids)) {
+            return in_array($userId, $this->target_ids);
+        }
+
+        return false;
+    }
+
+
+}

+ 26 - 0
app/Models/DistReadStatus.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class DistReadStatus extends Model
+{
+    use HasFactory;
+
+    protected $table = 'dist_read_status';
+    protected $fillable = ['user_id', 'message_id', 'is_read', 'created_at', 'updated_at'];
+
+    // 阅读状态属于一个用户
+    public function user()
+    {
+        return $this->belongsTo(DistAdminDistributor::class, 'user_id');
+    }
+
+    // 阅读状态属于一条消息
+    public function message()
+    {
+        return $this->belongsTo(DistMessage::class, 'message_id');
+    }
+}

+ 2 - 2
config/admin.php

@@ -22,7 +22,7 @@ return [
     | `img` tag, eg '<img src="http://logo-url" alt="Admin logo">'.
     |
     */
-    'logo' => ' Prime&nbsp; Admin',
+    'logo' => '<img src="/static/images/logo.svg" alt="Admin logo" style="height:auto;width:300px">',
 
     /*
     |--------------------------------------------------------------------------
@@ -211,7 +211,7 @@ return [
     |--------------------------------------------------------------------------
     */
     'helpers' => [
-        'enable' => false,
+        'enable' => true,
     ],
 
     /*

+ 2 - 0
lang/en/global.php

@@ -90,6 +90,8 @@ return [
         'position'              => 'Position',
         'banner_url'            => 'Banner Url',
         'template_file'         => 'Template File',
+        'target_type'           => 'Type',
+        'target_ids'            => 'Target Ids',
     ],
     'labels' => [
         'list'                  => 'List',

+ 2 - 1
lang/zh_CN/global.php

@@ -93,6 +93,8 @@ return [
         'subtitle'              => '副标题',
         'country_alpha_2'       => '国家简称',
         'country_lang'          => '国家语言',
+        'target_type'           => '类型',
+        'target_ids'            => '接收用户',
     ],
     'labels' => [
         'list'         => '列表',
@@ -167,7 +169,6 @@ return [
         'attribute'       => '属性',
         'landing_page' => '独立页',
         'video_help'   => '帮助',
-        'distributor_code' => '分销商编码',
     ],
     'options' => [
         //

+ 1 - 1
resources/views/admin/pages/login.blade.php

@@ -137,7 +137,7 @@
                     <div class="form-group d-flex justify-content-between align-items-center">
                         <div class="text-left">
                             <a class="lang-item" href="javascript:void(0);" data-lang="en">English</a>
-                            <a class="lang-item" href="javascript:void(0);" data-lang="zh_CN">中文</a>
+                           / <a class="lang-item" href="javascript:void(0);" data-lang="zh_CN">中文</a>
                         </div>
                     </div>