diff --git a/app/apis/elpApi.js b/app/apis/elpApi.js new file mode 100644 index 0000000..7c81b3b --- /dev/null +++ b/app/apis/elpApi.js @@ -0,0 +1,42 @@ +export default { + base: { + get_document: "elp/v1/indices/{{type_name}}/{{doc_id}}", + update_document: "elp/v1/indices/{{type_name}}/update/{{doc_id}}", + update_field: "elp/v1/indices/{{type_name}}/update/field/{{doc_id}}", + compute_field: "elp/v1/indices/{{type_name}}/compute/field", + add_document: "elp/v1/indices/{{type_name}}/insert", + delete_document: "elp/v1/indices/{{type_name}}/delete/{{doc_id}}", + getSchema: "elp/schema/get", + }, + search: { + elp_base_count: "elp/v1/indices/{{index_key}}/count", + elp_base_search: "elp/v1/indices/{{index_key}}/search", + elp_voice_search: "elp/voice/{{index_key}}/search", + elp_db_search: "elp/db/indices/{{index_key}}/search", + }, + Info: { + elp_option_get: "elp/v1/base/option/doc/{{main_key}}", + elp_completion: "elp/v1/indices/{{type_name}}/completion/{{property_key}}", + elp_main_label: "elp/v1/base/option/get/items/{{main_label}}", + elp_update_field: "elp/v1/indices/{{type_name}}/update/field/{{doc_id}}", + elp_list_Tree: "/elp/tbase/{{type_name}}/list/tree", + elp_get_Tree: "/elp/tbase/{{type_name}}/get/item/all", + elp_update_Tree: "/elp/tbase/{{type_name}}/update/{{id}}", + elp_delete_Tree: "/elp/tbase/{{type_name}}/delete/{{id}}", + elp_move_in_Tree: + "/elp/tbase/{{type_name}}/move_in/{{drop_id}}/{{drag_id}}", + elp_insert_Tree: "/elp/tbase/{{type_name}}/insert", + elp_relation_Tree: "/elp/tbase/{{type_name}}/relation/add", + elp_relation_Tree_delete: "/elp/tbase/{{type_name}}/relation/delete", + elp_get_list_Tree: "/elp/db/indices/{{index_key}}/tree", + }, + rag_chat: { + // elp_semantic_search: "elp/chat/semantic_search", + elp_chat: "elp/chat/query/{{type_name}}", + note_action: "elp/note/ai/action", + note_job_action: "elp/chat/job/add/action/{{note_id}}", + chat_job_query: "elp/chat/job/add/query/{{type_name}}/{{note_id}}", + chat_job_search_query: "elp/chat/job/search/query/{{type_name}}", + chat_job_get: "elp/chat/job/get/{{job_id}}", + }, +}; diff --git a/app/apis/repoApi.js b/app/apis/repoApi.js new file mode 100644 index 0000000..0e533d6 --- /dev/null +++ b/app/apis/repoApi.js @@ -0,0 +1,32 @@ +export default { + search: { + mirror_search: + "repo/monir/mirror/{{mirror_type}}/{{index_key}}/{{search_type}}/{{sortKey}}/{{field_collapse}}/{{offset}}/{{limit}}/{{filter}}", + autoComplate: "monir/complation/{{index_key}}/{{filter}}", + queryNormal: + "repo/monir/search/{{index_key}}/{{search_type}}/{{sortKey}}/{{field_collapse}}/{{offset}}/{{limit}}/{{filter}}", + textSearch: + "repo/monir/search/text/{{index_key}}/{{field}}/{{offset}}/{{limit}}/{{filter}}", + // queryMirror: + // "monir/mirror/{{mirror_type}}/{{index_key}}/{{search_type}}/{{sortKey}}/{{field_collapse}}/{{offset}}/{{limit}}/{{filter}}", + }, + + public: { + updateProperty_full: + "public/{{index_key}}/edit/{{entity_id}}/{{property}}/index/full", + + updateEntity: "repo/public/{{index_key}}/update/{{id}}", + get_doc_byid: "repo/public/get/byid/{{index_key}}/{{entity_id}}", + uplaod_file: "repo/public/file/{{type_key}}/uploadfile", + }, + calendar: { + schema: { + list: "repo/schema", + }, + list: "repo/calendar/@offset/@limit/@filter", + list_collpase: "repo/calendar/@field_collapsed/@offset/@limit/@filter", + addTask: "repo/calendar/add", + update: "repo/calendar/edit/@id", + delete: "repo/calendar/delete/@id", + }, +}; diff --git a/app/composables/useElpService.js b/app/composables/useElpService.js new file mode 100644 index 0000000..c1b401a --- /dev/null +++ b/app/composables/useElpService.js @@ -0,0 +1,977 @@ +// @/composables/useFormBuilder.js +import { useNuxtApp } from "#app"; +import elpApi from "@/apis/elpApi"; +import repoApi from "@/apis/repoApi"; +import { cleanTextUnpermittedChars } from "@/utils/generalUtil"; + +export function useElpService(props, emit) { + const { $http: httpService } = useNuxtApp(); + const toast = useToast(); + + ///----------------------------------------------------- + ///---- اسکیمای صفحات برنامه + ///----------------------------------------------------- + async function uepGetSchema(system = "search", organ = "monir") { + let payload = { + organ: organ, + system: system, + }; + + const url = elpApi.base.getSchema; + + return await httpService + .postRequest(url, payload) + .then((res) => { + return res?.data; + }) + .catch((err) => { + toast.add({ + title: "خطا", + description: err?.message, + color: "red", + }); + return {}; + }); + + dataEntrySchema.value = res?.data || {}; + } + + ///----------------------------------------------------- + ///--- گرفتن اطلاعات سند (GET Document) + ///----------------------------------------------------- + async function uepGetDocument(entityId, key = "") { + if (!entityId) { + toast.add({ + title: "خطا", + description: "شناسه وجود ندارد", + color: "red", + }); + return undefined; + } + + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.get_document; + url = url.replace("{{type_name}}", key); + url = url.replace("{{doc_id}}", entityId); + + return await httpService + .getRequest(url) + .then((res) => { + return res; // معمولاً شامل doc_id یا کل سند ایجاد شده است + }) + .catch((error) => { + console.error("Error in 1 :", error); + toast.add({ + title: "خطا", + description: "خطا در گرفتن سند، دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + + async function myPostRequest( + url, + payload, + by_message = false, + message = "عملیات با موفقیت انجام شد" + ) { + try { + const res = await httpService.postRequest(url, payload); + + if (by_message && toast?.add) { + toast.add({ + title: "موفق", + description: message, + icon: "i-lucide-file-plus", + }); + } + + return res; + } catch (error) { + console.error("Error in myPostRequest:", error); + + if (toast?.add) { + toast.add({ + title: "خطا", + description: "خطا در عملیات، دوباره تلاش کنید", + color: "red", + }); + } + + return undefined; + } + } + + ///----------------------------------------------------- + ///--- ایجاد سند جدید (Add Document) + ///-- payload = { + ///-- id: "" -- اختیاری + ///-- docuemnt : { + ///-- title: "..." + ///-- ... + ///-- sections: [ ... ] + ///-- ... + ///-- } + ///-- } + + ///----------------------------------------------------- + async function uepAddDocument(payload, key = "", by_message = false) { + if (!payload) { + toast.add({ + title: "خطا", + description: "دادههای سند برای ایجاد الزامی است", + color: "red", + }); + return undefined; + } + + let doc = { + document: { ...payload }, + }; + + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.add_document; + url = url.replace("{{type_name}}", key); + + return await httpService + .postRequest(url, doc) + .then((res) => { + if (by_message) + toast.add({ + title: "موفق", + description: "سند جدید با موفقیت ایجاد شد.", + icon: "i-lucide-file-plus", + }); + return res; // معمولاً شامل doc_id یا کل سند ایجاد شده است + }) + .catch((error) => { + console.error("Error in 1 :", error); + toast.add({ + title: "خطا", + description: "خطا در ایجاد سند جدید، دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + async function uepInsertTree(payload, typeName = "gntree") { + if (!payload) { + toast.add({ + title: "خطا", + description: "اطلاعات گره برای ایجاد الزامی است", + color: "red", + }); + return undefined; + } + + const url = elpApi.Info.elp_insert_Tree.replace("{{type_name}}", typeName); + + return await httpService.postRequest(url, payload).catch((error) => { + console.error("ساخت گرهٔ درخت ناموفق بود:", error); + toast.add({ + title: "خطا", + description: "خطا در ایجاد گرهٔ درخت، دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + + async function uepGetTree(payload, typeName = "gntree") { + const url = elpApi.Info.elp_get_Tree.replace("{{type_name}}", typeName); + + return await httpService.postRequest(url, payload).catch((error) => { + console.error("خواندن درخت ناموفق بود:", error); + return []; + }); + } + + async function uepDeleteTree(nodeId, typeName = "gntree") { + const url = elpApi.Info.elp_delete_Tree + .replace("{{type_name}}", typeName) + .replace("{{id}}", nodeId); + + return await httpService.postRequest(url).catch((error) => { + console.error("حذف گرهٔ درخت ناموفق بود:", error); + return undefined; + }); + } + async function uepUpdateTree(nodeId, payload, typeName = "gntree") { + if (!nodeId) { + toast.add({ + title: "خطا", + description: "شناسه گره برای ویرایش الزامی است", + color: "red", + }); + return undefined; + } + + if (!payload) { + toast.add({ + title: "خطا", + description: "اطلاعات گره برای ویرایش الزامی است", + color: "red", + }); + return undefined; + } + + const url = elpApi.Info.elp_update_Tree + .replace("{{type_name}}", typeName) + .replace("{{id}}", nodeId); + + try { + return await httpService.postRequest(url, payload); + } catch (error) { + console.error("ویرایش گره درخت ناموفق بود:", error); + + toast.add({ + title: "خطا", + description: "خطا در ویرایش گره، دوباره تلاش کنید", + color: "red", + }); + + return undefined; + } + } + ///----------------------------------------------------- + ///--- آپدیت کامل داکیومنت (چند فیلد باهم) + ///-- payload = { + ///-- document : { + ///-- title: "..." + ///-- ... + ///-- sections: [ ... ] + ///-- ... + ///-- } + ///-- } + ///----------------------------------------------------- + async function uepUpdateDocument( + doc_id, + payload, + key = "", + by_message = false + ) { + if (!doc_id) return; + + let doc = { + id: doc_id, + document: { ...payload }, + }; + + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.update_document; // باید این route در بک وجود داشته باشد + url = url.replace("{{type_name}}", key); + url = url.replace("{{doc_id}}", doc_id); + + return await httpService + .postRequest(url, doc) + .then((res) => { + if (by_message) + toast.add({ + title: "موفق", + description: "سند با موفقیت بروزرسانی شد.", + icon: "i-lucide-check", + }); + return res; + }) + .catch((err) => { + console.error("Error in 2 :", err); + toast.add({ + title: "خطا", + description: "خطا در بروزرسانی سند " + err.message, + color: "red", + }); + return undefined; + }); + } + + ///----------------------------------------------------- + ///--- یک فیلد را بروزرسانی می کند + ///-- payload = { + ///-- field_key: str + ///-- field_value: Any + ///-- action: str = 'edit' # edit, add, delete, full + ///-- index_in_array: Optional[int] = None + ///-- id_in_array: Optional[str] = None + ///-- } + ///----------------------------------------------------- + async function uepUpdateField(doc_id, payload, key = "", by_message = false) { + if (!doc_id) { + alert("شناسه uepUpdateField !!"); + return undefined; + } + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.update_field; + url = url.replace("{{type_name}}", key); + url = url.replace("{{doc_id}}", doc_id); + return await httpService + .postRequest(url, payload) + .then(() => { + if (by_message) + toast.add({ + title: "موفق", + description: "عملیات با موفقیت انجام شد.", + icon: "i-lucide-calendar-days", + }); + return true; + }) + .catch((err) => { + console.error("Error in 3 :", err); + toast.add({ + title: "خطا", + description: "خطا در انجام دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + + ///----------------------------------------------------- + ///- حذف کامل یک سند با شناسه مشخص + ///----------------------------------------------------- + async function uepDeleteDocument(doc_id, key = "", by_message = false) { + if (!doc_id) return; + + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.delete_document; + url = url.replace("{{type_name}}", key); + url = url.replace("{{doc_id}}", doc_id); + return await httpService + .postRequest(url, {}) + .then(() => { + if (by_message) + toast.add({ + title: "موفق", + description: "عملیات با موفقیت انجام شد.", + icon: "i-lucide-calendar-days", + }); + return true; + }) + .catch((err) => { + console.error("Error in 7 :", err); + toast.add({ + title: "خطا", + description: "خطا در انجام دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + ///----------------------------------------------------- + ///--- با توجه به یک فیلد، مقدار محاسبه شده ای بر میگردند مثلا : بیشترین مقدار یا مجموع یا ... + ///----------------------------------------------------- + async function uepGetComputeField( + key = "", + property_key = "meet_no", + compute_key = "max", + filters = {} + ) { + let payload = { + compute_key, + property_key, + filters, + }; + + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let url = elpApi.base.compute_field; + url = url.replace("{{type_name}}", key); + + return await httpService + .postRequest(url, payload) + .then((res) => { + return res; + }) + .catch(() => { + toast.add({ + title: "خطا", + description: "خطا در انجام عملیات، دوباره تلاش کنید", + color: "red", + }); + return undefined; + }); + } + + //------------------------------------------- + //------------------------------------------- + async function createSearchRequest( + index_key, + textSearch, + searchTypeKey, + mode_url = "normal", + filterPanel = "", + filterExtended = "", + offset = 0, + limit = 10, + field_collapse = "normal", + sortKey = "normal", + domainKey = "all", + domainSchema = {}, + user_synonyms = {}, + mirror_type = "" + ) { + let _payload = {}; + let domain_label = ""; + let query_string = cleanTextUnpermittedChars(textSearch); + + /* ===== Base URL ===== */ + if (!index_key) { + const config = useRuntimeConfig(); + index_key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let baseUrl = ""; + if (mode_url === "count") { + baseUrl = elpApi.search.elp_base_count; + baseUrl = baseUrl.replace("{{index_key}}", index_key); + } + if (mode_url === "elp_db") { + baseUrl = elpApi.search.elp_db_search; + baseUrl = baseUrl.replace("{{index_key}}", index_key); + } else if (mode_url === "elp_voice") { + baseUrl = elpApi.search.elp_voice_search; + baseUrl = baseUrl.replace("{{index_key}}", index_key); + } else if (mode_url === "mirror") { + baseUrl = repoApi.search.mirror_search; + baseUrl = baseUrl.replace("{{mirror_type}}", mirror_type); + } else if (mode_url === "elp_tree") { + baseUrl = elpApi.Info.elp_get_list_Tree; + baseUrl = baseUrl.replace("{{index_key}}", index_key); + } // if (mode_url === "elp" || mode_url == "") + else { + baseUrl = elpApi.search.elp_base_search; + baseUrl = baseUrl.replace("{{index_key}}", index_key); + } + + // ====Synonym / Vector / Normal + let sysnonymSearchQuery = ""; + + if (!searchTypeKey) searchTypeKey = "normal"; + + if (searchTypeKey === "synonym") { + let newSynonym = {}; + + if (user_synonyms) { + Object.keys(user_synonyms).forEach((key) => { + if ( + !( + "isStopWord" in user_synonyms[key] && + user_synonyms[key].isStopWord + ) + ) { + newSynonym[key] = user_synonyms[key].value; + sysnonymSearchQuery += " " + key; + } + }); + } + + if (textSearch === "" || textSearch === undefined) + textSearch = sysnonymSearchQuery; + + if (Object.keys(newSynonym).length) { + _payload = { + synonym: newSynonym, + }; + } + } else if (searchTypeKey === "vector") { + /* ===== Vector ===== */ + _payload = { + text: query_string, + }; + } else if (!(textSearch === "" || textSearch === undefined)) { + /* ===== Normal ===== */ + query_string = query_string; + + if (!domainKey) domainKey = "all"; + + if (domainKey === "all") { + if (domainSchema?.type_action) { + let isNumberInput = /^\d+$/.test(query_string); + + if (isNumberInput && domainSchema.type_action.number) { + let tag = domainSchema.type_action.number; + query_string = encodeURIComponent("#") + tag + " " + query_string; + } + } + } else if (domainKey !== "advance") { + let domainItem = domainSchema?.domain?.find( + (item) => item.key === domainKey + ); + + if (domainItem) { + domain_label = domainItem.label; + query_string = + encodeURIComponent("#") + domainItem.tag + " " + query_string; + } + } + } + + // === Filters + let filterFull = ""; + + if (searchTypeKey !== "vector" && query_string) { + filterFull += "q=" + query_string; + } + + filterFull += filterPanel + filterExtended; + + if (!filterFull) filterFull = "none"; + + // ==== URL Replace + let url = baseUrl; + const buildName = import.meta.env.VITE_BUILD_NAME; + + url = url.replace("{{appname}}", buildName); + url = url.replace("{{index_key}}", index_key); + url = url.replace("{{search_type}}", searchTypeKey); + url = url.replace("{{sortKey}}", sortKey); + url = url.replace("{{field_collapse}}", field_collapse); + url = url.replace("{{offset}}", offset); + url = url.replace("{{limit}}", limit); + url = url.replace("{{filter}}", filterFull); + + // == Payload + let filters = (filterPanel + filterExtended) + .split("&") + .filter((e) => e.length); + + let filters_obj = {}; + filters.forEach((fl) => { + let fl_items = fl.split("="); + if (fl_items.length === 2) filters_obj[fl_items[0]] = fl_items[1]; + }); + + let payload_full = { + track_total_hits: true, + query: query_string, + search_type: searchTypeKey, + filters: filters_obj, + sort: [sortKey], + from_: offset, + size: limit, + collapse_field: field_collapse, + }; + + if (_payload.synonym) { + payload_full.user_synonyms = _payload.synonym; + } + + return { + url, + payload_full, + payload: _payload, + sysnonymSearchQuery, + domainLabel: domain_label, + }; + } + + //------------------------------------------- + async function uepGetDataSearch({ + index_key, + textSearch, + searchTypeKey, + mode_url, + filterPanel, + filterExtended, + filterids, + offset, + limit, + field_collapse, + sortKey, + domainKey, + domainSchema, + user_synonyms, + mirror_type, + synonymData, + aggregations, + }) { + if (!index_key) { + const config = useRuntimeConfig(); + index_key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + const request = await createSearchRequest( + index_key, + textSearch ?? "", + searchTypeKey ?? "normal", + mode_url ?? "elp", + filterPanel ?? "", + filterExtended ?? "", + offset ?? 0, + limit ?? 10, + field_collapse ?? "normal", + sortKey ?? "normal", + domainKey ?? "all", + domainSchema ?? {}, + user_synonyms ?? {}, + mirror_type ?? "" + ); + + let payload_full = request.payload_full; + if (filterids?.length) { + if (!"filters" in payload_full) payload_full["filters"] = {}; + payload_full.filters["ids"] = filterids; + } + + //------------------ + if (aggregations && Object.keys(aggregations).length) { + request.payload_full.aggregation_fields = aggregations; + } + //------------------ + if (synonymData && Object.keys(synonymData).length) { + if (synonymData.synonyms?.length > 0) { + request.payload_full.synonyms = synonymData.synonyms; + } + if (Object.keys(synonymData.user_synonyms)?.length) { + request.payload_full.user_synonyms = synonymData.user_synonyms; + } + } + + try { + const res = await httpService.postRequest(request.url, payload_full); + + return res; + } catch (err) { + console.error(err); + return {}; + } finally { + } + } + + async function uepLogSearchQuery(query) { + let key = "logsearch"; + + let doc = { + query, + }; + + let url = elpApi.base.add_document; + url = url.replace("{{type_name}}", key); + return await myPostRequest(url, doc, by_message); + } + + //------------------------------------------- + //------------------------------------------- + + // جستجوی معنایی از مسیر کارهای چت (chat job) + /* + offset و limit برای صفحهبندی است (مثل بقیهٔ متدهای جستجو)؛ + در پیلود با نامهای from_ و size فرستاده میشوند که فیلدهای سرورند. + */ + async function uepChatJobSearchQuery( + query, + key, + filters = [], + offset = 0, + limit = 10, + lexical_weight = 0.5, + vector_weight = 0.5, + vector_reranker = false + ) { + + + const url = elpApi.rag_chat.chat_job_search_query.replace( + "{{type_name}}", + key + ); + + let filters_obj = {}; + filters.forEach((el) => { + let fls = el.split("&"); + fls.forEach((fl) => { + let fl_items = fl.split("="); + if (fl_items.length === 2) filters_obj[fl_items[0]] = fl_items[1]; + }); + }); + + const payload = { + query: query ?? "", + from_: offset, + size: limit, + lexical_weight, + vector_weight, + vector_reranker, + filters: filters_obj, + }; + + try { + const res = await httpService.postRequest(url, payload); + + return res; + } catch (err) { + console.error("uepChatJobSearchQuery error:", err); + return {}; + } finally { + } + } + + async function uepChatRag(query, key, filters = [], is_rerank = false) { + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + let filters_obj = {}; + filters.forEach((fl) => { + let fl_items = fl.split("="); + if (fl_items.length === 2) filters_obj[fl_items[0]] = fl_items[1]; + }); + + let payload = { + query, + filters: filters_obj, + sort: ["normal"], + size: 100, + is_rerank, + rerank_limit: 10, + }; + + let url = elpApi.rag_chat.elp_chat; + url = url.replace("{{type_name}}", key); + + try { + const res = await httpService.postRequest( + url, + payload, + { timeout: 180000 } // سه دقیقه + ); + + if (res.status == "success") return res.result; + else return res; + } catch (err) { + console.error(err); + return {}; + } finally { + } + } + + async function uepCahtLLM(user_prompt) { + let payload = { + user_prompt, + }; + + try { + const res = await httpService.postRequest( + elpApi.rag_chat.note_action, + payload + ); + + if (res.status == "success") return res.result; + else return res; + } catch (err) { + console.error(err); + return {}; + } finally { + } + } + async function uepJobAdd(payload, note_id, key = "", onProgress) { + if (!key) { + const config = useRuntimeConfig(); + key = config.public.NUXT_PUBLIC_INDEX_KEY; + } + + const url = elpApi.rag_chat.chat_job_query + .replace("{{type_name}}", key) + .replace("{{note_id}}", note_id); + + try { + const res = await httpService.postRequest(url, payload); + // console.log("add res ==> ", res); + + if (!res?.id) return res; + + return res; + } catch (err) { + console.error("uepJobAdd error:", err); + return {}; + } + } + async function uepJobGet(job_id) { + if (!job_id) return { job_status: "error", result: {} }; + + const url = elpApi.rag_chat.chat_job_get.replace("{{job_id}}", job_id); + + try { + const res = await httpService.getRequest(url); + // console.log("get res ==> ", res); + + const body = res?.result ?? res ?? {}; + + return { + ...body, + result: body, + job_status: body.job_status ?? res?.job_status ?? "wait", + }; + } catch (err) { + console.error("uepJobGet error:", err); + + return { job_status: "wait", result: {}, has_error: true }; + } + } + async function uepJobWaitForFinish(job_id, onProgress, options = {}) { + const repeatTimeQuery = 5000; + const maxRetryOnError = 5; + const abortSignal = options.signal; + + /* + اگر کاربر «توقف» را بزند، حلقه فوراً و بدون درخواست بعدی خارج میشود. + */ + function throwIfStopped() { + if (!abortSignal?.aborted) return; + + const abortError = new Error("پاسخ متوقف شد"); + abortError.name = "AbortError"; + throw abortError; + } + + /* انتظار بین دو درخواست، با قابلیت قطع فوری */ + function waitForNextPoll() { + return new Promise((resolve) => { + if (!abortSignal) { + setTimeout(resolve, repeatTimeQuery); + return; + } + + const timeoutId = setTimeout(() => { + abortSignal.removeEventListener("abort", handleAbort); + resolve(); + }, repeatTimeQuery); + + function handleAbort() { + clearTimeout(timeoutId); + resolve(); + } + + abortSignal.addEventListener("abort", handleAbort, { once: true }); + }); + } + + let retry = 0; + + while (true) { + throwIfStopped(); + + const res = await uepJobGet(job_id); + + throwIfStopped(); + + const result = res.result ?? {}; + const status = res.job_status; + + if (res.has_error) { + retry += 1; + + if (retry > maxRetryOnError) { + throw new Error(`Job unreachable after ${retry} tries: ${job_id}`); + } + + await waitForNextPoll(); + continue; + } + + retry = 0; + + if (typeof onProgress === "function") { + try { + onProgress(result, { job_status: status }); + } catch (err) { + console.error("onProgress error:", err); + } + } + + if (status === "finish") { + return result; + } + + if (status === "error" || status === "cancel") { + throw new Error(`Job ${status}: ${job_id}`); + } + + await waitForNextPoll(); + } + } + async function uepJobAction(note_id, payload) { + // console.log("note_id, payload ==> ", note_id, payload); + if (!note_id) return {}; + + const url = elpApi.rag_chat.note_job_action.replace("{{note_id}}", note_id); + + try { + const res = await httpService.postRequest(url, payload); + // console.log("action res ==> ", res); + + if (res?.status === "success") return res.result; + return res; + } catch (err) { + console.error("uepJobAction error:", err); + return {}; + } + } + // ========== دریافت مترادف از سرور ========== + const getSynonymsFromServer = async (word) => { + try { + let payload = { + query: word, + }; + + const response = await httpService.postRequest( + elpApi.search.repo_synonym_words, + payload + ); + + return response.data; + } catch (error) { + console.error("Error:", error); + return []; + } + }; + ///----------------------------------------------------- + ///----------------------------------------------------- + return { + uepGetDocument, + uepAddDocument, + uepInsertTree, + uepGetTree, + uepDeleteTree, + uepUpdateDocument, + uepDeleteDocument, + uepGetDataSearch, + uepChatJobSearchQuery, + uepChatRag, + uepCahtLLM, + getSynonymsFromServer, + uepUpdateField, + uepJobAdd, + uepJobGet, + uepJobWaitForFinish, + uepGetSchema, + uepGetComputeField, + uepJobAction, + uepUpdateTree, + }; +} + +export default useElpService; diff --git a/app/utils/generalUtil.js b/app/utils/generalUtil.js new file mode 100644 index 0000000..c3f721e --- /dev/null +++ b/app/utils/generalUtil.js @@ -0,0 +1,1071 @@ +import { useRuntimeConfig, useRouter } from "#app"; + +/* ===================================================== + Helpers (ملحقات لازم) +===================================================== */ + +/** + * جایگزین globalMixin.myEncodeQuery + */ +// export function myEncodeQuery(text) { +// if (!text) return ""; +// return encodeURIComponent(text); +// } + +export function uuid4Hex(len = 8) { + const bytes = new Uint8Array(Math.ceil(len / 2)); + crypto.getRandomValues(bytes); + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")) + .join("") + .slice(0, len); +} + +///------------------------------------------ +/// --- توابع html +///------------------------------------------ + +export function hasRichContent(html) { + const parser = new DOMParser(); + const doc = parser.parseFromString(html, "text/html"); + const body = doc.body; + + // بررسی وجود جدول + if (body.querySelector("table")) return true; + + // بررسی وجود استایل inline در هر المان + const allElements = body.querySelectorAll("*"); + for (const el of allElements) { + if (el.hasAttribute("style")) return true; + // بررسی کلاسهای خاص (مثلاً کلاسهای Tailwind یا تیپتاپ) + if ( + el.className && + /(align|color|size|bg|border|font)/i.test(el.className) + ) { + return true; + } + } + + // بررسی تگهای خاص + const richTags = ["FONT", "CENTER", "DIV"]; + for (const tag of richTags) { + if (body.querySelector(tag)) return true; + } + + return false; +} + +export function is_html(str) { + //return preg_match("/<[^<]+>/", $string, $m) != 0; + let m = str.match("/<[^<]+>/"); + return m != null && m.length != 0; +} + +export function isHTML(str) { + // return /^<.*?>$/.test(str) && !!$(str)[0]; + if (str) + // replace html tag with content + str = str + .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/gi, "") + // remove remaining self closing tags + .replace(/(<([^>]+)>)/gi, "") + // remove extra space at start and end + .trim(); + + let res = str && str != ""; + + return res; +} + +export function htmlSimple(text) { + if (isHTML(text)) { + if (is_html(text)) return text; + } + let charLine = "\n"; + if (text.indexOf(charLine) == -1) + if (text.indexOf("\r") != -1) charLine = "\r"; + let lines = text.split(charLine); + var tt = ""; + lines.forEach((text) => { + tt = tt + `
${text}
`; + }); + + return tt; +} + +export function isPlainText(html) { + const temp = document.createElement("div"); + temp.innerHTML = html; + const textContent = temp.textContent.trim(); + + // اگر تعداد کاراکترهای HTML بیشتر از متن خالص باشد، احتمالاً rich است + const htmlLength = html.replace(/\s/g, "").length; + const textLength = textContent.replace(/\s/g, "").length; + + // اگر تگهای اضافی وجود داشته باشد، htmlLength > textLength + return htmlLength === textLength; +} + +export function simpleHtmlToPlainText(html) { + if (!html) return ""; + + // ایجاد المنت موقت + const temp = document.createElement("div"); + temp.innerHTML = html; + + // جایگزینی تگها با خط جدید + let text = temp.innerHTML + // تگهای بلوکی + .replace(/]*>/g, "") + .replace(/<\/p>/g, "\n") + .replace(/
| ]*>/g, "") + .replace(/<\/td>/g, "\t") + .replace(/ | ]*>/g, "") + .replace(/<\/th>/g, "\t") + // حذف بقیه تگها + .replace(/<[^>]*>/g, "") + // حذف فاصلههای اضافی + .replace(/[ \t]+\n/g, "\n") + .replace(/\n[ \t]+/g, "\n") + .replace(/\n{3,}/g, "\n\n"); + + return text.trim(); +} + +// تابع کمکی برای برش HTML با حفظ تگها +export function truncateHtml(html, maxLength) { + if (!html) return ""; + + // استخراج متن ساده برای محاسبه طول + const temp = document.createElement("div"); + temp.innerHTML = html; + const plainText = temp.textContent || temp.innerText || ""; + + // اگر متن کوتاهتر از maxLength است، همین HTML را برگردان + if (plainText.length <= maxLength) { + return html; + } + + // پیدا کردن نقطه مناسب برای برش + let charCount = 0; + let result = ""; + let truncated = false; + + // پردازش تگها با استفاده از Regular Expression + const tags = html.match(/<[^>]*>/g) || []; + const textParts = html.split(/<[^>]*>/); + + for (let i = 0; i < textParts.length; i++) { + const text = textParts[i]; + const tag = i < tags.length ? tags[i] : ""; + + if (charCount + text.length <= maxLength) { + result += text; + charCount += text.length; + if (tag) result += tag; + } else { + // برش متن + const remaining = maxLength - charCount; + result += text.substring(0, remaining) + "..."; + truncated = true; + + // بستن تگهای باز + if (tag) { + // اگر تگ باز است و بسته نشده، آن را ببند + const openTags = []; + const allTags = result.match(/<([a-zA-Z][a-zA-Z0-9]*)[^>]*>/g) || []; + const closeTags = result.match(/<\/([a-zA-Z][a-zA-Z0-9]*)>/g) || []; + + for (const t of allTags) { + const tagName = t.match(/<([a-zA-Z][a-zA-Z0-9]*)/)[1]; + if (!closeTags.some((ct) => ct.includes(tagName))) { + openTags.push(tagName); + } + } + + // بستن تگها + for (const t of openTags.reverse()) { + result += `${t}>`; + } + } + break; + } + } + + return result; +} + +///------------------------------------------ +///------------------------------------------ + +/** + * پاکسازی کاراکترهای غیرمجاز + */ +export function cleanTextUnpermittedChars(text) { + if (!text) return ""; + // console.log("text ", text); + + // همان منطق قبلی (اصلاحشده برای JS صحیح) + text = text.replace(/([\x00-\x1F]|\x7F)/g, ""); + return text; +} + +export function buildImageUrl(path) { + console.log("buildImageUrl called with path:", path); + + if (!path) { + console.log("Path is null/undefined"); + return null; + } + + // اگر آدرس کامل است + if (path.startsWith("http")) { + console.log("Path is already full URL:", path); + return path; + } + if (path.startsWith("blob:")) { + console.log("Path is blob URL:", path); + return path; + } + + const config = useRuntimeConfig(); + + // حذف // اضافی + let cleanPath = path + .replace(/\/+/g, "/") // اسلشهای تکراری → یکی + .replace(/^[/\\]+|[/\\]+$/g, ""); // حذف از ابتدا و انتها (هم / هم \) + + console.log("Clean path:", cleanPath); + + // ساخت آدرس پایه + let BASE_URL = config.public.NUXT_PUBLIC_BASE_URL; + const API_NAME = config.public.NUXT_PUBLIC_API_NAME; + const API_MEDIA = config.public.NUXT_PUBLIC_API_MEDIA; + + if (BASE_URL == "/") { + if ( + window?.location?.origin.startsWith("http://192.168.23") || + window?.location?.origin.startsWith("http://localhost:") + ) + BASE_URL = config.public.NUXT_PUBLIC_LOCAL_URL; + else BASE_URL = window?.location?.origin + BASE_URL; + } + + // console.log("Config values:", { + // BASE_URL: config.public.NUXT_PUBLIC_BASE_URL, + // API_NAME: config.public.NUXT_PUBLIC_API_NAME, + // API_MEDIA: config.public.NUXT_PUBLIC_API_MEDIA + // }); + + // اطمینان از عدم وجود // اضافی + BASE_URL = BASE_URL.replace(/\/$/, ""); + // console.log("BASE_URL after cleanup:", BASE_URL); + + let result = ""; + + if (cleanPath.startsWith("Quick/")) { + // برای گرفتن از سرویس یک سرویس دیگر + result = `http://192.168.23.133/api/file/url/${cleanPath}`; // موقت هست بخاطر هدم دسترسی 102 به فایلها + // result = `${BASE_URL}/${API_NAME}/file/url/${cleanPath}`; + } else if (cleanPath.startsWith("/media")) { + // اگر مسیر با /media شروع میشود + result = `${BASE_URL}/${API_NAME}${cleanPath}`; + } else if (cleanPath.startsWith("media/")) { + result = `${BASE_URL}/${API_NAME}/${cleanPath}`; + } + // اگر مسیر با twork/ شروع میشود (مثل تصاویر آپلود شده) + else if (cleanPath.startsWith("twork/")) { + result = `${BASE_URL}/${API_NAME}/${API_MEDIA}/${cleanPath}`; + } + // اگر مسیر با /twork/ شروع میشود + else if (cleanPath.startsWith("/twork/")) { + result = `${BASE_URL}/${API_NAME}/${API_MEDIA}${cleanPath}`; + } + // حالت کلی + else { + result = `${BASE_URL}/${API_NAME}/${API_MEDIA}/${cleanPath}`; + } + + // console.log("Final image URL:", result); + + return result; +} + +export function mergeStreamText(previous, incoming) { + const prev = previous || ""; + const next = incoming || ""; + + if (!next) return prev; + if (!prev || next.startsWith(prev)) return next; + if (prev.startsWith(next) || (next.length >= 8 && prev.endsWith(next))) + return prev; + + return `${prev}${next}`; +} + +/* =====================================================*/ +// بارگذاری لوگو +export async function getAppLogo(appKey) { + let logoSrc = + "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%234f46e5'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15h-2v-2h2v2zm0-4h-2V7h2v6z'/%3E%3C/svg%3E"; + try { + if (appKey === "jahat") { + const logo = await import("~/assets/jahat/logo.png"); + logoSrc = logo.default; + } else if (appKey === "mokeb") { + const logo = await import("~/assets/mokeb/logo.png"); + logoSrc = logo.default; + } else if (appKey === "kaveshyar") { + const logo = await import("~/assets/kavesh/logo.png"); + logoSrc = logo.default; + } else { + try { + const defaultLogo = await import("~/assets/jahat/logo.png"); + logoSrc = defaultLogo.default; + } catch {} + } + } catch (error) { + console.error("خطا در بارگذاری لوگو:", error); + } + return logoSrc; +} + +export function trimChar(str, char) { + const regex = new RegExp(`^${char}+|${char}+$`, "g"); + return str.replace(regex, ""); +} + +/* =====================================================*/ +export function getTagActions(tagActions) { + let myActions = []; + tagActions?.forEach((tag) => { + if (tag == "edit") + myActions.push({ + icon: "i-lucide-pencil", + title: "ویرایش", + key: tag, + }); + else if (tag == "delete") + myActions.push({ + icon: "i-lucide-square-x", + title: "حذف", + key: tag, + }); + else if (tag == "duplicate") + myActions.push({ + icon: "i-lucide-copy-plus", + title: "کپی ردیف ", + key: tag, + }); + else if (tag == "tbookmark") + myActions.push({ + icon: "i-lucide-bookmark", + title: "علاقه مندی ها", + key: tag, + toggle_icons: { + icon1: "i-lucide-bookmark-check", + icon2: "i-lucide-bookmark", + }, + }); + else if (tag == "summary") + myActions.push({ + icon: "i-lucide-dock", + title: "خلاصه مشخصات", + key: tag, + }); + else if (tag == "copy-link") + myActions.push({ + icon: "i-lucide-clipboard-copy", + title: "کپی لینک", + key: tag, + }); + else if (tag == "state") + myActions.push({ + icon: "i-lucide-trending-up", + title: "انتخاب وضعیت", + key: tag, + }); + else if (tag == "import-infos") + myActions.push({ + key: tag, + icon: "i-lucide-info", + title: "ورود اطلاعات", + }); + else if (tag == "manage-files") + myActions.push({ + key: tag, + icon: "i-lucide-folder-cog", + title: "مدیریت فایل ها", + }); + else if (tag == "has-media") + myActions.push({ + key: tag, + icon: "lucide:list-checks", + title: "وضعیت رسانه", + }); + else if (tag == "add-doc") + myActions.push({ + key: tag, + icon: "lucide:file-plus", + title: "ورود محتوا", + }); + else if (tag == "graph") + myActions.push({ + icon: "i-lucide-vector-square", + title: "گراف", + key: tag, + }); + else if (tag == "aiDep") + myActions.push({ + icon: "i-lucide-banknote-arrow-up", + title: "وابستگی دستوری", + key: tag, + }); + else if (tag == "aiNer") + myActions.push({ + icon: "i-lucide-flag", + title: "نقش های نحوی متن", + action: tag, + }); + }); + return myActions; +} + +export function getSourceKey(rowItem, key, hilight_delimiter = "... ") { + // console.log("getSourceKey ", hilight_delimiter, key, rowItem); + return getSourceData(rowItem, { key: key }, hilight_delimiter); +} + +export function getSourceLabel(rowItem, schema) { + let value = getSourceData(rowItem, schema); + + if (schema.label) value = schema.label + value; + + if (schema.delimiter) value = schema.delimiter + value; + else value += " "; + + return value; +} + +export function getSourceData(rowItem, schema, hilight_delimiter = "... ") { + try { + let key = schema.key; + let trancate_word = schema?.trancate_word; + let delimiter = schema?.hilight_delimiter ?? hilight_delimiter; + let value = ""; + + // if(key == "content") + // console.log("getSourceData ", delimiter, rowItem, schema); + + value = getHighlightText(rowItem, key, delimiter); + if (value != "") return value; + + let _source = rowItem._source ?? rowItem; + if (!_source) return ""; + + key = key.replace("__", "."); + if (key.includes(".")) { + const keys = key.split("."); + for (let i = 0; i < keys.length - 1; i++) { + if (_source[keys[i]] !== undefined) { + _source = _source[keys[i]]; + } else { + return ""; + } + } + key = keys[keys.length - 1]; + } + + if (schema?.object_text && _source[schema.key]) { + const data = _source[schema.key]; + if (schema?.is_array == 1 && Array.isArray(data)) { + data.forEach((el) => { + const text = getObjectText(schema, el); + if (text) value += text + "-"; + }); + } else { + value = getObjectText(schema, data); + } + } + + if (value === "" && _source[key] !== undefined) { + value = _source[key]; + } + + if (value === undefined || value === "") return ""; + + if (typeof value === "boolean") { + if (value === true) value = "بله"; + else if (value === false) value = "خیر"; + } + + if (schema.key == "tags") { + if (Array.isArray(value)) value = value.join("، "); + } + if (schema.key == "convert_time") { + if (typeof value === "string" && value.includes(":")) { + let parts = value.split(":"); + if (parts.length >= 2) { + value = `${parts[0]}:${parts[1]}`; + } + } + return value; + } + + if (trancate_word && trancate_word > 0) { + const words = String(value).split(" "); + if (words.length > trancate_word) { + value = words.slice(0, trancate_word).join(" ") + "..."; + } + } + + let proccess = schema?.process ?? schema?.proccess; + if (proccess) { + if (proccess === "len") { + return String(value).length; + } + if (proccess == "convert_date" || proccess == "date") { + return formatDateToPersian(value); + } else if (proccess == "convert_gdate") { + return convertToDate3Lang(value); + } + } + + // if ( + // key.toLowerCase().startsWith("date") || + // key.toLowerCase().startsWith("time") + // ) { + // return formatDateToPersian(value); + // } + + if (schema?.colors && value in schema.colors) { + value = `${value}`; + } + + return value ?? ""; + } catch (error) { + console.error("Error in getCellValue:", error); + return ""; + } +} + +export function getHighlightText( + item, + key, + hilight_delimiter = "...", + posfix = ["fa", "ph"], +) { + var text = ""; + if (item.highlight) { + let key_highlight = key; + let i = 0; + while (i < posfix.length) { + if (key_highlight in item.highlight) break; + key_highlight = key + "." + posfix[i]; + i++; + } + + if (key_highlight in item.highlight) { + let value1 = ""; + value1 = item.highlight[key_highlight]; + + if (Array.isArray(value1)) text = value1.join(hilight_delimiter); + else text = value1; + } + } + return text; +} + +export function getObjectText(schema, data) { + let text = ""; + if (schema.is_object == 1 && schema.object_text) { + Object.keys(schema.object_text).forEach((k) => { + if (data[k] !== undefined) { + if (schema.object_text[k]) text += " - " + schema.object_text[k] + ":"; + text += data[k]; + } + }); + } else { + text = String(data); + } + return text; +} + +export function convertToDate3Lang(date) { + const resFa = persianDateAndTime(date, "fa-IR"); + const resAr = persianDateAndTime(date, "fa-u-ca-islamic-umalqura"); + const parsedDate = + `${resFa.weekday.short} ${resFa.year.numeric}/${resFa.month.numeric}/${resFa.day.numeric}` + + ` - ${resAr.day.numeric} ${resAr.month.short} ${resAr.year.numeric}`; + return parsedDate; +} + +export function getIranianDate() { + const now = new Date(); + return new Date(now.toLocaleString("en-US", { timeZone: "Asia/Tehran" })); +} + +// زمان نسبی +export function getTimeAgo(timestamp) { + // console.log("getTimeAgo ", timestamp); + + if (!timestamp) return "نامشخص"; + + // اگر timestamp به ثانیه است + let date; + if (typeof timestamp === "number") { + // اگر timestamp به میلیثانیه است + if (timestamp > 1000000000000) { + date = new Date(timestamp); + } else { + // اگر به ثانیه است + date = new Date(timestamp * 1000); + } + } else { + date = new Date(timestamp); + } + + const now = new Date(); + const diffDays = Math.floor(Math.abs(now - date) / (1000 * 60 * 60 * 24)); + + if (diffDays === 0) return "امروز"; + if (diffDays === 1) return "دیروز"; + if (diffDays < 7) return `${diffDays} روز پیش`; + if (diffDays < 30) return `${Math.floor(diffDays / 7)} هفته پیش`; + if (diffDays < 365) return `${Math.floor(diffDays / 30)} ماه پیش`; + return `${Math.floor(diffDays / 365)} سال پیش`; +} + +export function formatDateToPersian(item) { + if (!item) return ""; + + let date; + const num = Number(item); + + if (!isNaN(num) && item.toString().length === 10) { + date = new Date(item * 1000); + } else if (typeof item === "string" && !item.includes("T00:00:00")) { + date = new Date(item + "T00:00:00"); + } else { + date = new Date(item); + } + + if (isNaN(date.getTime())) return item; + + return date.toLocaleDateString("fa-IR"); +} + +/* + عنوان خودکار دفترچهٔ گفتگو: نام بخش + تاریخ شمسی + خروجی مثل: «گفتگو ۱۴۰۵-۰۷-۲۹» +*/ +export function buildChatDefaultTitle() { + const dateParts = new Intl.DateTimeFormat("fa-IR-u-ca-persian", { + year: "numeric", + month: "2-digit", + day: "2-digit", + }).formatToParts(new Date()); + + const getDatePart = (partType) => + dateParts.find((datePart) => datePart.type === partType)?.value ?? ""; + + const year = getDatePart("year"); + const month = getDatePart("month"); + const day = getDatePart("day"); + + return `گفتگو ${year}-${month}-${day}`; +} + +export function openRouteNewPage(item, schema) { + if (!schema || !schema.link_route) { + console.log(" error openRouteNewPage item, schema ", item, schema); + return; + } + + let cloneItem = { ...item }; + if (schema.link_route?.length == 0) return; + + if (schema.link_route?.url_key) { + window.open(item._source.url, "_blank"); + } else { + // let cloneList = []; + // arrayItemData.forEach((item) => { + // cloneList.push({ + // _id: item._id, + // _source: { + // id: item._id, + // title: item?._source?.title ?? item?._source?.book_title, + // qanon_title: item?._source?.qanon_title, + // qanon_id: item?._source?.qanon_id, + // }, + // }); + // }); + + // localStorage.setItem("myList", JSON.stringify(cloneList)); + localStorage.setItem("myItem", JSON.stringify(cloneItem)); + let key = ""; + let query_key = ""; + let query_value = ""; + let keys = ""; + let id_route = ""; + let id_route2 = ""; + let keyName = schema?.link_route.id; + let query = {}; + // if (process.env.VUE_APP_BUILD_NAME != "majles") { + // query = { searchtext: textSearch ?? undefined }; + // } + + if (schema.link_route?.id2) { + id_route2 = getSourceKey(item, schema.link_route.id2); + } + id_route = getSourceKey(item, schema.link_route?.id); + + if (schema.link_route?.query) { + let querys = schema.link_route.query; + if (typeof querys === "string") { + keys = schema.link_route?.query.split("="); + if (keys.length >= 2) { + query_key = keys[0]; + query_value = keys[1]; + } + if (query_key && query_value) { + query[query_key] = query_value; + } + } else { + let newObject = {}; + for (const [key, value] of Object.entries(querys)) { + if (value in item) { + newObject[key] = item[value]; + } else { + newObject[key] = item?._source[value]; + } + } + Object.assign(query, newObject); + } + } + + if (schema.link_route?.key_item || schema.link_route?.key) { + if (schema.link_route?.key_item) + key = getSourceKey(item, schema.link_route.key_item); + else key = schema.link_route.key; + } + + const router = useRouter(); + const routeData = router.resolve({ + name: schema.link_route?.name, + params: { + id: id_route, + ...(id_route2 && { id2: id_route2 }), + key: key, + }, + query: query, + }); + + window.open(routeData.href, "_blank"); + } +} + +//===================================================== + +export function playVoice(player, itemData, index) { + let voice_times = itemData.voice_times; + // console.log("itemData ", voice_times, index); + + let selectedVoice = undefined; + let start = 0; + + if (!voice_times) { + start = 0; + } else if (!voice_times[index]) { + return; // error + } else { + selectedVoice = voice_times[index]; + start = selectedVoice.start || 0; + } + + let src = buildImageUrl(itemData._source.sound_link); + if (player.src != src) { + player.src = src; + } + + player.muted = true; + player.play(); + + setTimeout(() => { + if (player.readyState >= 1) { + initPlayTime(player, start); + } else { + player.addEventListener( + "loadedmetadata", + () => { + initPlayTime(player, start); + }, + { once: true }, + ); + } + }, 1000); +} + +export function initPlayTime(player, start) { + player.pause(); + player.muted = true; + player.currentTime = start; + player + .play() + .then(() => { + setTimeout(() => { + player.muted = false; + player.currentTime = start; + }, 500); + }) + .catch((err) => console.warn("Init play failed:", err)); +} + +//===================================================== + +/* ===================================================== + متنِ استریمِ job (خدمات هوشمند) + ----------------------------------------------------- + خروجی job بهصورت پلبهپل میرسد و شکلش ثابت نیست: + رشتهٔ ساده · JSON رشتهای (حتی ناقص) · آبجکتِ تو در تو + این توابع متنِ هر پل را استخراج و با متن قبلی ترکیب میکنند. +===================================================== */ + +const JOB_TEXT_KEYS = [ + "answer", + "llm_answer", + "llm_text", + "response", + "output", + "text", + "content", + "result", + "message", + "data", +]; + +/* JSON ناقص (وسطِ استریم آبجکت) را تا حد ممکن قابل خواندن میکند */ +function closeTruncatedJson(value) { + let inString = false; + let escaped = false; + const stack = []; + + for (let index = 0; index < value.length; index += 1) { + const char = value[index]; + + if (inString) { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') inString = false; + + continue; + } + + if (char === '"') inString = true; + else if (char === "{" || char === "[") stack.push(char); + else if (char === "}" || char === "]") stack.pop(); + } + + let fixed = value; + + if (inString) fixed += '"'; + + while (stack.length) { + fixed += stack.pop() === "{" ? "}" : "]"; + } + + return fixed; +} + +function pickJobTextFromObject(value, depth = 0) { + if (!value || typeof value !== "object" || depth > 5) return ""; + + for (const key of JOB_TEXT_KEYS) { + const candidate = value[key]; + + if (typeof candidate === "string" && candidate.trim()) return candidate; + + if (candidate && typeof candidate === "object") { + const nested = pickJobTextFromObject(candidate, depth + 1); + + if (nested.trim()) return nested; + } + } + + return ""; +} + +function parseJobJsonText(raw) { + const trimmed = raw.trim(); + + if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return ""; + + for (const candidate of [trimmed, closeTruncatedJson(trimmed)]) { + try { + const parsed = JSON.parse(candidate); + + const inner = + typeof parsed === "string" ? parsed : pickJobTextFromObject(parsed); + + if (inner && inner.trim()) return inner; + } catch { + /* بدنهٔ ناقص؛ حالت بعدی */ + } + } + + return ""; +} + +/** متنِ خامِ یک پل از job (بدون merge) */ +export function pickJobStreamText(partial) { + if (partial == null) return ""; + + if (typeof partial === "string") { + return parseJobJsonText(partial) || partial.trim(); + } + + if (typeof partial !== "object") return ""; + + return pickJobTextFromObject(partial).trim(); +} +/** + * تعاریف پیشفرض و رنگبندی خدمات هوشمند + */ + +export const utilDefaultSmartServices = [ + { + key: "mind-map", + label: "نقشه ذهنی", + description: "نمایش ساختار و ارتباط مفاهیم صفحه بهصورت شاخهای", + icon: "lucide:git-fork", + color: "violet", + actionKey: "ai_mind_map", + prompt: + "از متن کامل صفحه یک نقشه ذهنی منظم بساز. خروجی را فقط به صورت فهرست تو در تو با تورفتگی دو فاصلهای بده؛ به این شکل که موضوع اصلی در خط اول و شاخهها و زیرشاخهها با بولت و تورفتگی مشخص شوند. هیچ توضیح اضافهای ننویس.", + }, + { + key: "structured-summary", + label: "خلاصه ساختاریافته", + description: "خلاصهای منظم از مهمترین بخشها و نکات صفحه", + icon: "lucide:file-text", + color: "sky", + actionKey: "ai_structured_summary", + prompt: + "یک خلاصه ساختاریافته از متن کامل صفحه با چکیده، محورهای اصلی و نتیجهگیری بنویس.", + }, + { + key: "concept-cards", + label: "کارتهای مفهومی", + description: "معرفی مفاهیم کلیدی صفحه با تعریف و نکتهٔ مهم", + icon: "lucide:layers", + color: "green", + actionKey: "ai_concept_cards", + prompt: + "از مفاهیم کلیدی صفحه کارتهای مفهومی بساز. برای هر مفهوم دقیقاً این قالب را رعایت کن:\n### عنوان مفهوم\nتعریف: ...\nنکته کلیدی: ...\nبین کارتها یک خط خالی بگذار.", + }, + { + key: "subject-index", + label: "فهرست موضوعی", + description: "دستهبندی موضوعهای اصلی و فرعی صفحه", + icon: "lucide:list-tree", + color: "orange", + actionKey: "ai_subject_index", + prompt: + "فهرست موضوعی صفحه را به ترتیب موضوعهای اصلی و زیرموضوعها بساز. هر موضوع اصلی را با تیتر ## و زیرموضوعها را با بولت زیر همان تیتر بنویس.", + }, + { + key: "research-questions", + label: "سوالات پژوهشی", + description: "پرسشهایی برای بررسی عمیقتر محتوای صفحه", + icon: "lucide:circle-help", + color: "brown", + actionKey: "ai_research_questions", + prompt: + "بر اساس محتوای صفحه، پرسشهای پژوهشی دقیق و قابل بررسی پیشنهاد بده. هر پرسش را با شماره بنویس و زیر آن یک خط با «چرا مهم است:» و توضیح کوتاه اضافه کن.", + }, + { + key: "audio-summary", + label: "خلاصه صوتی", + description: "روایت صوتی از خلاصهٔ محتوای صفحه", + icon: "lucide:headphones", + color: "red", + isComingSoon: true, + actionKey: "ai_audio_summary", + prompt: + "متن یک خلاصه صوتی کوتاه و روان از صفحه بنویس؛ لحن گفتاری و مناسب شنیدن باشد و آن را در چند پاراگراف کوتاه تقسیم کن.", + }, +]; + +export const utilDefaultServiceColors = { + violet: { + card: "bg-violet-100 hover:bg-violet-200/70 dark:bg-violet-950/40 dark:hover:bg-violet-900/60", + icon: "bg-violet-500", + label: "text-violet-700 dark:text-violet-300", + }, + sky: { + card: "bg-sky-100 hover:bg-sky-200/70 dark:bg-sky-950/40 dark:hover:bg-sky-900/60", + icon: "bg-sky-500", + label: "text-sky-700 dark:text-sky-300", + }, + blue: { + card: "bg-blue-100 hover:bg-blue-200/70 dark:bg-blue-950/40 dark:hover:bg-blue-900/60", + icon: "bg-blue-600", + label: "text-blue-700 dark:text-blue-300", + }, + green: { + card: "bg-emerald-100 hover:bg-emerald-200/70 dark:bg-emerald-950/40 dark:hover:bg-emerald-900/60", + icon: "bg-emerald-600", + label: "text-emerald-700 dark:text-emerald-300", + }, + orange: { + card: "bg-orange-100 hover:bg-orange-200/70 dark:bg-orange-950/40 dark:hover:bg-orange-900/60", + icon: "bg-orange-400", + label: "text-orange-700 dark:text-orange-300", + }, + amber: { + card: "bg-amber-100 hover:bg-amber-200/70 dark:bg-amber-950/40 dark:hover:bg-amber-900/60", + icon: "bg-amber-400", + label: "text-amber-700 dark:text-amber-300", + }, + rose: { + card: "bg-rose-100 hover:bg-rose-200/70 dark:bg-rose-950/40 dark:hover:bg-rose-900/60", + icon: "bg-rose-500", + label: "text-rose-700 dark:text-rose-300", + }, + red: { + card: "bg-red-100 hover:bg-red-200/70 dark:bg-red-950/40 dark:hover:bg-red-900/60", + icon: "bg-red-500", + label: "text-red-700 dark:text-red-300", + }, + brown: { + card: "bg-amber-100 hover:bg-amber-200/70 dark:bg-stone-950/50 dark:hover:bg-stone-900/70", + icon: "bg-amber-700", + label: "text-amber-800 dark:text-amber-300", + }, + cyan: { + card: "bg-cyan-100 hover:bg-cyan-200/70 dark:bg-cyan-950/40 dark:hover:bg-cyan-900/60", + icon: "bg-cyan-500", + label: "text-cyan-700 dark:text-cyan-300", + }, + gray: { + card: "bg-gray-100 hover:bg-gray-200/70 dark:bg-gray-800/50 dark:hover:bg-gray-700/70", + icon: "bg-gray-500", + label: "text-gray-700 dark:text-gray-300", + }, +}; diff --git a/nuxt.config.ts b/nuxt.config.ts index fe52835..6a4524c 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -19,7 +19,7 @@ export default defineNuxtConfig({ css: ["~/assets/css/main.css"], imports: { - dirs: ["stores", "composables", "apis"], + dirs: ["stores", "composables", "apis", "utils"], }, colorMode: { |
|---|