1import { ListResource } from "@/types";
2import { ODAgent } from "@/types/doctypes";
3import { createListResource, createResource } from "frappe-ui";
4import { reactive, ref, watch } from "vue";
5
6const PAGE_LENGTH = 20;
7
8export const agents: ListResource<ODAgent> = createListResource({
9 doctype: "OD Agent",
10 fields: ["name", "user_image", "agent_name", "is_active", "user"],
11 cache: ["OD Agent", "List"],
12 start: 0,
13 pageLength: PAGE_LENGTH,
14 orderBy: "creation desc",
15});
16
17export const activeFilter = ref("Active");
18export const showNewAgentsDialog = ref(false);
19
20export const useAgents = () => {
21 const search = ref("");
22 const filters = reactive({});
23 watch(search, (newValue) => {
24 agents.filters = {
25 agent_name: ["like", `%${newValue}%`],
26 ...filters,
27 };
28 if (!newValue) {
29 agents.filters = {
30 ...filters,
31 };
32 agents.start = 0;
33 agents.pageLength = PAGE_LENGTH;
34 }
35 agents.reload();
36 });
37 watch(
38 filters,
39 (newVal) => {
40 agents.filters = {
41 ...agents.filters,
42 ...newVal,
43 };
44 agents.start = 0;
45 agents.pageLength = PAGE_LENGTH;
46 agents.reload();
47 },
48 { deep: true }
49 );
50 watch(
51 activeFilter,
52 (newVal) => {
53 if (newVal === "Active") {
54 agents.filters = {
55 ...agents.filters,
56 is_active: 1,
57 };
58 } else if (newVal === "Inactive") {
59 agents.filters = {
60 ...agents.filters,
61 is_active: 0,
62 };
63 } else {
64 agents.filters = {
65 ...agents.filters,
66 is_active: ["in", [0, 1]],
67 };
68 }
69 agents.start = 0;
70 agents.pageLength = PAGE_LENGTH;
71 agents.reload();
72 },
73 { immediate: true }
74 );
75
76 async function updateAgent(agent: string, isActive: boolean | number) {
77 const res = createResource({
78 url: "frappe.client.set_value",
79 params: {
80 doctype: "OD Agent",
81 name: agent,
82 fieldname: "is_active",
83 value: isActive,
84 },
85 });
86 await res.submit();
87 }
88
89 return {
90 search,
91 agents,
92 filters,
93 updateAgent,
94 };
95};
96