feat: rename , executionMethod/type to trigger, crontab to triggerCron

This commit is contained in:
Fu Diwei 2025-01-04 13:29:03 +08:00
parent 2213399f5e
commit da76d1065e
11 changed files with 206 additions and 85 deletions

View File

@ -15,19 +15,19 @@ const (
)
const (
WorkflowTypeAuto = "auto"
WorkflowTypeManual = "manual"
WorkflowTriggerAuto = "auto"
WorkflowTriggerManual = "manual"
)
type Workflow struct {
Meta
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Crontab string `json:"crontab"`
Trigger string `json:"trigger"`
TriggerCron string `json:"triggerCron"`
Enabled bool `json:"enabled"`
Content *WorkflowNode `json:"content"`
Draft *WorkflowNode `json:"draft"`
Enabled bool `json:"enabled"`
HasDraft bool `json:"hasDraft"`
}

View File

@ -20,8 +20,8 @@ func NewWorkflowRepository() *WorkflowRepository {
func (w *WorkflowRepository) ListEnabledAuto(ctx context.Context) ([]domain.Workflow, error) {
records, err := app.GetApp().Dao().FindRecordsByFilter(
"workflow",
"enabled={:enabled} && type={:type}",
"-created", 1000, 0, dbx.Params{"enabled": true, "type": domain.WorkflowTypeAuto},
"enabled={:enabled} && trigger={:trigger}",
"-created", 1000, 0, dbx.Params{"enabled": true, "trigger": domain.WorkflowTriggerAuto},
)
if err != nil {
return nil, err
@ -83,13 +83,12 @@ func record2Workflow(record *models.Record) (*domain.Workflow, error) {
},
Name: record.GetString("name"),
Description: record.GetString("description"),
Type: record.GetString("type"),
Crontab: record.GetString("crontab"),
Trigger: record.GetString("trigger"),
TriggerCron: record.GetString("triggerCron"),
Enabled: record.GetBool("enabled"),
HasDraft: record.GetBool("hasDraft"),
Content: content,
Draft: draft,
HasDraft: record.GetBool("hasDraft"),
}
return workflow, nil

View File

@ -46,16 +46,16 @@ func update(ctx context.Context, record *models.Record) error {
id := record.Id
enabled := record.GetBool("enabled")
executeMethod := record.GetString("type")
trigger := record.GetString("trigger")
scheduler := app.GetScheduler()
if !enabled || executeMethod == domain.WorkflowTypeManual {
if !enabled || trigger == domain.WorkflowTriggerManual {
scheduler.Remove(id)
scheduler.Start()
return nil
}
err := scheduler.Add(id, record.GetString("crontab"), func() {
err := scheduler.Add(id, record.GetString("triggerCron"), func() {
NewWorkflowService(repository.NewWorkflowRepository()).Run(ctx, &domain.WorkflowRunReq{
Id: id,
})

View File

@ -33,7 +33,7 @@ func (s *WorkflowService) InitSchedule(ctx context.Context) error {
}
scheduler := app.GetScheduler()
for _, workflow := range workflows {
err := scheduler.Add(workflow.Id, workflow.Crontab, func() {
err := scheduler.Add(workflow.Id, workflow.TriggerCron, func() {
s.Run(ctx, &domain.WorkflowRunReq{
Id: workflow.Id,
})

View File

@ -0,0 +1,116 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("tovyif5ax6j62ur")
if err != nil {
return err
}
// update
edit_trigger := &schema.SchemaField{}
if err := json.Unmarshal([]byte(`{
"system": false,
"id": "vqoajwjq",
"name": "trigger",
"type": "select",
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSelect": 1,
"values": [
"auto",
"manual"
]
}
}`), edit_trigger); err != nil {
return err
}
collection.Schema.AddField(edit_trigger)
// update
edit_triggerCron := &schema.SchemaField{}
if err := json.Unmarshal([]byte(`{
"system": false,
"id": "8ho247wh",
"name": "triggerCron",
"type": "text",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), edit_triggerCron); err != nil {
return err
}
collection.Schema.AddField(edit_triggerCron)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("tovyif5ax6j62ur")
if err != nil {
return err
}
// update
edit_trigger := &schema.SchemaField{}
if err := json.Unmarshal([]byte(`{
"system": false,
"id": "vqoajwjq",
"name": "type",
"type": "select",
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSelect": 1,
"values": [
"auto",
"manual"
]
}
}`), edit_trigger); err != nil {
return err
}
collection.Schema.AddField(edit_trigger)
// update
edit_triggerCron := &schema.SchemaField{}
if err := json.Unmarshal([]byte(`{
"system": false,
"id": "8ho247wh",
"name": "crontab",
"type": "text",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), edit_triggerCron); err != nil {
return err
}
collection.Schema.AddField(edit_triggerCron)
return dao.SaveCollection(collection)
})
}

View File

@ -6,7 +6,7 @@ import { produce } from "immer";
import Show from "@/components/Show";
import { deployProvidersMap } from "@/domain/provider";
import { notifyChannelsMap } from "@/domain/settings";
import { type WorkflowNode, WorkflowNodeType } from "@/domain/workflow";
import { WORKFLOW_TRIGGERS, type WorkflowNode, WorkflowNodeType } from "@/domain/workflow";
import { useZustandShallowSelector } from "@/hooks";
import { useWorkflowStore } from "@/stores/workflow";
@ -35,21 +35,21 @@ const WorkflowElement = ({ node, disabled }: NodeProps) => {
return (
<div className="flex items-center justify-between space-x-2">
<Typography.Text className="truncate">
{node.config?.executionMethod === "auto"
{node.config?.trigger === WORKFLOW_TRIGGERS.AUTO
? t("workflow.props.trigger.auto")
: node.config?.executionMethod === "manual"
: node.config?.trigger === WORKFLOW_TRIGGERS.MANUAL
? t("workflow.props.trigger.manual")
: ""}
: " "}
</Typography.Text>
<Typography.Text className="truncate" type="secondary">
{node.config?.executionMethod === "auto" ? (node.config?.crontab as string) : ""}
{node.config?.trigger === WORKFLOW_TRIGGERS.AUTO ? (node.config?.triggerCron as string) : ""}
</Typography.Text>
</div>
);
}
case WorkflowNodeType.Apply: {
return <Typography.Text className="truncate">{node.config?.domain as string}</Typography.Text>;
return <Typography.Text className="truncate">{(node.config?.domain as string) || " "}</Typography.Text>;
}
case WorkflowNodeType.Deploy: {
@ -57,7 +57,7 @@ const WorkflowElement = ({ node, disabled }: NodeProps) => {
return (
<Space>
<Avatar src={provider?.icon} size="small" />
<Typography.Text className="truncate">{t(provider?.name ?? "")}</Typography.Text>
<Typography.Text className="truncate">{t(provider?.name ?? " ")}</Typography.Text>
</Space>
);
}
@ -66,7 +66,7 @@ const WorkflowElement = ({ node, disabled }: NodeProps) => {
const channel = notifyChannelsMap.get(node.config?.channel as string);
return (
<div className="flex items-center justify-between space-x-2">
<Typography.Text className="truncate">{t(channel?.name ?? "")}</Typography.Text>
<Typography.Text className="truncate">{t(channel?.name ?? " ")}</Typography.Text>
<Typography.Text className="truncate" type="secondary">
{(node.config?.subject as string) ?? ""}
</Typography.Text>

View File

@ -32,7 +32,7 @@ const AddNode = ({ node, disabled }: AddNodeProps) => {
].map(([type, label, icon]) => {
return {
key: type as string,
disabled: true,
disabled: disabled,
label: t(label as string),
icon: icon,
onClick: () => {

View File

@ -7,7 +7,7 @@ import { produce } from "immer";
import { z } from "zod";
import Show from "@/components/Show";
import { type WorkflowNode, type WorkflowStartNodeConfig } from "@/domain/workflow";
import { WORKFLOW_TRIGGERS, type WorkflowNode, type WorkflowStartNodeConfig } from "@/domain/workflow";
import { useAntdForm, useZustandShallowSelector } from "@/hooks";
import { useWorkflowStore } from "@/stores/workflow";
import { getNextCronExecutions, validCronExpression } from "@/utils/cron";
@ -19,8 +19,8 @@ export type StartNodeFormProps = {
const initFormModel = (): WorkflowStartNodeConfig => {
return {
executionMethod: "auto",
crontab: "0 0 * * *",
trigger: WORKFLOW_TRIGGERS.AUTO,
triggerCron: "0 0 * * *",
};
};
@ -32,19 +32,19 @@ const StartNodeForm = ({ node }: StartNodeFormProps) => {
const formSchema = z
.object({
executionMethod: z.string({ message: t("workflow_node.start.form.trigger.placeholder") }).min(1, t("workflow_node.start.form.trigger.placeholder")),
crontab: z.string().nullish(),
trigger: z.string({ message: t("workflow_node.start.form.trigger.placeholder") }).min(1, t("workflow_node.start.form.trigger.placeholder")),
triggerCron: z.string().nullish(),
})
.superRefine((data, ctx) => {
if (data.executionMethod !== "auto") {
if (data.trigger !== WORKFLOW_TRIGGERS.AUTO) {
return;
}
if (!validCronExpression(data.crontab!)) {
if (!validCronExpression(data.triggerCron!)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: t("workflow_node.start.form.trigger_cron.errmsg.invalid"),
path: ["crontab"],
path: ["triggerCron"],
});
}
});
@ -67,51 +67,45 @@ const StartNodeForm = ({ node }: StartNodeFormProps) => {
},
});
const [triggerType, setTriggerType] = useState(node?.config?.executionMethod);
const [triggerCronLastExecutions, setTriggerCronExecutions] = useState<Date[]>([]);
const fieldTrigger = Form.useWatch<string>("trigger", formInst);
const fieldTriggerCron = Form.useWatch<string>("triggerCron", formInst);
const [fieldTriggerCronExpectedExecutions, setFieldTriggerCronExpectedExecutions] = useState<Date[]>([]);
useEffect(() => {
setTriggerType(node?.config?.executionMethod);
setTriggerCronExecutions(getNextCronExecutions(node?.config?.crontab as string, 5));
}, [node?.config?.executionMethod, node?.config?.crontab]);
setFieldTriggerCronExpectedExecutions(getNextCronExecutions(fieldTriggerCron, 5));
}, [fieldTriggerCron]);
const handleTriggerTypeChange = (value: string) => {
setTriggerType(value);
if (value === "auto") {
formInst.setFieldValue("crontab", formInst.getFieldValue("crontab") || initFormModel().crontab);
const handleTriggerChange = (value: string) => {
if (value === WORKFLOW_TRIGGERS.AUTO) {
formInst.setFieldValue("triggerCron", formInst.getFieldValue("triggerCron") || initFormModel().triggerCron);
}
};
const handleTriggerCronChange = (value: string) => {
setTriggerCronExecutions(getNextCronExecutions(value, 5));
};
return (
<Form {...formProps} form={formInst} disabled={formPending} layout="vertical">
<Form.Item
name="executionMethod"
name="trigger"
label={t("workflow_node.start.form.trigger.label")}
rules={[formRule]}
tooltip={<span dangerouslySetInnerHTML={{ __html: t("workflow_node.start.form.trigger.tooltip") }}></span>}
>
<Radio.Group value={triggerType} onChange={(e) => handleTriggerTypeChange(e.target.value)}>
<Radio value="auto">{t("workflow_node.start.form.trigger.option.auto.label")}</Radio>
<Radio value="manual">{t("workflow_node.start.form.trigger.option.manual.label")}</Radio>
<Radio.Group onChange={(e) => handleTriggerChange(e.target.value)}>
<Radio value={WORKFLOW_TRIGGERS.AUTO}>{t("workflow_node.start.form.trigger.option.auto.label")}</Radio>
<Radio value={WORKFLOW_TRIGGERS.MANUAL}>{t("workflow_node.start.form.trigger.option.manual.label")}</Radio>
</Radio.Group>
</Form.Item>
<Form.Item
name="crontab"
name="triggerCron"
label={t("workflow_node.start.form.trigger_cron.label")}
hidden={triggerType !== "auto"}
hidden={fieldTrigger !== WORKFLOW_TRIGGERS.AUTO}
rules={[formRule]}
tooltip={<span dangerouslySetInnerHTML={{ __html: t("workflow_node.start.form.trigger_cron.tooltip") }}></span>}
extra={
<Show when={triggerCronLastExecutions.length > 0}>
<Show when={fieldTriggerCronExpectedExecutions.length > 0}>
<div>
{t("workflow_node.start.form.trigger_cron.extra")}
<br />
{triggerCronLastExecutions.map((date, index) => (
{fieldTriggerCronExpectedExecutions.map((date, index) => (
<span key={index}>
{dayjs(date).format("YYYY-MM-DD HH:mm:ss")}
<br />
@ -121,12 +115,14 @@ const StartNodeForm = ({ node }: StartNodeFormProps) => {
</Show>
}
>
<Input placeholder={t("workflow_node.start.form.trigger_cron.placeholder")} onChange={(e) => handleTriggerCronChange(e.target.value)} />
<Input placeholder={t("workflow_node.start.form.trigger_cron.placeholder")} />
</Form.Item>
<Form.Item hidden={triggerType !== "auto"}>
<Show when={fieldTrigger === WORKFLOW_TRIGGERS.AUTO}>
<Form.Item>
<Alert type="info" message={<span dangerouslySetInnerHTML={{ __html: t("workflow_node.start.form.trigger_cron_alert.content") }}></span>} />
</Form.Item>
</Show>
<Form.Item>
<Button type="primary" htmlType="submit" loading={formPending}>

View File

@ -7,14 +7,21 @@ import i18n from "@/i18n";
export interface WorkflowModel extends BaseModel {
name: string;
description?: string;
type: string;
crontab?: string;
trigger: string;
triggerCron?: string;
enabled?: boolean;
content?: WorkflowNode;
draft?: WorkflowNode;
enabled?: boolean;
hasDraft?: boolean;
}
export const WORKFLOW_TRIGGERS = Object.freeze({
AUTO: "auto",
MANUAL: "manual",
} as const);
export type WorkflowTriggerType = (typeof WORKFLOW_TRIGGERS)[keyof typeof WORKFLOW_TRIGGERS];
// #region Node
export enum WorkflowNodeType {
Start = "start",
@ -86,8 +93,8 @@ export type WorkflowNode = {
};
export type WorkflowStartNodeConfig = {
executionMethod: string;
crontab?: string;
trigger: string;
triggerCron?: string;
};
export type WorkflowApplyNodeConfig = {
@ -139,7 +146,7 @@ type InitWorkflowOptions = {
export const initWorkflow = (options: InitWorkflowOptions = {}): WorkflowModel => {
const root = newNode(WorkflowNodeType.Start, {}) as WorkflowNode;
root.config = { executionMethod: "manual" };
root.config = { trigger: WORKFLOW_TRIGGERS.MANUAL };
if (options.template === "standard") {
let temp = root;
@ -155,8 +162,8 @@ export const initWorkflow = (options: InitWorkflowOptions = {}): WorkflowModel =
return {
id: null!,
name: `MyWorkflow-${dayjs().format("YYYYMMDDHHmmss")}`,
type: root.config!.executionMethod as string,
crontab: root.config!.crontab as string,
trigger: root.config!.trigger as string,
triggerCron: root.config!.triggerCron as string,
enabled: false,
draft: root,
hasDraft: true,
@ -388,16 +395,19 @@ export const isAllNodesValidated = (node: WorkflowNode): boolean => {
return true;
};
export const getExecuteMethod = (node: WorkflowNode): { type: string; crontab: string } => {
/**
* @deprecated
*/
export const getExecuteMethod = (node: WorkflowNode): { trigger: string; triggerCron: string } => {
if (node.type === WorkflowNodeType.Start) {
return {
type: (node.config?.executionMethod as string) ?? "",
crontab: (node.config?.crontab as string) ?? "",
trigger: (node.config?.trigger as string) ?? "",
triggerCron: (node.config?.triggerCron as string) ?? "",
};
} else {
return {
type: "",
crontab: "",
trigger: "",
triggerCron: "",
};
}
};

View File

@ -25,7 +25,7 @@ import {
import dayjs from "dayjs";
import { ClientResponseError } from "pocketbase";
import { type WorkflowModel, isAllNodesValidated } from "@/domain/workflow";
import { WORKFLOW_TRIGGERS, type WorkflowModel, isAllNodesValidated } from "@/domain/workflow";
import { list as listWorkflow, remove as removeWorkflow, save as saveWorkflow } from "@/repository/workflow";
import { getErrMsg } from "@/utils/error";
@ -67,16 +67,16 @@ const WorkflowList = () => {
title: t("workflow.props.trigger"),
ellipsis: true,
render: (_, record) => {
const trigger = record.type;
const trigger = record.trigger;
if (!trigger) {
return "-";
} else if (trigger === "manual") {
} else if (trigger === WORKFLOW_TRIGGERS.MANUAL) {
return <Typography.Text>{t("workflow.props.trigger.manual")}</Typography.Text>;
} else if (trigger === "auto") {
} else if (trigger === WORKFLOW_TRIGGERS.AUTO) {
return (
<Space className="max-w-full" direction="vertical" size={4}>
<Typography.Text>{t("workflow.props.trigger.auto")}</Typography.Text>
<Typography.Text type="secondary">{record.crontab ?? ""}</Typography.Text>
<Typography.Text type="secondary">{record.triggerCron ?? ""}</Typography.Text>
</Space>
);
}

View File

@ -68,8 +68,8 @@ export const useWorkflowStore = create<WorkflowState>((set, get) => ({
id: (get().workflow.id as string) ?? "",
content: root,
enabled: !get().workflow.enabled,
type: executeMethod.type,
crontab: executeMethod.crontab,
trigger: executeMethod.trigger,
triggerCron: executeMethod.triggerCron,
});
set((state: WorkflowState) => {
@ -79,8 +79,8 @@ export const useWorkflowStore = create<WorkflowState>((set, get) => ({
id: resp.id,
content: resp.content,
enabled: resp.enabled,
type: resp.type,
crontab: resp.crontab,
trigger: resp.trigger,
triggerCron: resp.triggerCron,
},
};
});
@ -93,8 +93,8 @@ export const useWorkflowStore = create<WorkflowState>((set, get) => ({
id: (get().workflow.id as string) ?? "",
content: root,
hasDraft: false,
type: executeMethod.type,
crontab: executeMethod.crontab,
trigger: executeMethod.trigger,
triggerCron: executeMethod.triggerCron,
});
set((state: WorkflowState) => {
@ -104,8 +104,8 @@ export const useWorkflowStore = create<WorkflowState>((set, get) => ({
id: resp.id,
content: resp.content,
hasDraft: false,
type: resp.type,
crontab: resp.crontab,
trigger: resp.trigger,
triggerCron: resp.triggerCron,
},
};
});