dcodegroup/activity-log

dcode使用的简单包,用于管理活动日志

安装: 10,357

依赖项: 0

建议者: 0

安全: 0

星级: 4

关注者: 6

分支: 0

开放问题: 0

语言:JavaScript


README

dcodegroup/activity-log 包提供了一种简单统一的方法来跟踪和记录针对您的 Laravel 模型(及其关系)的活动/交互。通过捕获更改、更新和用户交互,以集中和一致的方式提高应用程序的可视性和审计。

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

更新说明

版本 1.1.1 开始,我们不再需要使用观察者来监听模型的更改。 ActivityLoggable 中的 bootActivityLoggable 解决了这个问题。在更新之前,请确保删除重复的观察者。

安装

将以下内容添加到您的 package.json 文件中

"dependencies": {
   ...
    "floating-vue": "^2.0.0-beta.1",
    "vue-markdown-render": "^2.1.1",
    "vue-mention": "^2.0.0-alpha.3"
}

PHP

您可以通过 composer 安装此包

composer require dcodegroup/activity-log

然后运行安装命令。

php artisan activity-log:install

运行迁移

php artisan migrate

用户模型

将以下合约添加到 User 模型。

<?php
namespace App\Models;

use Dcodegroup\ActivityLog\Contracts\HasActivityUser;

class User extends Authenticatable implements HasActivityUser
{

    public function getActivityLogUserName(): string
    {
        return $this->name;
    }
    
    public function getActivityLogEmail(): string
    {
        return $this->email;
    }
    
    public function getActivityLogUser(): array
    {
        return [
            'id' => $this->id,
            'full_name' => $this->getActivityLogUserName(),
            'email' => $this->getActivityLogEmail(),
        ];
    }
   

JS

将以下别名添加到 vite.config.js

resolve: {
  alias: {
    "@dcodegroup": path.resolve(__dirname, "./vendor/dcodegroup/"),

将以下 js 添加到您的 index.js 文件中。

import VActivityLog from "@dcodegroup/activity-log/resources/js/components/VActivityLog.vue";
import ActivityLogList from "@dcodegroup/activity-log/resources/js/components/ActivityLogList.vue";
import ActivityEmail from "@dcodegroup/activity-log/resources/js/components/ActivityEmail.vue";

app.component("VActivityLog", VActivityLog);
app.component("ActivityLogList", ActivityLogList);
app.component("ActivityEmail", ActivityEmail);

在您的 app.scss 文件中添加以下内容

@import "@dcodegroup/activity-log/resources/sass/index.scss";
@import "floating-vue/dist/style.css";

似乎需要在 tailwind.config.js 中的 spacing 下添加此内容

spacing: {
  "3xlSpace": "96px",
  "2xlSpace": "64px",
  xlSpace: "32px",
  lgSpace: "24px",
  mdSpace: "16px",
  smSpace: "12px",
  xsSpace: "8px",
  "2xsSpace": "4px",
  "3xsSpace": "2px",
}

更新内容下的模块导出

content: [
  ...
    "./vendor/dcodegroup/**/*.{blade.php,vue,js,ts}",
  ...
],

更新 vue il8n 包以加载额外的路径

i18n({
  // you can also change your langPath here
  // langPath: 'locales'
  additionalLangPaths: [
    "vendor/dcodegroup/activity-log/lang", // Load translations from this path too!
  ],
}),

运行 npm 构建(开发/生产)

npm run prod:assets

配置

大多数配置都已设置为合理的默认值。但是,您可以在 config/activity-log.php 中查看配置文件并根据需要调整。

<?php

use Dcodegroup\ActivityLog\Models\ActivityLog;

return [

    /*
    |--------------------------------------------------------------------------
    | Middleware
    |--------------------------------------------------------------------------
    |
    | What middleware should the package apply.
    |
    */

    'middleware' => ['web', 'auth'],

    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
    |
    | Here you can configure the route paths and route name variables.
    |
    | What should the route path for the activity log be
    | eg 'api/generic/activity-logs'
    |
    | What should the route name for the activity log be
    | eg eg 'api.generic.activity-logs',
    */

    'route_path' => env('LARAVEL_ACTIVITY_LOG_ROUTE_PATH', 'activity-logs'),
    'route_name' => env('LARAVEL_ACTIVITY_LOG_ROUTE_NAME', 'activity-logs'),

    /*
    |--------------------------------------------------------------------------
    | Model and Binding
    |--------------------------------------------------------------------------
    |
    | binding - eg 'activity-logs'
    | model - eg 'ActivityLog'
    |
   */

    'binding' => env('LARAVEL_ACTIVITY_LOG_MODEL_BINDING', 'activity-logs'),
    'activity_log_model' => ActivityLog::class,

    /*
     |--------------------------------------------------------------------------
     | Formatting
     |--------------------------------------------------------------------------
     |
     | Configuration here is for display configuration
     |
    */

    'datetime_format' => env('LARAVEL_ACTIVITY_LOG_DATETIME_FORMAT', 'd-m-Y H:ia'),
    'date_format' => env('LARAVEL_ACTIVITY_LOG_DATE_FORMAT', 'd.m.Y'),

    /*
     |--------------------------------------------------------------------------
     | Pagination
     |--------------------------------------------------------------------------
     |
     | Configuration here is for pagination
     |
    */

    'default_filter_pagination' => env('LARAVEL_ACTIVITY_LOG_PAGINATION', 50),

    /*
     |--------------------------------------------------------------------------
     | User
     |--------------------------------------------------------------------------
     |
     | Configuration here is for the user model and table
     | eg 'User'
    */

    'user_relationship' => env('LARAVEL_ACTIVITY_LOG_USER_RELATIONSHIP', 'user'),
    'user_model' => \App\Models\User::class,
    'user_table' => env('LARAVEL_ACTIVITY_LOG_USERS_TABLE', 'users'),

    /*
     |--------------------------------------------------------------------------
     | Communication log
     |--------------------------------------------------------------------------
     |
     |
    */

    'communication_log_model' => \Dcodegroup\ActivityLog\Models\CommunicationLog::class,
    'communication_log_table' => env('LARAVEL_ACTIVITY_LOG_COMMUNICATION_LOG_TABLE', 'communication_logs'),
    'communication_log_relationship' => env('LARAVEL_ACTIVITY_LOG_COMMUNICATION_LOG_RELATIONSHIP', 'communicationLog'),

    /*
     |--------------------------------------------------------------------------
     | Filter Builder
     |--------------------------------------------------------------------------
     |
     | Configuration here is for the filter builder
     | eg 'FilterBuilder class: App\Support\QueryBuilder\Filters\FilterBuilder'
    */

    'filter_builder_path' => env('LARAVEL_ACTIVITY_LOG_FILTER_BUILDER_PATH', ''),

    /*
     |--------------------------------------------------------------------------
     | Events
     |--------------------------------------------------------------------------
     |
     | Configuration here is for the events
     | eg 'open_modal_event' => 'openModal'
    */

    'open_modal_event' => env('LARAVEL_ACTIVITY_LOG_EVENT_OPEN_MODEL', 'openModal'),
    'reload_event' => env('LARAVEL_ACTIVITY_LOG_EVENT_RELOAD', 'getActivities'),
];

用法

该包提供了一些端点,您可以使用它们。通过运行查看完整的列表

php artisan route:list --name=activity-log

它们是

[example.com/activity-logs],这是您将形成索引的地方。这是默认受保护的身份验证中间件,但您可以在配置中修改。这是您想要在管理面板和可能的新窗口中链接的地方

QueryBuilder 过滤器

位于

src\Support\QueryBuilder\Filters\DateRangeFilter.php
src\Support\QueryBuilder\Filters\TermFilter.php

活动日志模型特质

位于

src\Support\Traits\ActivityLoggable.php
src\Support\Traits\LastModifiedBy.php

ActivityLoggable 特质

ActivityLoggable 特质提供与模型相关的活动日志和通信日志的功能。

方法

  • logCreate(): void:每当创建新的模型时,自动创建活动日志。 (从版本 1.1.1 支持)
  • logUpdate(): void:每当模型更新时,自动创建活动日志。 (从版本 1.1.1 支持)
  • logDelete(): void:每当模型被删除时,自动创建活动日志。 (从版本 1.1.1 支持)
  • getActivityLogEmails(): array:获取与活动日志关联的电子邮件。
  • activities(): Collection:获取与模型关联的活动集合。
  • modelRelation(): Collection:获取模型列与相关表的关联。 modelRelation 还具有限制记录到定义的列的效果,而不是在声明 getModelChangesJson(true) 时记录模型的所有更改

通过使用 ActivityLoggable 在模型中定义模型关系的示例

 public function modelRelation(): Collection
    {
        return collect([
            'account_id' => collect([               // column change in model
                'label' => 'Account',               // attribute label display in activity log description
                'modelClass' => Account::class,     // relationship model
                'modelKey' => 'name',               // columns display instead 
            ]),
          ......
          ])

当这样声明时,而不是活动日志显示如下。 account_id: 1 -> 20 结果将返回如下: Account: Alison Cahill -> Annie Pollock

  • getModelChanges(?array $modelChangesJson = null): string:以格式化的字符串形式获取模型更改。
  • getModelChangesJson(bool $allowCustomAttribute = false): array:以 JSON 数组的形式获取模型更改。如果 $allowCustomAttribute = true,则如果我们要限制存储在模型关系中定义的字段;false:如果我们要存储所有模型更改
  • createActivityLog(array $description): ActivityLog:创建一个新的活动日志。

使用ActivityLoggable通过模型定义活动日志的示例

// Creating an activity log
$activityLog = $model->createActivityLog([
'type' => \Dcodegroup\ActivityLog\Models\ActivityLog::TYPE_DATA // if type is null default type will be TYPE_DATA, we support 3 other types: TYPE_STATUS, TYPE_COMMENT, TYPE_NOTIFICATION 
'title' => 'Updated profile information',
'description' => 'Updated user profile information',
// Additional custom fields as needed
'communication_log_id' => '' // required when type = TYPE_NOTIFICATION to link activity log with communication log
]);

如果您有一个用户案例,其中想要将日志消息记录到另一个模型,例如。您有一个Order模型,并且想要将OrderItem模型记录到Order中。然后按照以下步骤操作。

OrderItem模型中添加方法targetModel

class OrderItem extends Model
{
    ...
    public function targetModel(): self|Model
    {
        return $this->order;
    }
    
}

通常,一个模型将具有字段nametitlelabel。此包可以在大多数情况下处理此操作。但是,如果您使用非标准字段来命名模型,则可以使用以下方法自定义模型的标签。如果没有找到标签,则会抛出ModelLabelNotDefinedException异常。

public function getActivityLogModelLabel(): string
{
    /**
      * This can be any field or method to return the label but the return must be a string 
      */
    return $this->reference;
}

您可以通过将以下方法添加到模型中为任何模型提供自定义标签。如果未设置,则将使用Str::headline对模型进行操作。

public function getActivityLogModelLabel(): string
{
    /**
      * This can be any field or method to return the label but the return must be a string 
      */
    return __('order.title');
}

该包将自动尝试找到模型的关键。通常,这将是一个名为nametitlelabel的字段。但是,这不一定总是如此,并且键可能根据模型的状态而更改。例如,类型报价可能为quote_number,订单可能使用sales_order_number。如果找不到默认值之一,则将抛出ModelKeyNotDefinedException异常。

这应该只在您的本地环境中发生。如果发生这种情况,请在该模型中实现以下方法。

public function getActivityLogModelKey(): string
{
    return (string) $this->custom_field_name;
}

默认情况下,此包将记录除created_atupdated_atdeleted_atpasswordid之外的所有字段。如果您希望排除模型上的其他字段,例如第三方API令牌,则可以在该模型中实现以下方法。

public function getActivityLogModelExcludeFields(): array
{
    return ['xero_api_token', 'stripe_api_token'];
}
You can use a custom formatter for fields in your model by using the `activityLogFieldFormatters` method.

example. Add the following to the model

```php
use Illuminate\Support\Collection;

...
    public function activityLogFieldFormatters(): Collection
    {
        return collect([
            'price' => fn ($value) => Number::currency(($value / 100), 'AUD'),
        ]);
    }

price是该字段的键。右侧应该是一个闭包,可以用于格式化将呈现的值。

您可以覆盖实体的默认名称/标签。只需创建一个返回字符串的方法即可。以下为默认值。

 public function activityLogEntityName(): string
  {
     return Arr::join(Str::ucsplit(class_basename($this)), ' ').' (id:'.$this->id.')';
  }

*createCommunicationLog(array $data, string $to, string $content, string $type = CommunicationLog::TYPE_EMAIL): CommunicationLog **:创建一个新的通信日志。

使用ActivityLoggable通过模型定义通信日志的示例

// Creating a communication log
$communicationLog = $model->createCommunicationLog([
'type' => 
'cc' => ['cc@example.com'],
'bcc' => ['bcc@example.com'],
'subject' => 'Subject of the email',
], 'to@example.com', 'Content of the email');

用于支持跟踪已读电子邮件的活动日志可邮寄特质

位于

src\Support\Traits\ReadMailableTrait.php

使用<activity-log-list><v-activity-log>来显示活动日志列表。如果需要过滤器功能,请通过插槽传递过滤器

<ActivityLogList :model-id="tender.id" :model-class="tenderModel">
    <v-filter entity="activity-logs" class="flex flex-row-reverse space-x-2 space-x-reverse"></v-filter>
</ActivityLogList>

用法

为了记录任何内容,请将以下特质添加到您想要记录的模型上。

...
use Dcodegroup\ActivityLog\Support\Traits\ActivityLoggable;

class Order extends Model
{
    use ActivityLoggable;
    ...
}

此外,我们可以在模型中添加任何我们想要的位置活动日志

    $model->createActivityLog([
            'type' => \Dcodegroup\ActivityLog\Models\ActivityLog::TYPE_COMMENT // if type is null default type will be TYPE_DATA, we support 3 other types: TYPE_STATUS, TYPE_COMMENT, TYPE_NOTIFICATION
            'title' => 'left a comment.',
            'description' => 'left a comment',
        ]);

变更日志

请参阅CHANGELOG以获取有关最近更改的更多信息。

贡献

我们相信协作的力量!如果您与我们一起致力于推动商业软件的边界,请随时贡献、报告问题或提出改进建议。您的见解使我们变得更好。

安全

如果您发现了与此包相关的任何问题,包括任何安全相关的问题;请通过security@dcodegroup.com发送电子邮件,以确保我们可以以保密的方式优先处理这些问题。

致谢

此项目由Dcode Group及其团队(包括过去和现在的团队成员)支持和资助。特别感谢

关于Dcode Group

码道集团专注于利用Laravel框架定制软件开发解决方案。我们的重点在于开发支持独特业务运营的商业、金融和流程驱动系统。利用此类包,我们简化了跨项目中的常见特性/功能,确保快速集成广泛的功能,同时提升整体代码库的维护和管理。了解更多关于

许可