templates.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * store/templates.js
  3. * Pinia store — Email Templates domain
  4. */
  5. import { defineStore } from 'pinia'
  6. import { ref, computed } from 'vue'
  7. import api from '@/api/index.js'
  8. export const useTemplatesStore = defineStore('templates', () => {
  9. // ── State ────────────────────────────────────────────────────────────────
  10. const templates = ref([])
  11. const loading = ref(false)
  12. const error = ref('')
  13. // ── Getters ──────────────────────────────────────────────────────────────
  14. const count = computed(() => templates.value.length)
  15. const notificationTemplates = computed(() => templates.value.filter(t => t.template_type === 'Notification'))
  16. const overdueTemplates = computed(() => templates.value.filter(t => t.template_type === 'Overdue'))
  17. function nameById(id) {
  18. return templates.value.find(t => t.id === id)?.name ?? `#${id}`
  19. }
  20. // ── Actions ──────────────────────────────────────────────────────────────
  21. async function fetchAll() {
  22. loading.value = true
  23. error.value = ''
  24. try {
  25. const { data } = await api.get('/templates')
  26. templates.value = data
  27. } catch (e) {
  28. error.value = e.response?.data?.detail ?? 'Failed to load email templates.'
  29. } finally {
  30. loading.value = false
  31. }
  32. }
  33. async function create(payload) {
  34. const { data } = await api.post('/templates', payload)
  35. templates.value.push(data)
  36. return data
  37. }
  38. async function update(id, payload) {
  39. const { data } = await api.put(`/templates/${id}`, payload)
  40. const idx = templates.value.findIndex(t => t.id === id)
  41. if (idx !== -1) templates.value[idx] = data
  42. return data
  43. }
  44. async function remove(id) {
  45. await api.delete(`/templates/${id}`)
  46. templates.value = templates.value.filter(t => t.id !== id)
  47. }
  48. return {
  49. templates, loading, error, count,
  50. notificationTemplates, overdueTemplates,
  51. nameById,
  52. fetchAll, create, update, remove,
  53. }
  54. })