Files
2026-11-04 16:40:55 +03:30

61 KiB
Raw Permalink Blame History

درباره پروژه

یک سامانه مدیریت هوشمند مبتنی بر Nuxt 4 است که با هدف [توضیح کوتاه هدف پروژه] توسعه یافته است.

تکنولوژی مورد استفاده

    "@fullcalendar/core": "^6.1.20",
    	"@fullcalendar/daygrid": "^6.1.20",
    	"@fullcalendar/interaction": "^6.1.20",
    	"@fullcalendar/list": "^6.1.20",
    	"@fullcalendar/timegrid": "^6.1.20",
    	"@fullcalendar/vue3": "^6.1.20",
    	"@iconify-json/meteor-icons": "^1.2.1",
    	"@nuxt/icon": "^2.2.1",
    	"@nuxt/ui": "^4.3.0",
    	"@nuxtjs/i18n": "^10.2.1",
    	"@pinia/nuxt": "^0.11.3",
    	"@tiptap/extension-drag-handle": "^3.20.0",
    	"@tiptap/extension-horizontal-rule": "^3.20.0",
    	"@tiptap/extension-link": "^3.20.0",
    	"@tiptap/extension-placeholder": "^3.20.0",
    	"@tiptap/extension-task-item": "^3.20.0",
    	"@tiptap/extension-task-list": "^3.20.0",
    	"@tiptap/extension-text-align": "^3.20.0",
    	"@tiptap/starter-kit": "^3.20.0",
    	"@tiptap/vue-3": "^3.20.0",
    	"@vuelidate/core": "^2.0.3",
    	"@vuelidate/validators": "^2.0.4",
    	"@vueuse/integrations": "^14.1.0",
    	"echarts": "^6.0.0",
    	"export-from-json": "^1.7.4",
    	"jalaali-js": "^1.2.8",
    	"lodash-es": "^4.17.22",
    	"mammoth": "^1.11.0",
    	"nuxt": "^4.2.1",
    	"ohmyfetch": "^0.4.21",
    	"pinia": "^3.0.4",
    	"sortablejs": "^1.15.6",
    	"sweetalert2": "^11.26.4",
    	"vite-tsconfig-paths": "^6.1.1",
    	"vue": "^3.5.25",
    	"vue-router": "^4.6.3",
    	"vue3-persian-datetime-picker": "^1.2.2"

درخت پروژه

pakar/
├── app
│ ├── apis
│ │ ├── elpApi.js
│ │ └── new-project
│ ├── app.config.ts
│ ├── app.vue
│ ├── assets
│ │ ├── css
│ │ │ ├── main.css
│ │ │ └── tailwindcss
│ │ ├── img
│ │ │ └── captcha.png
│ │ └── pakar
│ │ ├── logo.png
│ │ └── theme.json
│ ├── components
│ │ ├── auto-import
│ │ │ ├── BaseModal.vue
│ │ │ └── LoginForm.vue
│ │ ├── lazy-load
│ │ └── new-project
│ ├── composables
│ │ ├── composSystemTheme.ts
│ │ └── useConfirm.ts
│ ├── json
│ ├── layouts
│ │ └── default.vue
│ ├── manuals
│ │ └── utilities.js
│ ├── middleware
│ ├── pages
│ │ ├── about.vue
│ │ ├── contact.vue
│ │ ├── index.vue
│ │ ├── index.vue.backup
│ │ └── new-project
│ ├── plugins
│ │ ├── httpService.ts
│ │ └── themeLoader.client.ts
│ ├── stores
│ │ ├── authStore.ts
│ │ ├── commonStore.ts
│ │ ├── new-project
│ │ └── permissionStore.ts
│ ├── types
│ └── utils
├── HELP2.md
├── HELP.md
├── nuxt.config.ts
├── package.json
├── package-lock.json
├── public
│ ├── favicon.ico
│ ├── fonts
│ │ ├── sahel
│ │ │ ├── Sahel-Black.eot
│ │ │ ├── Sahel-Black.ttf
│ │ │ ├── Sahel-Black.woff
│ │ │ ├── Sahel-Black.woff2
│ │ │ ├── Sahel-Bold.eot
│ │ │ ├── Sahel-Bold.ttf
│ │ │ ├── Sahel-Bold.woff
│ │ │ ├── Sahel-Bold.woff2
│ │ │ ├── Sahel.eot
│ │ │ ├── Sahel-Light.eot
│ │ │ ├── Sahel-Light.ttf
│ │ │ ├── Sahel-Light.woff
│ │ │ ├── Sahel-Light.woff2
│ │ │ ├── Sahel-SemiBold.eot
│ │ │ ├── Sahel-SemiBold.ttf
│ │ │ ├── Sahel-SemiBold.woff
│ │ │ ├── Sahel-SemiBold.woff2
│ │ │ ├── Sahel.ttf
│ │ │ ├── Sahel-VF.ttf
│ │ │ ├── Sahel-VF.woff2
│ │ │ ├── Sahel.woff
│ │ │ └── Sahel.woff2
│ │ └── vazir
│ │ ├── Vazirmatn-Black.woff2
│ │ ├── Vazirmatn-Bold.woff2
│ │ ├── Vazirmatn-ExtraBold.woff2
│ │ ├── Vazirmatn-ExtraLight.woff2
│ │ ├── Vazirmatn-Light.woff2
│ │ ├── Vazirmatn-Medium.woff2
│ │ ├── Vazirmatn-Regular.woff2
│ │ ├── Vazirmatn-SemiBold.woff2
│ │ ├── Vazirmatn-Thin.woff2
│ │ └── Vazirmatn[wght].woff2
│ ├── logo
│ │ └── pakar
│ │ ├── dark_logo.png
│ │ └── light_logo.png
│ └── robots.txt
├── README.md
├── tailwind.config.js
└── tsconfig.json

کد ها و توضیحات هر بخش

1. theme.json

{
	"name": "پروژه جدید من",
	"title": "عنوان پروژه",
	"subTitle": "زیر عنوان پروژه",
	"description": "توضیحات پروژه",
	"version": "1.0.0",
	"logo": {
		"light": "/logo/my-project/light_logo.png",
		"dark": "/logo/my-project/dark_logo.png",
		"favicon": "/favicon.ico",
		"icon": "/logo/my-project/icon.png"
	},
	"font": "Vazirmatn",
	"fontFallback": "system-ui, Tahoma, sans-serif",
	"fontFiles": [
		{
			"weight": "400",
			"style": "normal",
			"src": "/fonts/vazir/Vazirmatn-Regular.woff2"
		},
		{
			"weight": "700",
			"style": "normal",
			"src": "/fonts/vazir/Vazirmatn-Bold.woff2"
		}
	],
	"colors": {
		"primary": {
			"50": "#f0fdf4",
			"100": "#dcfce7",
			"200": "#bbf7d0",
			"300": "#86efac",
			"400": "#4ade80",
			"500": "#22c55e",
			"600": "#16a34a",
			"700": "#15803d",
			"800": "#166534",
			"900": "#14532d",
			"950": "#052e16"
		}
	},
	"layout": {
		"containerWidth": "1280px",
		"sidebarWidth": "280px",
		"headerHeight": "64px",
		"footerHeight": "80px"
	},
	"darkMode": {
		"enabled": true,
		"default": "light",
		"storageKey": "theme-mode"
	},
	"rtl": true,
	"direction": "rtl"
}

2. main.css

/* app/assets/css/main.css */
@import "tailwindcss";
@import "@nuxt/ui";

@theme static {
	/* light-colors */
	--color-light-primary: #fff;
	--color-text__orange: #e86c6b;
	--color-link-color: #2563eb;

	/* dark-colors */
	--color-dark-primary: #111827;
	--color-dark-primary-800: #1f2937;
	--color-dark-primary-700: #374151;
	--color-dark-primary-600: #4b5563;
	--color-dark-primary-500: #6b7280;
	--color-dark-primary-400: #9ca3af;
	--color-dark-primary-300: #d1d5db;
	--color-dark-primary-200: #e5e7eb;
	--color-dark-primary-100: #f3f4f6;
	--color-dark-primary-50: #f9fafb;

	/* رنگ متن معمولی */
	--color-white-normal: #ffffff; /* متن سفید معمولی */
	--color-black-normal: #111827; /* متن مشکی معمولی */

	/* متن سفید */
	--color-white-bold: #ffffff; /* متن پررنگ سفید */
	--color-white-light: rgba(255, 255, 255, 0.6); /* متن کم‌رنگ سفید */
	--color-white-strong: #ffffff; /* متن بولد سفید */

	/* متن خاکستری / دارک */
	--color-dark-normal: #e5e7eb; /* متن خاکستری روشن */
	--color-dark-bold: #111827; /* متن روشن‌تر و بولد */
	--color-dark-light: #6b7280; /* متن کم‌رنگ خاکستری */
	--color-dark-strong: #ffffff; /* متن بولد خاکستری روشن */

	/* متن غیر فعال */
	--color-text-disabled: #9ca3af;

	/* رنگ های دلخواه دیگر */
	--color-text-orange: #e86c6b;
	--color-link-color: #2563eb;
}

/* تعریف رنگ دلخواه  */
/* primary-colors */
/* --color-primary: #00b6e3; */
/* --color-primary-50: #e0f6fb;
--color-primary-100: #b3e9f7;
--color-primary-200: #80d8f3;
--color-primary-300: #4dc6ef;
--color-primary-400: #1ab4eb;
--color-primary-500: #00b6e3;
--color-primary-600: #0097b0;
--color-primary-700: #007580;
--color-primary-800: #005250;
--color-primary-900: #002f30;
--color-primary-950: #001519; */

* {
	font-family: var(--app-font), sans-serif !important;
}

html,
body,
#__nuxt,
.root {
	font-family: var(--app-font), sans-serif !important;
	direction: rtl;
	text-align: right;
}
button,
a {
	cursor: pointer;
}

3. BaseModal.vue

<template>
  <UModal
    v-model:open="isModalOpen"
    :title="localModalSchema.title || ''"
    :description="localModalSchema.description || ''"
    :ui="modalUi"
    :overlay="localModalSchema.overlay !== false"
    :dismissible="localModalSchema.dismissible !== false"
    :scrollable="localModalSchema.scrollable || false"
    :fullscreen="localModalSchema.fullscreen || false"
  >
    <!-- Body -->
    <template #body>
      <slot name="modal-body-content" />
    </template>

    <!-- Footer -->
    <template v-if="hasFooter" #footer>
      <div class="flex w-full flex-wrap items-center justify-between gap-3">
        <!-- right actions -->
        <div class="flex flex-wrap gap-2">
          <UButton
            v-for="action in rightActions"
            :key="action.key"
            v-bind="resolveActionProps(action)"
            @click="onActionClick(action)"
            size="lg"
            class="dark:text-white"
          />
        </div>

        <!-- left actions -->
        <div class="flex flex-wrap items-center gap-2">
          <UButton
            v-for="action in leftActions"
            :key="action.key"
            v-bind="resolveActionProps(action)"
            @click="onActionClick(action)"
            size="lg"
            class="dark:text-white"
          />
        </div>
      </div>

      <div v-if="footerText" class="mt-2 text-sm text-gray-600">
        {{ footerText }}
      </div>
    </template>
  </UModal>
</template>

<script setup>
import { ref, computed, watch } from "vue";

/* ---------------- props & emits ---------------- */

const props = defineProps({
  modalSchema: {
    type: Object,
    default: () => ({
      title: "مدال",
      description: "",
      size: "lg",
      footerDescription: "",
      actions: {
        left: [
          {
            key: "close",
            label: "بستن",
            variant: "outline",
            closeOnClick: true,
          },
          {
            key: "save",
            label: "ذخیره",
            color: "primary",
            closeOnClick: false,
          },
        ],
      },
    }),
  },
  isOpen: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["modal-action", "update-isOpen", "modal-close"]);

/* ---------------- state ---------------- */

const isModalOpen = ref(props.isOpen);
const footerText = ref("");

/* ---------------- computed ---------------- */

const localModalSchema = computed(() => props.modalSchema || {});

const actions = computed(() => localModalSchema.value.actions || {});
const leftActions = computed(() => {
  const actionsList = actions.value.left || [];
  return actionsList.filter((action) => action && action.key); // فیلتر کردن actions خالی
});
const rightActions = computed(() => {
  const actionsList = actions.value.right || [];
  return actionsList.filter((action) => action && action.key); // فیلتر کردن actions خالی
});

const hasFooter = computed(
  () => leftActions.value.length > 0 || rightActions.value.length > 0,
);

/* -------- modal width by size -------- */

const modalWidthMap = {
  sm: "max-w-[400px]",
  md: "max-w-[600px]",
  lg: "max-w-[900px]",
  xl: "max-w-[1200px]",
  xxl: "max-w-[1400px]",
  xxxl: "max-w-[1600px]",
};

const modalUi = computed(() => {
  const size = localModalSchema.value.size || "md";
  const widthClass = modalWidthMap[size] || modalWidthMap.md;

  return {
    ...localModalSchema.value.ui,
    content: [widthClass, localModalSchema.value.ui?.content]
      .filter(Boolean)
      .join(" "),
    header: [
      localModalSchema.value.ui?.header,
      "bg-gray-50 dark:bg-dark-primary",
    ]
      .filter(Boolean)
      .join(" "),
    footer: [
      localModalSchema.value.ui?.footer,
      "bg-gray-50 dark:bg-dark-primary",
    ]
      .filter(Boolean)
      .join(" "),
  };
});

/* ---------------- watchers ---------------- */

/* sync parent → modal */
watch(
  () => props.isOpen,
  (val) => {
    isModalOpen.value = val;
  },
  { immediate: true },
);

/* sync modal → parent (❌ / ESC / overlay) */
watch(isModalOpen, (newVal) => {
  emit("update-isOpen", newVal);

  // اگر مودال بسته شد، event مخصوص close هم emit کن
  if (newVal === false) {
    emit("modal-close");
  }
});

// /* وقتی overlay یا ESC بزند */
// function onOverlayClick() {
//   emit("modal-action", {
//     action: "overlay-close",
//   });
// }

/* footer description */
watch(
  () => localModalSchema.value.footerDescription,
  (val) => {
    footerText.value = val || "";
  },
  { immediate: true },
);

/* ---------------- methods ---------------- */

function onActionClick(action) {
  // همیشه event را emit کن (حتی برای close)
  emit("modal-action", action.key);

  // اگر دکمه باید مودال را ببندد
  if (action.closeOnClick) {
    isModalOpen.value = false;
  }
}

function resolveActionProps(action) {
  return {
    label: action.label,
    icon: action.icon,
    color: action.color || "gray",
    variant: action.variant || "solid",
    size: action.size || "sm",
    loading: action.loading || false,
    disabled: action.disabled || false,
  };
}
</script>


4. composSystemTheme.ts

import { ref, computed } from "vue";
import { useState } from "#imports";

export function composSystemTheme() {
  const isDark = useState<boolean>("is-dark", () => false);
  const { $theme, $themeKey } = useNuxtApp();
  const currentTheme = useState("theme", () => $theme)
  const themeKey = ref($themeKey);

  const toggleDarkMode = () => {
    isDark.value = !isDark.value;
    if (process.client) {
      localStorage.setItem("theme-mode", isDark.value ? "dark" : "light");
      const root = document.documentElement;
      isDark.value ? root.classList.add("dark") : root.classList.remove("dark");
    }
  };

  const logo = computed(() => {
    if (!currentTheme.value) return "";
    return isDark.value
      ? currentTheme.value.logo.dark
      : currentTheme.value.logo.light;
  });

  const primaryColor = computed(() => {
    if (process.client) {
      const v = getComputedStyle(document.documentElement)
        .getPropertyValue("--color-primary-500")
        .trim();
      if (v) return v;
    }
    return currentTheme.value?.colors?.primary?.["500"] || "#4caf50";
  });

  const applyTheme = async () => {
    return currentTheme.value;
  };

  return {
    applyTheme,
    currentTheme,
    isDark,
    toggleDarkMode,
    logo,
    primaryColor,
    themeKey,
  };
}

5. useConfirm.ts

// ~/composables/confirm.ts
import { reactive, readonly } from "vue";

// یک state مشترک برای تمام کامپوننت‌ها
const confirmState = reactive({
  isOpen: false,
  title: "تأیید عملیات",
  message: "آیا از انجام این عملیات اطمینان دارید؟",
  resolve: null as ((value: boolean) => void) | null,
});

export const useConfirmState = () => readonly(confirmState);

export const useConfirm = () => {
  const ucoShowConfirmModal = (
    options: { title?: string; message?: string } = {}
  ): Promise<boolean> => {
    confirmState.title = options.title || "تأیید عملیات";
    confirmState.message =
      options.message || "آیا از انجام این عملیات اطمینان دارید؟";
    confirmState.isOpen = true;

    return new Promise((resolve) => {
      confirmState.resolve = resolve;
    });
  };

  return { ucoShowConfirmModal };
};

export const useConfirmActions = () => {
  const ucoConfirm = () => {
    confirmState.isOpen = false;
    if (confirmState.resolve) confirmState.resolve(true);
    confirmState.resolve = null;
  };

  const ucoCancelConfirmModal = () => {
    confirmState.isOpen = false;
    if (confirmState.resolve) confirmState.resolve(false);
    confirmState.resolve = null;
  };

  return { ucoConfirm, ucoCancelConfirmModal };
};

6. layouts/default.vue

	
<!-- app/layouts/default.vue -->
<template>
  <div class="min-h-screen bg-light-primary dark:bg-dark-primary">

    <main class="">
      <slot />
    </main>
    <Footer />
  </div>
</template>


7. manuals/utilities.js


// import Vue from "vue";
// const crypto = require("crypto");
import exportFromJSON from "export-from-json";
// import store from "@store/store";
export const isLoginRemoved = () => process.env.VUE_APP_LOGIN_REMOVE == 1;

// util to export to excel file using plugin
// https://github.com/zheeeng/export-from-json
export const convertJsonToExcelUsingPlugin = async (
  data,
  fileName = "download"
) => {
  // 'txt'(default), 'css', 'html', 'json', 'csv', 'xls', 'xml'
  const exportType = exportFromJSON.types.xls;
  const withBOM = true;

  return await exportFromJSON({ data, fileName, exportType, withBOM });
};

// util to export to excel file manually
export const exportJsonToExcelManually = (JSONData, FileTitle, ShowLabel) => {
  //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
  var arrData = typeof JSONData != "object" ? JSON.parse(JSONData) : JSONData;
  var CSV = "";
  //This condition will generate the Label/Header
  if (ShowLabel) {
    var row = "";
    //This loop will extract the label from 1st index of on array
    for (var index in arrData[0]) {
      //Now convert each value to string and comma-seprated
      row += encodeURI(index) + ",";
    }
    row = row.slice(0, -1);
    //append Label row with line break
    CSV += row + "\r\n";
  }
  //1st loop is to extract each row
  for (var i = 0; i < arrData.length; i++) {
    var row = "";
    //2nd loop will extract each column and convert it in string comma-seprated
    for (var index in arrData[i]) {
      row += '"' + arrData[i][index] + '",';
    }
    row.slice(0, row.length - 1);
    //add a line break after each row
    CSV += row + "\r\n";
  }
  if (CSV == "") {
    alert("Invalid data");
    return;
  }
  //Generate a file name
  // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8;
  // text/csv;charset=utf-8;
  // var csvContent = "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent);

  var filename = FileTitle;
  var blob = new Blob([CSV], {
    type: "text/csv;charset=utf-8,BOM",
  });

  if (navigator.msSaveBlob) {
    // IE 10+
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement("a");
    if (link.download !== undefined) {
      // feature detection
      // Browsers that support HTML5 download attribute
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.style = "visibility:hidden";
      link.download = filename + ".csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};

// util to delay promise
export const wait = (ms) => {
  return (x) => {
    return new Promise((resolve) => setTimeout(() => resolve(x), ms));
  };
};
// util to createObjectByNewProperties
export const createObjectByNewProperties = (list, allowedProperties) => {
  const properties = [];

  list.forEach((item, index) => {
    const filtered = Object.keys(item)
      .filter((key) => allowedProperties.includes(key))
      .reduce((obj, key) => {
        obj[key] = item[key];
        return obj;
      }, {});

    properties[index] = filtered;
  });
  return properties;
};
// util to convert digits to character
export const toNumbersInCharacters = (number) => {
  const persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"];
  const arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"];
  const englishNumbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
  const persianNumbersInCharacters = [
    "یک",
    "دو",
    "سه",
    "چهار",
    "پنج",
    "شش",
    "هفت",
    "هشت",
    "نه",
    "صفر",
  ];

  // only replace english number with persian number character
  return persianNumbersInCharacters[englishNumbers.indexOf(number)];

  // convert all numbers to persian digits
  // return str.split("").map(c =>
  //     persianNumbersInCharacters[englishNumbers.indexOf(c)] ||
  //     persianNumbersInCharacters[englishNumbers.indexOf(c)] || c).join("")
};
// util to handle if img src is not valid
export const handleImageSrcOnError = ({ target }, isUserAvatar = true) => {
  if (isUserAvatar) target.classList.add("human-avatar");
  target.classList.add("error");
};
// util to convert date to local date and time strng;
export const persianDateAndTime = (stringDate, local = "fa-IR") => {
  let date = new Date(stringDate);
  let jsonDate = {
    weekday: {
      long: date.toLocaleDateString(local, { weekday: "long" }),
      short: date.toLocaleDateString(local, { weekday: "short" }),
      narrow: date.toLocaleDateString(local, { weekday: "narrow" }),
    },
    era: {
      long: date.toLocaleDateString(local, { era: "long" }),
      short: date.toLocaleDateString(local, { era: "short" }),
      narrow: date.toLocaleDateString(local, { era: "narrow" }),
    },
    timeZoneName: {
      long: date.toLocaleDateString(local, { timeZoneName: "long" }),
      short: date.toLocaleDateString(local, { timeZoneName: "short" }),
    },
    year: {
      numeric: date.toLocaleDateString(local, { year: "numeric" }),
      "2-digit": date.toLocaleDateString(local, { year: "2-digit" }),
    },
    month: {
      numeric: date.toLocaleDateString(local, { month: "numeric" }),
      "2-digit": date.toLocaleDateString(local, { month: "2-digit" }),
      long: date.toLocaleDateString(local, { month: "long" }),
      short: date.toLocaleDateString(local, { month: "short" }),
      narrow: date.toLocaleDateString(local, { month: "narrow" }),
    },
    day: {
      numeric: date.toLocaleDateString(local, { day: "numeric" }),
      "2-digit": date.toLocaleDateString(local, { day: "2-digit" }),
    },
    hour: {
      numeric: date.toLocaleTimeString(local, { hour: "numeric" }),
      "2-digit": date.toLocaleTimeString(local, { hour: "2-digit" }),
    },
    minute: {
      numeric: date.toLocaleTimeString(local, { minute: "numeric" }),
      "2-digit": date.toLocaleTimeString(local, { minute: "2-digit" }),
    },
    second: {
      numeric: date.toLocaleTimeString(local, { second: "numeric" }),
      "2-digit": date.toLocaleTimeString(local, { second: "2-digit" }),
    },
  };
  return jsonDate;
};
// util to format numbers to local curency
export const formatNumber = (price = "") => {
  return new Intl.NumberFormat("fa-IR").format(price);
};

export const isValidHttpUrl = (string) => {
  let url;

  try {
    url = new URL(string);
  } catch (_) {
    return false;
  }

  return url.protocol === "http:" || url.protocol === "https:";
};
export const addJsCssFileToDom = (fileUrl, fileType, uuid) => {
  let targetElement =
    fileType == "js" ? "script" : fileType == "css" ? "link" : "none";
  let targetAttr =
    fileType == "js" ? "src" : fileType == "css" ? "href" : "none";

  let node = document.createElement(targetElement);
  node.setAttribute(targetAttr, fileUrl);
  node.setAttribute("id", targetElement + "-" + uuid);

  document.head.appendChild(node);
};
export const removeJsCssFileFromDom = (fileType, uuid) => {
  let targetElement =
    fileType == "js" ? "script" : fileType == "css" ? "link" : "none";
  document.getElementById(targetElement + "-" + uuid)?.remove();
};
export const clearBodyClass = (className = undefined) => {
  if (className) document.querySelector("html").replace(className, "");
  else document.querySelector("html").removeAttribute("class");
};
export const redirectToExternalLink = (href, openInNewTab) => {
  if (href) {
    if (isValidHttpUrl(href) && openInNewTab) window.open(href, "_blank");
    else if (isValidHttpUrl(href) && !openInNewTab) window.location.href = href;
    else if (!isValidHttpUrl(href) && openInNewTab) {
      if (href.includes("www.")) window.open("http://" + href, "_blank");
    } else if (!isValidHttpUrl(href) && !openInNewTab) {
      if (href.includes("www.")) window.location.href = "http://" + href;
    }
  }
};
export const extractAllQueryParams = (href) => {
  return new URLSearchParams(href);

  // return new Proxy(new URLSearchParams(href), {
  // get: (searchParams, prop) => searchParams.get(prop),
  // });
};
export const makeQueryParams = (url, searchParams) => {
  var query = new URLSearchParams();

  // (A) URL SEARCH PARAMS OBJECT TO QUICKLY BUILD QUERY STRING
  Object.keys(searchParams).forEach((key) =>
    query.append(key, searchParams[key])
  );

  // (B) CONVERT TO STRING, APPEND TO URL
  url += "?" + query.toString();
  return url;
};

// export const decryptData = (
//   data,
//   key = "fTjWnZr4u7x!A%D*G-KaNdRgUkXp3s6v",
//   method = "AES-256-CBC",
//   iv = "poaskq2234??@35."
// ) => {
//   let decipher = crypto.createDecipheriv(method, key, iv);
//   let decrypted = decipher.update(data, "base64", "utf8");
//   let dd = decrypted + decipher.final("utf8");
//   return JSON.parse(dd);
// };

// util to handle response errors

export const handleErrors = (error) => {
  return new Promise((resolve, reject) => {
    /* 
      401: The HTTP 401 Unauthorized response status code indicates that
       the client request has not been completed because it lacks
       valid authentication credentials for the requested resource.

      403: The HTTP 403 Forbidden response status code indicates that
      the server understands the request but refuses to authorize it.

      404:  The HTTP 404 Not Found response status code indicates that 
      the server cannot find the requested resource
      
      405: The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed
       response status code indicates that the server knows the
      request method, but the target resource doesn't support this method

      406: Not Acceptable
      */
    try {
      let res = error.response;

      if (res) {
        if (res.status === 401) {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });

          //   router.push({ name: 'login' })
        } else if (res.status === 403) {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });
        } else if (res.status === 404) {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });

          // router.push('/404')
        } else if (res.status === 405) {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });

          // router.push('/404')
        } else if (res.status === 406) {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });

          // router.push('/404')
        } else if (res.status === 500) {
          toast.add({
            title: "خطا!",
            description: res.data.message ?? res.data,
          });
        } else {
          toast.add({
            title: "خطا!",
            description: res.data.message,
          });
        }

        resolve(error.response);
      } else {
        let message = "خطا!!!";

        // if (error) {
        //   message = error.message ?? error;
        // }
        // else
        // {
        //   message = "خطا!!!"
        // }

        reject(new Error(message));

        // text: error.stack,
        toast.add({
          title: message,
        });
      }
    } catch (error) {
      let message = "خطا!!!";
      message = error?.message ?? message;

      return reject(new Error(message));
    }
  });
};

function countDownTimer(timeInSecond = 120) {
  var timeleft = timeInSecond;
  var downloadTimer = setInterval(function () {
    if (timeleft <= 0) {
      clearInterval(downloadTimer);
      // document.getElementById("countdown").innerHTML = "Finished";
    } else {
      // document.getElementById("countdown").innerHTML =
      // timeleft + " seconds remaining";
    }
    timeleft -= 1;
  }, 1000);

  return timeleft;
}

///////////////////////////////////////
/////  html functions
///////////////////////////////////////
export function getSelectionHtmlRange() {
  var sel;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      return sel.getRangeAt(0);
    }
  } else if (document.selection) {
    return document.selection.createRange();
  }
  return null;
}

export function getSelectedHtmlInfo() {
  const selectRange = getSelectionHtmlRange();
  if (!selectRange) return {};

  // if (selectRange.startContainer !== selectRange.endContainer) {
  //   return;
  // }

  let begin = 0;
  let strBegin = "";
  let prevFullText = "";
  if (selectRange.startOffset > 0)
    strBegin = selectRange.startContainer.textContent.substring(
      0,
      selectRange.startOffset - 1
    );

  // برای وقتی که در تگ قبلی ، شماره کلمه انتها ذخیره شده است و نیازی به بررسی قبل از آن نیست
  if (
    selectRange.commonAncestorContainer.previousSibling &&
    selectRange.commonAncestorContainer.previousSibling.dataset?.end
  ) {
    begin =
      parseInt(
        selectRange.commonAncestorContainer.previousSibling.dataset.end
      ) + 1;
    begin += splitWord(strBegin).length;
  } else {
    prevFullText = getPreviousHtmlText(selectRange.startContainer, selectRange);
    begin += splitWord(prevFullText).length;
  }

  let selectedText = selectRange.startContainer.textContent.substring(
    selectRange.startOffset,
    selectRange.endOffset
  );
  let end = begin + splitWord(selectedText).length - 1;

  ///////////////////////////////////////////////////////
  ///// استخراج کلمه کلیک شده و دو کلمه بعدش
  ///// برای حالتی که متنی انتخاب نشده و فقط کلیک شده نیاز هست

  let node = selectRange.startContainer;
  const fullText = node.textContent;
  const offset = selectRange.startOffset;

  const words = fullText.split(/\s+/);
  let totalChars = 0;
  let wordIndex = -1;
  let wordsClicked = "";

  /// چون احتمال داره وسط کلمه کلیک شده باشه، قبل کلمه کلیک شده می ایستیم
  for (let i = 0; i < words.length; i++) {
    totalChars += words[i].length + 1;
    if (offset < totalChars) {
      wordIndex = i;
      break;
    }
  }

  if (wordIndex !== -1) {
    wordsClicked =
      words[wordIndex] +
      " " +
      (words[wordIndex + 1] || "") +
      " " +
      (words[wordIndex + 2] || "");
  }
  ///////////////////////////////////////////////////////

  let info = {
    begin: begin,
    end: end,
    selectedText: selectedText,
    prevTextBegin: strBegin,
    texts: wordsClicked,
    // prevTextFull: prevFullText,
  };
  return info;
}

export function getPreviousHtmlText(node, selectRange = null) {
  let text = "";
  if (!node) return text;
  else if (selectRange && node == selectRange.startContainer) {
    if (selectRange.startOffset > 0)
      text = selectRange.startContainer.textContent.substring(
        0,
        selectRange.startOffset - 1
      );
    // else
    //   text = selectRange.startContainer.textContent;
  } else text = node.textContent;

  if (node.previousSibling)
    text = getPreviousHtmlText(node.previousSibling, null) + text;

  return text;
}
////////////////////////////////////////////////////////////////////

export function splitWord(text) {
  let items = text.split(
    /[\t\n\r\.\'\"«»\)\(\]\[\{\}\%\#\$\*\<\>\/,;،؛ \-!?:٭؟]+/
  );
  // let items = text.split("\t\n\r.'\"«»)(][{}%#$*<>/,;،؛ -!?:٭؟")
  return items;
}

export function normalizeText(
  text,
  options = { charArNormal: true, errorLine: true }
) {
  // //defualt
  // options = {
  //   charArNormal: true,
  //   errorLine: true,
  //   alphabetsNormal: false,
  //   emptylinesNormal: false,
  //   hamzehNormal: false,
  //   spaceCorrection: false,
  //   trimLine: false
  // };

  text = text.trim();

  //اصلاح خطاهای متن در کد خط
  if (options?.errorLine) {
    text = text.replaceAll("\\n", "\n");
    text = text.replaceAll("\\r", "\r");
    text = replaceRegText("(\r\n)+", "\n", text);
    text = text.replaceAll("\r", "\n");

    //شنبهها ==> شنبه‌ها
    //رسیدگیهای ==> رسیدگی‌های
    // text = replaceRegText("(ه)(ها)", /\1\2/gm, text);
  }
  // یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
  if (options?.alphabetsNormal) {
    text = replaceAlphabets(text);
  }

  //حذف خطوط و فاصله‌های خالی
  if (options?.emptylinesNormal) {
    text = replaceRegText("( )+", " ", text);
    text = replaceRegText("(\n)+", "\n", text);
  }

  // نرمال کردن حروف اختلافی عربی و فارسی
  if (options?.charArNormal) {
    text = text.replaceAll("ي", "ی");
    text = text.replaceAll("ك", "ک");
  }

  // پرش از اختلافات همزه‌ای
  if (options?.hamzehNormal) {
    text = replaceRegText("ئ|ﺋ", "ی", text);
    text = replaceRegText("ؤ|ﺅ", "و", text);
    text = replaceRegText("ﺔ|ۀ|ة", "ه", text);
    text = replaceRegText("إ|أ", "ا", text);
  }
  if (options?.dateNormal) {
    text = dateNormalize(text);
  }
  if (options?.spaceCorrection) {
    text = spaceCorrection(text);
  }

  // حذف خطوط اضافی اول و انتهای متن
  if (options?.trimLine) text = text.replace(/^\s+|\s+$/g, "");

  text = text.trim();

  return text;
}

//برعکس بودن تاریخ ها را درست میکند
export function dateNormalize(text, forWord = false) {
  if (forWord) {
    // فرمت YYYY/MM/DD یا YYYY-MM-DD
    text = replaceRegText(
      /(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})/,
      (_, year, month, day) =>
        `${day.padStart(2, "0")}/${month.padStart(2, "0")}/${year}`,
      text
    );

    // // فرمت DD/MM/YYYY یا DD-MM-YYYY
    // text = replaceRegText(
    //   /(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,
    //   (_, day, month, year) =>
    //     `${year}/${month.padStart(2, "0")}/${day.padStart(2, "0")}`,
    //   text
    // );
  } else {
    // فرمت YYYY/MM/DD یا YYYY-MM-DD
    text = replaceRegText(
      /(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})/,
      (_, year, month, day) =>
        `${year}/${month.padStart(2, "0")}/${day.padStart(2, "0")}`,
      text
    );

    // فرمت DD/MM/YYYY یا DD-MM-YYYY
    text = replaceRegText(
      /(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,
      (_, day, month, year) =>
        `${year}/${month.padStart(2, "0")}/${day.padStart(2, "0")}`,
      text
    );
  }

  // // فرمت MM/DD/YYYY
  // text = replaceRegText(
  //   /(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,
  //   (_, month, day, year) =>
  //     `${year}/${month.padStart(2, "0")}/${day.padStart(2, "0")}`,
  //   text
  // );
  return text;
}

export function replaceAlphabets(text) {
  let res = text;
  res = res.replaceAll("\u00AD", "\u200C");
  res = res.replaceAll("\u00AC", "\u200C"); // نیم اسپیس خاص

  res = replaceRegText("ﺁ|آ", "آ", res);
  res = replaceRegText("ﺎ|ٱ|ﺍ", "ا", res); //
  res = replaceRegText("ٲ|أ|ﺄ|ﺃ", "أ", res);
  res = replaceRegText("ﺈ|ﺇ", "إ", res);
  res = replaceRegText("ﺐ|ﺏ|ﺑ|ﺒ", "ب", res);
  res = replaceRegText("ﭖ|ﭗ|ﭙ|ﭘ", "پ", res);
  res = replaceRegText("ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ﺘ", "ت", res);
  res = replaceRegText("ﺙ|ﺛ|ﺚ|ﺜ", "ث", res);
  res = replaceRegText("ﺝ|ڃ|ﺠ|ﺟ", "ج", res);
  res = replaceRegText("ڃ|ﭽ|ﭼ", "چ", res);
  res = replaceRegText("ﺢ|ﺤ|څ|ځ|ﺣ", "ح", res);
  res = replaceRegText("ﺥ|ﺦ|ﺨ|ﺧ", "خ", res);
  res = replaceRegText("ڏ|ډ|ﺪ|ﺩ", "د", res);
  res = replaceRegText("ﺫ|ﺬ|ذ", "ذ", res);
  res = replaceRegText("ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ﺮ", "ر", res);
  res = replaceRegText("ﺰ|ﺯ", "ز", res);
  res = replaceRegText("ﮊ", "ژ", res);
  res = replaceRegText("ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ", "س", res);
  res = replaceRegText("ﺵ|ﺶ|ﺸ|ﺷ", "ش", res);
  res = replaceRegText("ﺺ|ﺼ|ﺻ|ﺹ", "ص", res); //
  res = replaceRegText("ﺽ|ﺾ|ﺿ|ﻀ", "ض", res);
  res = replaceRegText("ﻁ|ﻂ|ﻃ|ﻄ", "ط", res);
  res = replaceRegText("ﻆ|ﻇ|ﻈ", "ظ", res);
  res = replaceRegText("ڠ|ﻉ|ﻊ|ﻋ|ﻌ", "ع", res);
  res = replaceRegText("ﻎ|ۼ|ﻍ|ﻐ|ﻏ", "غ", res);
  res = replaceRegText("ﻒ|ﻑ|ﻔ|ﻓ", "ف", res);
  res = replaceRegText("ﻕ|ڤ|ﻖ|ﻗ|ﻘ", "ق", res);
  res = replaceRegText("ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ك", "ک", res);
  res = replaceRegText("ﮚ|ﮒ|ﮓ|ﮕ|ﮔ", "گ", res);
  res = replaceRegText("ﻝ|ﻞ|ﻠ|ڵ|ﻟ", "ل", res); //
  res = replaceRegText("ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ", "لا", res); //
  res = replaceRegText("ﻡ|ﻤ|ﻢ|ﻣ", "م", res);
  res = replaceRegText("ڼ|ﻦ|ﻥ|ﻨ|ﻧ", "ن", res);
  res = replaceRegText("ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ؤ", "و", res);
  res = replaceRegText("ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ہ", "ه", res);
  res = replaceRegText("ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي", "ی", res);
  res = replaceRegText("¬", "‌", res);
  res = replaceRegText("•|·|●|·|・|∙|。|ⴰ", ".", res);
  res = replaceRegText(",|٬|٫|‚|،", "،", res);
  res = replaceRegText("ʕ", "؟", res);
  res = replaceRegText("۰|٠", "0", res);
  res = replaceRegText("۱|١", "1", res);
  res = replaceRegText("۲|٢", "2", res);
  res = replaceRegText("۳|٣", "3", res);
  res = replaceRegText("۴|٤", "4", res);
  res = replaceRegText("۵", "5", res);
  res = replaceRegText("۶|٦", "6", res);
  res = replaceRegText("۷|٧", "7", res);
  res = replaceRegText("۸|٨", "8", res);
  res = replaceRegText("۹|٩", "9", res);
  res = replaceRegText("²", "2", res);
  res = replaceRegText("|ِ|ُ|َ|ٍ|ٌ|ً|", "", res);
  // res = replaceRegText("ـ", "_", res);
  res = replaceRegText("ـ", "-", res); //

  // res = replaceRegText("([\u0600-\u06FF])ـ([\u0600-\u06FF])", "\1\2", res)  // حذف حروف کشیده
  // res = replaceRegText("([\u0600-\u06FF])ـ", "\1", res)  // حذف حروف کشیده

  res = res.replace(/\u200C+$/, "");
  res = res.trim();

  return res;
}

export function spaceCorrection(text) {
  let res = text;
  res = replaceRegText("^(بی|می|نمی)( )", "$1‌", res);
  res = replaceRegText("( )(می|نمی|بی)( )", "$1$2‌", res);
  res = replaceRegText(
    "( )(هایی|ها|های|ایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|ات|ان|ین|انی|بان|ام|ای|یم|ید|اید|اند|بودم|بودی|بود|بودیم|بودید|بودند|ست)( )",
    "‌$2$3",
    res
  );
  res = replaceRegText("( )(شده|نشده)( )", "‌$2‌", res);
  res = replaceRegText(
    "( )(طلبان|طلب|گرایی|گرایان|شناس|شناسی|گذاری|گذار|گذاران|شناسان|گیری|پذیری|بندی|آوری|سازی|بندی|کننده|کنندگان|گیری|پرداز|پردازی|پردازان|آمیز|سنجی|ریزی|داری|دهنده|آمیز|پذیری|پذیر|پذیران|گر|ریز|ریزی|رسانی|یاب|یابی|گانه|گانه‌ای|انگاری|گا|بند|رسانی|دهندگان|دار)( )",
    "‌$2$3",
    res
  );
  return res;
}

export function replaceRegText(pattern, replacement, text) {
  const regex = new RegExp(pattern, "g");
  return text.replace(regex, replacement);
}

export function generateUID() {
  // I generate the UID from two parts here
  // to ensure the random number provide enough bits.
  var firstPart = (Math.random() * 46656) | 0;
  var secondPart = (Math.random() * 46656) | 0;
  firstPart = ("000" + firstPart.toString(36)).slice(-3);
  secondPart = ("000" + secondPart.toString(36)).slice(-3);
  return firstPart + secondPart; // eg : 9c8yxr
}

function myEncodeQuery(text) {
  if (!text || text == "") return "";
  //text = JSON.stringify(text);
  let ch1 = encodeURIComponent("#");
  let ch3 = encodeURIComponent("\\");
  let ch4 = encodeURIComponent("&");
  text = text.replaceAll("#", ch1);
  text = text.replaceAll("&", ch4);
  text = text.replaceAll("/", "\\");
  text = text.replaceAll("\\", ch3);

  // با تبدیل نقطه مشکل نشانی درخواست در بک حل نشد
  //text = text.replaceAll(".", '%2E');
  return text;
}

export function cleanTextUnpermittedChars(text) {
  if (!text) return "";

  text = text.replaceAll("([0x0000-0x001F]|(0x007F))", "");
  return text;
}


// utils/tree.js
export function findNodeWithPath(nodes, targetId, path = []) {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    const currentPath = [...path, i];

    // ✅ Adjust this condition based on how you identify a node
    if (node.id === targetId) {
      return { node, path: currentPath };
    }

    // Recurse into children if they exist
    if (node.children && node.children.length > 0) {
      const result = findNodeWithPath(node.children, targetId, currentPath);
      if (result) return result;
    }
  }
  return null; // Not found
}

export function updateNodeByPath(nodes, path, newValue) {
  let current = nodes;
  // Navigate to the parent of the target node
  for (let i = 0; i < path.length - 1; i++) {
    current = current[path[i]].children;
  }
  // Update the target node
  const targetIndex = path[path.length - 1];
  current[targetIndex] = { ...current[targetIndex], ...newValue };
}

//////////////////////////////////////////

// export { wait, handleErrors }

8. plugins/httpService.ts


import { useStorage } from "@vueuse/core";

export default defineNuxtPlugin((nuxtApp) => {
  // ======================
  // Runtime Config (Public)
  // ======================
  const config = useRuntimeConfig();

  const BASE_URL = config.public.NUXT_PUBLIC_BASE_URL || "";
  const API_NAME = config.public.NUXT_PUBLIC_API_NAME || "";

  // ======================
  // Safe URL Joiner
  // ======================
  const joinURL = (base: string, path: string) => {
    return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
  };

  const baseURL = joinURL(BASE_URL, API_NAME);

  // ======================
  // Reactive Token
  // ======================
  const token = useStorage<string>("id_token", "GuestAccess");

  // ======================
  // Fetch Instance
  // ======================
  const api = $fetch.create({
    baseURL,

    // ======================
    // Request Interceptor
    // ======================
    onRequest({ options }) {
      const auth = token.value;
      if (!auth) return;
      const headers = (options.headers ||= {});
      if (headers instanceof Headers) {
        headers.set("Authorization", auth);
      } else if (Array.isArray(headers)) {
        headers.push(["Authorization", auth]);
      } else {
        headers.Authorization = auth;
      }
    },

    // ======================
    // Response Handler
    // ======================
    onResponse({ response }) {
      return response._data;
    },

    // ======================
    // Error Handler
    // ======================
    async onResponseError({ response }) {
      const status = response?.status;

      if (status === 401) {
        token.value = null;
        await nuxtApp.runWithContext(() => navigateTo("/login"));
      }

      throw {
        status,
        message:
          response?._data?.message || response?.statusText || "خطای نامشخص",
        data: response?._data || null,
      };
    },
  });

  // ======================
  // HTTP Service (Public API)
  // ======================
  const http = {
    getRequest: (url: string, options: any = {}) =>
      api(url, { method: "GET", ...options }),

    postRequest: (url: string, body: any, options: any = {}) =>
      api(url, { method: "POST", body, ...options }),

    putRequest: (url: string, body: any, options: any = {}) =>
      api(url, { method: "PUT", body, ...options }),

    patchRequest: (url: string, body: any, options: any = {}) =>
      api(url, { method: "PATCH", body, ...options }),

    deleteRequest: (url: string, options: any = {}) =>
      api(url, { method: "DELETE", ...options }),
  };

  // ======================
  // Provide to Nuxt
  // ======================
  return {
    provide: {
      http,
    },
  };
});


9. plugins/themeLoader.client.ts

// plugins/00-themeLoader.client.ts
import pakar from "~/assets/pakar/theme.json";

export const themes = { pakar };

type ThemeKey = keyof typeof themes;
type ThemeConfig = (typeof themes)[ThemeKey];

function hexToRgb(hex: string): string {
  hex = hex.replace("#", "");
  if (hex.length === 3)
    hex = hex
      .split("")
      .map((c) => c + c)
      .join("");
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);
  return `${r} ${g} ${b}`;
}

export default defineNuxtPlugin(() => {
  if (!process.client) return;

  const html = document.documentElement;

  // انتخاب تم - فقط پاکار
  const key: ThemeKey = "pakar";
  const theme: ThemeConfig = themes[key];

  // ست کردن CSS variables
  if (theme.colors && (theme as any).colors.primary) {
    Object.entries((theme as any).colors.primary).forEach(([shade, val]) => {
      html.style.setProperty(`--color-primary-${shade}`, val as string);
    });
  }

  // تنظیم فونت
  if (theme.font) {
    html.style.setProperty("--app-font", theme.font);
    const fontId = `font-${theme.font}`;
    if (!document.getElementById(fontId)) {
      const style = document.createElement("style");
      style.id = fontId;
      let rules = "";
      if (theme.fontFiles && Array.isArray(theme.fontFiles)) {
        theme.fontFiles.forEach((f: any) => {
          rules += `
            @font-face {
              font-family: "${theme.font}";
              src: url("${f.src}") format("woff2");
              font-weight: ${f.weight};
              font-style: ${f.style};
              font-display: swap;
            }
          `;
        });
      }
      style.textContent = rules;
      document.head.appendChild(style);
    }
  }

  // ست کردن لوگوها
  if (theme.logo) {
    if (theme.logo.light)
      html.style.setProperty("--system-logo-light", theme.logo.light);
    if (theme.logo.dark)
      html.style.setProperty("--system-logo-dark", theme.logo.dark);
  }

  // ارائه theme و key به اپ
  return {
    provide: {
      themeKey: key,
      theme,
    },
  };
});

10. stores/authStore.ts

// stores/authStore.ts
import { defineStore } from "pinia";
import { useStorage } from "@vueuse/core";

export const useAuthStore = defineStore("authStore", () => {
  // ===== state =====
  const user = ref<any>({});
  const isAuthenticated = ref(false);
  const isRealUser = ref(false);
  const errors = ref<any>(null);
  const loading = ref(false);

  // ===== getters =====
  const isLoggedIn = computed(() => isAuthenticated.value && !!user.value?.token);
  const userName = computed(() => {
    if (!user.value) return '';
    return `${user.value.first_name || ''} ${user.value.last_name || ''}`.trim();
  });

  // ===== actions =====
  function setUser(response: any) {
    const payload = response?.data ?? response ?? {};
    
    const userData = {
      id: payload.user_id ?? payload.id ?? null,
      level: payload.user_level ?? payload.level ?? null,
      token: payload.token ?? null,
      expire: payload.expire ?? null,
      refresh_token: payload.refresh_token ?? null,
      first_name: payload.first_name ?? payload.user_data?.first_name ?? '',
      last_name: payload.last_name ?? payload.user_data?.last_name ?? '',
      avatar: payload.avatar ?? payload.user_data?.avatar ?? '',
      username: payload.username ?? payload.user_data?.username ?? '',
      email: payload.email ?? payload.user_data?.email ?? '',
      mobile: payload.mobile ?? payload.user_data?.mobile ?? '',
      ...(payload.user_data || {}),
    };

    isAuthenticated.value = true;
    isRealUser.value = true;
    user.value = userData;
    errors.value = null;
    loading.value = false;

    // ذخیره در localStorage با استفاده از useStorage
    try {
      const tokenStorage = useStorage("id_token", "");
      tokenStorage.value = userData.token || "";
      
      const userStorage = useStorage("user", {});
      userStorage.value = userData;
      
      const userIdStorage = useStorage("user_id", "");
      userIdStorage.value = String(userData.id || "");
      
      // تنظیم توکن در http service
      const nuxtApp = useNuxtApp();
      if (nuxtApp.$http && userData.token) {
        nuxtApp.$http.setToken(userData.token);
      }
    } catch (e) {
      console.warn("Could not write to storage:", e);
    }
  }

  async function login(credentials: { username: string; password: string; captcha?: string }) {
    loading.value = true;
    errors.value = null;
    
    try {
      const nuxtApp = useNuxtApp();
      const { $http } = nuxtApp;
      
      const response = await $http.postRequest("/auth/login", credentials);
      
      if (response?.data || response?.token) {
        setUser(response);
        return { success: true, data: response };
      }
      
      throw new Error(response?.message || "ورود ناموفق بود");
    } catch (error: any) {
      errors.value = error?.message || "خطا در ارتباط با سرور";
      loading.value = false;
      return { success: false, error: errors.value };
    }
  }

  async function getCaptcha() {
    try {
      const nuxtApp = useNuxtApp();
      const { $http } = nuxtApp;
      
      const response = await $http.getRequest("/auth/captcha");
      return response;
    } catch (error) {
      console.error("Captcha Error:", error);
      return null;
    }
  }

  async function register(credentials: any) {
    loading.value = true;
    errors.value = null;
    
    try {
      const nuxtApp = useNuxtApp();
      const { $http } = nuxtApp;
      
      const response = await $http.postRequest("/auth/register", credentials);
      
      if (response?.data || response?.token) {
        setUser(response);
        return { success: true, data: response };
      }
      
      throw new Error(response?.message || "ثبت نام ناموفق بود");
    } catch (error: any) {
      errors.value = error?.message || "خطا در ثبت نام";
      loading.value = false;
      return { success: false, error: errors.value };
    }
  }

  async function logout() {
    try {
      const nuxtApp = useNuxtApp();
      const { $http } = nuxtApp;
      
      // تلاش برای logout از سرور
      if (isAuthenticated.value) {
        await $http.postRequest("/auth/logout", {});
      }
    } catch (error) {
      console.warn("Logout API error:", error);
    } finally {
      userReset();
    }
  }

  function userReset() {
    user.value = {};
    isAuthenticated.value = false;
    isRealUser.value = false;
    errors.value = null;
    loading.value = false;

    // پاک کردن localStorage
    try {
      const tokenStorage = useStorage("id_token", "");
      tokenStorage.value = "";
      
      const userStorage = useStorage("user", {});
      userStorage.value = {};
      
      const userIdStorage = useStorage("user_id", "");
      userIdStorage.value = "";
      
      // پاک کردن توکن از http service
      const nuxtApp = useNuxtApp();
      if (nuxtApp.$http) {
        nuxtApp.$http.clearToken();
      }
    } catch (e) {
      console.warn("Could not clear storage:", e);
    }
  }

  // بازیابی session از localStorage در شروع
  const restoreSession = () => {
    try {
      const userStorage = useStorage("user", {});
      const storedUser = userStorage.value;
      
      if (storedUser && storedUser.token) {
        user.value = storedUser;
        isAuthenticated.value = true;
        isRealUser.value = !!storedUser.id;
        
        // تنظیم توکن در http service
        const nuxtApp = useNuxtApp();
        if (nuxtApp.$http && storedUser.token) {
          nuxtApp.$http.setToken(storedUser.token);
        }
      }
    } catch (e) {
      console.warn("Could not restore session:", e);
    }
  };

  // اجرای بازیابی session
  if (process.client) {
    restoreSession();
  }

  return {
    // state
    user,
    isAuthenticated,
    isRealUser,
    errors,
    loading,
    
    // getters
    isLoggedIn,
    userName,
    
    // actions
    setUser,
    login,
    getCaptcha,
    register,
    logout,
    userReset,
    restoreSession,
  };
});

11. stores/commonStore.ts

export const useCommonStore = defineStore("commonStore", () => {
  const sidebarOpen = ref(false);

  function toggleSidebar() {
    sidebarOpen.value = !sidebarOpen.value;
  }

  function closeSidebar() {
    sidebarOpen.value = false;
  }

  return {
    sidebarOpen,
    toggleSidebar,
    closeSidebar,
  };
});

12. stores/permissionStore.ts

// stores/permissionStore.ts
import { defineStore } from "pinia";
import { ref } from "vue";
import { useAuthStore } from "./authStore";
import { useStorage } from "@vueuse/core";

export const getUserPermission = defineStore("permissionStore", () => {
  const permissions = ref<any[]>([]);
  const loading = ref(false);

  const hasPagePermission = (to_fullPath: string) => {
    let index = to_fullPath.indexOf("?");
    if (index !== -1) to_fullPath = to_fullPath.substring(0, index);

    const items = to_fullPath.split("/");
    const page_key = items[1] + "_" + items[2];
    
    return permissions.value.some((p) => p.section_tag === page_key);
  };

  const hasActionPermission = (to_fullPath: string, action_tag: string) => {
    let index = to_fullPath.indexOf("?");
    if (index !== -1) to_fullPath = to_fullPath.substring(0, index);

    const items = to_fullPath.split("/");
    const page_key = items[1] + "_" + items[2];
    
    return permissions.value.some(
      (p) => p.section_tag === page_key && p.action_tag === action_tag
    );
  };

  const fetchUserPermissions = async (projectId?: number) => {
    const { $http } = useNuxtApp();
    const authStore = useAuthStore();
    
    if (!authStore.isAuthenticated && !localStorage.getItem("user")) {
      console.log("No authenticated user found");
      return;
    }
    
    loading.value = true;
    
    try {
      const data = {
        project_id: projectId || 50,
        project_only: 1,
      };

      const response = await $http.postRequest("/permissions/user-permissions", data);
      
      permissions.value = response?.data || response || [];
      
      // ذخیره در localStorage برای استفاده بعدی
      useStorage("permit", permissions.value);
    } catch (error) {
      console.error("❌ Failed to fetch user permissions:", error);
      permissions.value = [];
    } finally {
      loading.value = false;
    }
  };

  const reset = () => {
    permissions.value = [];
    loading.value = false;
  };

  return {
    permissions,
    loading,
    hasPagePermission,
    hasActionPermission,
    fetchUserPermissions,
    reset,
  };
});

13. app.config.ts

export default defineAppConfig({
  ui: {
    colors: {
      primary: "primary",
      secondary: "purple",
      neutral: "zinc",
    },
    button: {
      slots: {
        base: ["cursor-pointer"],
      },
      defaultVariants: {
        color: "primary",
        variant: "solid",
        // size حذف شد - پیش‌فرض Nuxt UI استفاده بشه
      },
    },
  },
});

15. app.vue

<template>
  <UApp>
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </UApp>
  <ConfirmModal />
</template>

<script setup lang="ts">
import { onMounted, watch } from "vue";
import { useHead } from "#imports";
import { composSystemTheme } from "~/composables/composSystemTheme";
import { getUserPermission } from "@/stores/permissionStore";

const userPermissionStore = getUserPermission();
const useSystemTheme = composSystemTheme();
const { applyTheme, logo, currentTheme } = useSystemTheme;

// --------------------
//  تنظیم تم سیستم قبل از render
// --------------------
onMounted(async () => {
  // همگام با localStorage و composable
  const saved = localStorage.getItem("theme-mode");
  if (saved === "dark") {
    document.documentElement.classList.add("dark");
  } else {
    document.documentElement.classList.remove("dark");
  }

  // اعمال theme CSS و فونت‌ها
  await applyTheme();

  // بارگذاری مجوزهای کاربر
  userPermissionStore.fetchUserPermissions();
});

// --------------------
//  reactive عنوان و favicon
// --------------------
watch(
  [logo, currentTheme],
  ([newLogo, newTheme]) => {
    useHead({
      title: `${newTheme?.title || ""} - ${newTheme?.subTitle || ""}`,
      link: [
        {
          rel: "icon",
          type: "image/png",
          href: newLogo || "/favicon.ico",
        },
      ],
    });
  },
  { immediate: true },
); // اجرا بلافاصله برای بار اول
</script>

14. .env

# .env (پایه)
NUXT_PUBLIC_SYSTEM=pakar
NUXT_PUBLIC_API_NAME=api/v1

# .env.monir
NUXT_PUBLIC_SYSTEM=monir
NUXT_PUBLIC_BASE_URL=http://192.168.23.60/
NUXT_PUBLIC_API_NAME=api/v1

# .env.tavasi (اگر نیاز دارید)
NUXT_PUBLIC_SYSTEM=tavasi
NUXT_PUBLIC_BASE_URL=http://localhost:3000/
NUXT_PUBLIC_API_NAME=api/v1

14. nuxt.config.ts

import { fileURLToPath } from "node:url";

export default defineNuxtConfig({
	compatibilityDate: "2025-07-15",
	devtools: { enabled: false },
	// devtools: { enabled: true },
	ssr: false, // آفلاین بهتر با CSR
	modules: ["@nuxt/ui", "@pinia/nuxt", "@nuxt/icon"],
	css: ["~/assets/css/main.css"],
	imports: {
		dirs: ["stores", "composables", "apis"],
	},
	colorMode: {
		preference: "light",
		fallback: "light",
		classSuffix: "",
		storageKey: "theme-mode",
	},
	icon: {
		serverBundle: {
			collections: ["lucide", "system-uicons", "meteor-icons"],
		},
	},
	ui: {
		icons: {
			collections: ["lucide", "system-uicons", "meteor-icons"],
		},
	},
	components: [
		{
			path: "~/components/auto-import",
			extensions: ["vue"],
			pathPrefix: false,
		},
	],
	runtimeConfig: {
		public: {
			apiBase: "", // خالی برای آفلاین
			wsUrl: "",
		},
	},
	alias: {
		"@": fileURLToPath(new URL("./app", import.meta.url)),
		"@@": fileURLToPath(new URL(".", import.meta.url)),
		"@/components": fileURLToPath(new URL("./app/components", import.meta.url)),
		"@/composables": fileURLToPath(
			new URL("./app/composables", import.meta.url),
		),
		"@/layouts": fileURLToPath(new URL("./app/layouts", import.meta.url)),
		"@/pages": fileURLToPath(new URL("./app/pages", import.meta.url)),
		"@/plugins": fileURLToPath(new URL("./app/plugins", import.meta.url)),
		"@/stores": fileURLToPath(new URL("./app/stores", import.meta.url)),
		"@/assets": fileURLToPath(new URL("./app/assets", import.meta.url)),
		"@/public": fileURLToPath(new URL("./public", import.meta.url)),
	},
	// fonts: { providers: false },  ← حذف شد
});

15. package.json

{
	"name": "pakar",
	"version": "1.0.0",
	"description": "پروژه پاکار",
	"type": "module",
	"private": true,
	"scripts": {
		"build": "nuxt build",
		"dev": "nuxt dev",
		"dev-tavasi": "env-cmd -f .env.tavasi nuxt dev --host --port 3006 --inspect",
		"dev-monir": "env-cmd -f .env.monir nuxt dev --host --port 3008 --inspect",
		"build-monir": "env-cmd -f .env.monir nuxt build --host --inspect",
		"build-db": "env-cmd -f .env.db nuxt build --host --inspect"
	},
	"dependencies": {
		"@fullcalendar/core": "^6.1.20",
		"@fullcalendar/daygrid": "^6.1.20",
		"@fullcalendar/interaction": "^6.1.20",
		"@fullcalendar/list": "^6.1.20",
		"@fullcalendar/timegrid": "^6.1.20",
		"@fullcalendar/vue3": "^6.1.20",
		"@iconify-json/meteor-icons": "^1.2.1",
		"@nuxt/icon": "^2.2.1",
		"@nuxt/ui": "^4.3.0",
		"@nuxtjs/i18n": "^10.2.1",
		"@pinia/nuxt": "^0.11.3",
		"@tiptap/extension-drag-handle": "^3.20.0",
		"@tiptap/extension-horizontal-rule": "^3.20.0",
		"@tiptap/extension-link": "^3.20.0",
		"@tiptap/extension-placeholder": "^3.20.0",
		"@tiptap/extension-task-item": "^3.20.0",
		"@tiptap/extension-task-list": "^3.20.0",
		"@tiptap/extension-text-align": "^3.20.0",
		"@tiptap/starter-kit": "^3.20.0",
		"@tiptap/vue-3": "^3.20.0",
		"@vuelidate/core": "^2.0.3",
		"@vuelidate/validators": "^2.0.4",
		"@vueuse/integrations": "^14.1.0",
		"echarts": "^6.0.0",
		"export-from-json": "^1.7.4",
		"jalaali-js": "^1.2.8",
		"lodash-es": "^4.17.22",
		"mammoth": "^1.11.0",
		"nuxt": "^4.2.1",
		"ohmyfetch": "^0.4.21",
		"pinia": "^3.0.4",
		"sortablejs": "^1.15.6",
		"sweetalert2": "^11.26.4",
		"vite-tsconfig-paths": "^6.1.1",
		"vue": "^3.5.25",
		"vue-router": "^4.6.3",
		"vue3-persian-datetime-picker": "^1.2.2"
	},
	"devDependencies": {
		"@iconify-json/lucide": "^1.2.86",
		"env-cmd": "^11.0.0",
		"sass": "^1.95.0",
		"vue-draggable-next": "^2.3.0"
	}
}


16. tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
  darkMode: "class",
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
};

17. tsconfig.json

{
  // https://nuxt.com/docs/guide/concepts/typescript
  "files": [],
  "references": [
    {
      "path": "./.nuxt/tsconfig.app.json"
    },
    {
      "path": "./.nuxt/tsconfig.server.json"
    },
    {
      "path": "./.nuxt/tsconfig.shared.json"
    },
    {
      "path": "./.nuxt/tsconfig.node.json"
    }
  ]
}