feat(crm): formularios Clientes/Prospectos y Proveedores por catálogo — T2026-07-081/082
Frontend de los catálogos de referencia en BD: - Store crm-catalogs + cliente API; selects poblados desde /v1/crm/catalogs (fiscal: régimen, uso CFDI, forma/método de pago SAT, moneda ISO; comercial; país/estado/tipo de domicilio/área). Muestran la descripción, no la clave. - "Otro → especificar" (medio de contacto y clasificación), observaciones generales, y datos de auditoría (ID, fechas, usuarios) en la vista de edición. - Botón "Editar" explícito en los listados. - Pantalla de administración de catálogos (insertar/editar/borrar): globales solo activar/desactivar; los de la empresa con alta/edición/borrado. - addresses.country ampliado a 3 (país ISO alfa-3) + migración con down(). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
"""ampliar crm.addresses.country a 3 (país ISO alfa-3 del catálogo)
|
||||
|
||||
Revision ID: e7f8a9b0c1d2
|
||||
Revises: e6f7a8b9c0d1
|
||||
Create Date: 2026-07-22 00:30:00.000000
|
||||
|
||||
El catálogo de País usa códigos ISO 3166 alfa-3 (MEX, USA, …). La columna
|
||||
addresses.country era String(2); se amplía a String(3) para almacenarlos.
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "e7f8a9b0c1d2"
|
||||
down_revision: Union[str, None] = "e6f7a8b9c0d1"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
SCHEMA = "crm"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.alter_column(
|
||||
"addresses", "country",
|
||||
type_=sa.String(length=3),
|
||||
existing_type=sa.String(length=2),
|
||||
existing_nullable=True,
|
||||
server_default=sa.text("'MEX'"),
|
||||
schema=SCHEMA,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Trunca a 2 chars por si hay códigos alfa-3 guardados (rollback de dev).
|
||||
op.execute("UPDATE crm.addresses SET country = left(country, 2) WHERE length(country) > 2")
|
||||
op.alter_column(
|
||||
"addresses", "country",
|
||||
type_=sa.String(length=2),
|
||||
existing_type=sa.String(length=3),
|
||||
existing_nullable=True,
|
||||
server_default=sa.text("'MX'"),
|
||||
schema=SCHEMA,
|
||||
)
|
||||
@@ -29,7 +29,8 @@ class Address(Base, TenantScopedMixin, TimestampMixin):
|
||||
neighborhood: Mapped[str | None] = mapped_column(String(120), nullable=True) # colonia
|
||||
postal_code: Mapped[str | None] = mapped_column(String(10), nullable=True) # código postal
|
||||
city: Mapped[str | None] = mapped_column(String(120), nullable=True) # municipio
|
||||
state: Mapped[str | None] = mapped_column(String(120), nullable=True) # estado
|
||||
country: Mapped[str | None] = mapped_column(String(2), nullable=True, server_default=text("'MX'"))
|
||||
state: Mapped[str | None] = mapped_column(String(120), nullable=True) # estado (código catálogo)
|
||||
# País como código ISO 3166 alfa-3 del catálogo (p. ej. MEX). Ampliado de 2→3.
|
||||
country: Mapped[str | None] = mapped_column(String(3), nullable=True, server_default=text("'MEX'"))
|
||||
reference_notes: Mapped[str | None] = mapped_column(Text, nullable=True) # referencias
|
||||
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
63
frontend/src/lib/api/crm/catalogs.ts
Normal file
63
frontend/src/lib/api/crm/catalogs.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Cliente API — Catálogos de referencia del CRM (SAT/ISO + del cliente).
|
||||
* T2026-07-081/082.
|
||||
*/
|
||||
import { api, type ApiResponse } from '$lib/api';
|
||||
|
||||
export interface CatalogItem {
|
||||
id: number;
|
||||
catalog: string;
|
||||
code: string;
|
||||
label: string;
|
||||
parent_catalog?: string | null;
|
||||
parent_code?: string | null;
|
||||
tenant_id: number | null;
|
||||
sort_order: number;
|
||||
is_active: boolean;
|
||||
is_system: boolean;
|
||||
}
|
||||
|
||||
export interface CatalogMeta {
|
||||
catalog: string;
|
||||
label: string;
|
||||
scope: 'global' | 'tenant';
|
||||
is_system: boolean;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface CatalogItemInput {
|
||||
code: string;
|
||||
label: string;
|
||||
parent_catalog?: string | null;
|
||||
parent_code?: string | null;
|
||||
sort_order?: number;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
function qp(companyId: number, extra?: Record<string, string | number | boolean | undefined>) {
|
||||
const qs = new URLSearchParams({ company_id: String(companyId) });
|
||||
for (const [k, v] of Object.entries(extra ?? {})) if (v !== undefined && v !== '') qs.set(k, String(v));
|
||||
return qs.toString();
|
||||
}
|
||||
async function unwrap<T>(p: Promise<{ data?: T; error?: string }>): Promise<T> {
|
||||
const res = await p;
|
||||
if (res.error) throw new Error(res.error);
|
||||
return res.data as T;
|
||||
}
|
||||
|
||||
export const referenceCatalogsAPI = {
|
||||
/** Metadata de todos los catálogos (para la pantalla de administración). */
|
||||
meta: (companyId: number) => unwrap<CatalogMeta[]>(api.get(`/v1/crm/catalogs?${qp(companyId)}`)),
|
||||
/** Opciones activas de un catálogo (global + del tenant), con dependiente opcional. */
|
||||
list: (catalog: string, companyId: number, parentCode?: string) =>
|
||||
unwrap<CatalogItem[]>(api.get(`/v1/crm/catalogs/${catalog}?${qp(companyId, { parent_code: parentCode })}`)),
|
||||
/** Todas las opciones incluyendo inactivas (administración). */
|
||||
listAll: (catalog: string, companyId: number) =>
|
||||
unwrap<CatalogItem[]>(api.get(`/v1/crm/catalogs/${catalog}?${qp(companyId, { include_inactive: true })}`)),
|
||||
create: (catalog: string, companyId: number, data: CatalogItemInput, scope: 'tenant' | 'global' = 'tenant') =>
|
||||
api.post(`/v1/crm/catalogs/${catalog}?${qp(companyId, { scope })}`, data) as Promise<ApiResponse<CatalogItem>>,
|
||||
update: (catalog: string, id: number, companyId: number, data: Partial<CatalogItemInput>) =>
|
||||
api.patch(`/v1/crm/catalogs/${catalog}/${id}?${qp(companyId)}`, data) as Promise<ApiResponse<CatalogItem>>,
|
||||
remove: (catalog: string, id: number, companyId: number) =>
|
||||
api.delete(`/v1/crm/catalogs/${catalog}/${id}?${qp(companyId)}`) as Promise<ApiResponse<void>>
|
||||
};
|
||||
@@ -24,10 +24,12 @@ export interface Account {
|
||||
status: AccountStatus;
|
||||
commercial_classification: string | null;
|
||||
preferred_contact_method: string | null;
|
||||
preferred_contact_other: string | null;
|
||||
language: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
website: string | null;
|
||||
commercial_observations: string | null;
|
||||
tax_regime: string | null;
|
||||
cfdi_use: string | null;
|
||||
payment_method: string | null;
|
||||
@@ -66,6 +68,7 @@ export interface Supplier {
|
||||
person_type: string | null;
|
||||
status: AccountStatus;
|
||||
classifications: string[];
|
||||
classification_other: string | null;
|
||||
services_offered: string | null;
|
||||
coverage: string | null;
|
||||
countries: string[];
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import type { AccountInput } from '$lib/api/crm';
|
||||
import {
|
||||
ACCOUNT_TYPES, ACCOUNT_STATUS, RECORD_TYPES, PERSON_TYPES,
|
||||
COMMERCIAL_CLASSIFICATION, CONTACT_METHODS
|
||||
} from '$lib/components/crm/format';
|
||||
import { ACCOUNT_TYPES } from '$lib/components/crm/format';
|
||||
import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
|
||||
|
||||
// `form` es un objeto reactivo del padre; se mutan sus propiedades vía bind:value.
|
||||
let { form = $bindable(), tab }: { form: AccountInput; tab: string } = $props();
|
||||
|
||||
const inputCls =
|
||||
'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
// Catálogos que usa este formulario (se precargan; los selects se llenan solos).
|
||||
onMount(() => {
|
||||
void crmCatalogs.preload([
|
||||
'tipo_registro', 'tipo_persona', 'estatus', 'giro', 'clasificacion_cliente',
|
||||
'medio_contacto', 'idioma', 'regimen_fiscal', 'uso_cfdi', 'metodo_pago',
|
||||
'forma_pago', 'moneda'
|
||||
]);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if tab === 'generales'}
|
||||
@@ -18,28 +26,32 @@
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Nombre comercial</span><input class={inputCls} bind:value={form.trade_name} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">RFC</span><input class="font-mono {inputCls}" maxlength="13" bind:value={form.rfc} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">CURP</span><input class="font-mono {inputCls}" maxlength="18" bind:value={form.curp} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de registro</span><select class={inputCls} bind:value={form.record_type}>{#each RECORD_TYPES as r (r.value)}<option value={r.value}>{r.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de persona</span><select class={inputCls} bind:value={form.person_type}><option value={undefined}>—</option>{#each PERSON_TYPES as p (p.value)}<option value={p.value}>{p.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Giro / Industria</span><input class={inputCls} bind:value={form.industry} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de registro</span><select class={inputCls} bind:value={form.record_type}>{#each crmCatalogs.options('tipo_registro') as r (r.value)}<option value={r.value}>{r.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de persona</span><select class={inputCls} bind:value={form.person_type}><option value={undefined}>—</option>{#each crmCatalogs.options('tipo_persona') as p (p.value)}<option value={p.value}>{p.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Giro / Industria</span><select class={inputCls} bind:value={form.industry}><option value={undefined}>—</option>{#each crmCatalogs.options('giro') as g (g.value)}<option value={g.value}>{g.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo operativo</span><select class={inputCls} bind:value={form.account_type}><option value={undefined}>—</option>{#each ACCOUNT_TYPES as t (t.value)}<option value={t.value}>{t.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={form.status}>{#each ACCOUNT_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={form.status}>{#each crmCatalogs.options('estatus') as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
|
||||
</div>
|
||||
{:else if tab === 'comercial'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Clasificación</span><select class={inputCls} bind:value={form.commercial_classification}><option value={undefined}>—</option>{#each COMMERCIAL_CLASSIFICATION as c (c.value)}<option value={c.value}>{c.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Medio de contacto preferido</span><select class={inputCls} bind:value={form.preferred_contact_method}><option value={undefined}>—</option>{#each CONTACT_METHODS as m (m.value)}<option value={m.value}>{m.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Idioma</span><input class={inputCls} bind:value={form.language} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Clasificación del cliente</span><select class={inputCls} bind:value={form.commercial_classification}><option value={undefined}>—</option>{#each crmCatalogs.options('clasificacion_cliente') as c (c.value)}<option value={c.value}>{c.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Medio de contacto preferido</span><select class={inputCls} bind:value={form.preferred_contact_method}><option value={undefined}>—</option>{#each crmCatalogs.options('medio_contacto') as m (m.value)}<option value={m.value}>{m.label}</option>{/each}</select></label>
|
||||
{#if form.preferred_contact_method === 'otro'}
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Especifica el medio de contacto</span><input class={inputCls} bind:value={form.preferred_contact_other} placeholder="Indica cuál" /></label>
|
||||
{/if}
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Idioma</span><select class={inputCls} bind:value={form.language}><option value={undefined}>—</option>{#each crmCatalogs.options('idioma') as i (i.value)}<option value={i.value}>{i.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Email</span><input type="email" class={inputCls} bind:value={form.email} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Teléfono</span><input class={inputCls} bind:value={form.phone} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Sitio web</span><input class={inputCls} bind:value={form.website} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Observaciones generales</span><textarea rows="3" class={inputCls} bind:value={form.commercial_observations}></textarea></label>
|
||||
</div>
|
||||
{:else if tab === 'fiscal'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Régimen fiscal</span><input class={inputCls} bind:value={form.tax_regime} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Uso de CFDI</span><input class={inputCls} bind:value={form.cfdi_use} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Método de pago</span><input class={inputCls} bind:value={form.payment_method} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Forma de pago</span><input class={inputCls} bind:value={form.payment_form} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda</span><input class={inputCls} maxlength="3" bind:value={form.currency} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Régimen fiscal</span><select class={inputCls} bind:value={form.tax_regime}><option value={undefined}>—</option>{#each crmCatalogs.options('regimen_fiscal') as r (r.value)}<option value={r.value}>{r.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Uso de CFDI</span><select class={inputCls} bind:value={form.cfdi_use}><option value={undefined}>—</option>{#each crmCatalogs.options('uso_cfdi') as u (u.value)}<option value={u.value}>{u.value} — {u.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Método de pago</span><select class={inputCls} bind:value={form.payment_method}><option value={undefined}>—</option>{#each crmCatalogs.options('metodo_pago') as m (m.value)}<option value={m.value}>{m.value} — {m.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Forma de pago</span><select class={inputCls} bind:value={form.payment_form}><option value={undefined}>—</option>{#each crmCatalogs.options('forma_pago') as f (f.value)}<option value={f.value}>{f.value} — {f.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda</span><select class={inputCls} bind:value={form.currency}><option value={undefined}>—</option>{#each crmCatalogs.options('moneda') as c (c.value)}<option value={c.value}>{c.value} — {c.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Límite de crédito</span><input type="number" min="0" step="0.01" class={inputCls} bind:value={form.credit_limit} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Días de crédito</span><input type="number" min="0" class={inputCls} bind:value={form.credit_days} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Patente aduanal</span><input class={inputCls} maxlength="20" bind:value={form.patente_aduanal} /></label>
|
||||
@@ -47,7 +59,7 @@
|
||||
</div>
|
||||
{:else if tab === 'observaciones'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Comentarios</span><textarea rows="4" class={inputCls} bind:value={form.notes}></textarea></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Comentarios generales</span><textarea rows="4" class={inputCls} bind:value={form.notes}></textarea></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Notas internas</span><textarea rows="4" class={inputCls} bind:value={form.internal_notes}></textarea></label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -8,10 +8,16 @@
|
||||
addressesAPI, contactsAPI, documentsAPI,
|
||||
type Address, type Contact, type Document, type AddressInput, type ContactInput, type DocumentInput
|
||||
} from '$lib/api/crm';
|
||||
import { ADDRESS_TYPES, DOC_TYPES, CONTACT_AREAS, labelOf } from '$lib/components/crm/format';
|
||||
import { DOC_TYPES, labelOf } from '$lib/components/crm/format';
|
||||
import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { uploadFile, uploadUrl } from '$lib/api/uploads';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
onMount(() => {
|
||||
void crmCatalogs.preload(['tipo_domicilio', 'area', 'pais']);
|
||||
});
|
||||
|
||||
// Dueño de los registros relacionados y qué sección mostrar
|
||||
let {
|
||||
ownerType,
|
||||
@@ -31,7 +37,7 @@
|
||||
let activeModal = $state<'address' | 'contact' | 'document' | null>(null);
|
||||
let saving = $state(false);
|
||||
|
||||
let addressForm = $state<AddressInput>({ address_type: 'fiscal', country: 'MX', is_primary: false });
|
||||
let addressForm = $state<AddressInput>({ address_type: 'fiscal', country: 'MEX', is_primary: false });
|
||||
let contactForm = $state<ContactInput>({ first_name: '' });
|
||||
let documentForm = $state<DocumentInput>({ doc_type: 'constancia_fiscal', name: '' });
|
||||
let uploading = $state(false);
|
||||
@@ -70,6 +76,11 @@
|
||||
if (companyId && ownerId) void load(companyId);
|
||||
});
|
||||
|
||||
// Estado depende del país seleccionado (catálogo dependiente)
|
||||
$effect(() => {
|
||||
if (addressForm.country) void crmCatalogs.ensure('estado', addressForm.country);
|
||||
});
|
||||
|
||||
async function load(cid: number) {
|
||||
try {
|
||||
[addresses, contacts, documents] = await Promise.all([
|
||||
@@ -83,7 +94,7 @@
|
||||
}
|
||||
|
||||
function openModal(kind: 'address' | 'contact' | 'document') {
|
||||
if (kind === 'address') addressForm = { address_type: 'fiscal', country: 'MX', is_primary: false };
|
||||
if (kind === 'address') addressForm = { address_type: 'fiscal', country: 'MEX', is_primary: false };
|
||||
if (kind === 'contact') contactForm = { first_name: '' };
|
||||
if (kind === 'document') documentForm = { doc_type: 'constancia_fiscal', name: '' };
|
||||
activeModal = kind;
|
||||
@@ -174,7 +185,7 @@
|
||||
<Table.Body>
|
||||
{#each addresses as a (a.id)}
|
||||
<Table.Row>
|
||||
<Table.Cell>{labelOf(ADDRESS_TYPES, a.address_type)}{#if a.is_primary}<span class="ml-1 text-[10px] text-primary">(principal)</span>{/if}</Table.Cell>
|
||||
<Table.Cell>{crmCatalogs.label('tipo_domicilio', a.address_type)}{#if a.is_primary}<span class="ml-1 text-[10px] text-primary">(principal)</span>{/if}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{[a.street, a.ext_number, a.neighborhood].filter(Boolean).join(' ') || '—'}</Table.Cell>
|
||||
<Table.Cell>{a.postal_code ?? '—'}</Table.Cell>
|
||||
<Table.Cell>{[a.city, a.state].filter(Boolean).join(', ') || '—'}</Table.Cell>
|
||||
@@ -204,7 +215,7 @@
|
||||
{#each contacts as c (c.id)}
|
||||
<Table.Row>
|
||||
<Table.Cell class="font-medium">{c.first_name} {c.last_name ?? ''}{#if c.is_primary}<span class="ml-1 text-[10px] text-primary">(principal)</span>{/if}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{[c.job_title, labelOf(CONTACT_AREAS, c.area) !== '—' ? labelOf(CONTACT_AREAS, c.area) : null].filter(Boolean).join(' · ') || '—'}</Table.Cell>
|
||||
<Table.Cell class="text-sm">{[c.job_title, c.area ? crmCatalogs.label('area', c.area) : null].filter(Boolean).join(' · ') || '—'}</Table.Cell>
|
||||
<Table.Cell>{c.email ?? '—'}</Table.Cell>
|
||||
<Table.Cell>{c.phone ?? c.mobile ?? '—'}</Table.Cell>
|
||||
<Table.Cell class="text-right"><Button variant="ghost" size="sm" onclick={() => removeContact(c)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button></Table.Cell>
|
||||
@@ -252,15 +263,15 @@
|
||||
{#if activeModal === 'address'}
|
||||
<h3 class="mb-4 text-base font-semibold">Nueva dirección</h3>
|
||||
<form class="grid gap-3 sm:grid-cols-2" onsubmit={saveAddress}>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo</span><select class={inputCls} bind:value={addressForm.address_type}>{#each ADDRESS_TYPES as t (t.value)}<option value={t.value}>{t.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de domicilio</span><select class={inputCls} bind:value={addressForm.address_type}>{#each crmCatalogs.options('tipo_domicilio') as t (t.value)}<option value={t.value}>{t.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Código Postal</span><input class={inputCls} maxlength="10" bind:value={addressForm.postal_code} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Calle</span><input class={inputCls} bind:value={addressForm.street} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Núm. exterior</span><input class={inputCls} bind:value={addressForm.ext_number} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Núm. interior</span><input class={inputCls} bind:value={addressForm.int_number} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Colonia</span><input class={inputCls} bind:value={addressForm.neighborhood} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Municipio</span><input class={inputCls} bind:value={addressForm.city} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estado</span><input class={inputCls} bind:value={addressForm.state} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">País</span><input class={inputCls} maxlength="2" bind:value={addressForm.country} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Municipio / Ciudad</span><input class={inputCls} bind:value={addressForm.city} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estado</span>{#if crmCatalogs.options('estado', addressForm.country).length > 0}<select class={inputCls} bind:value={addressForm.state}><option value={undefined}>—</option>{#each crmCatalogs.options('estado', addressForm.country) as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select>{:else}<input class={inputCls} bind:value={addressForm.state} placeholder="Estado / provincia" />{/if}</label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">País</span><select class={inputCls} bind:value={addressForm.country}><option value={undefined}>—</option>{#each crmCatalogs.options('pais') as p (p.value)}<option value={p.value}>{p.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Referencias</span><textarea rows="2" class={inputCls} bind:value={addressForm.reference_notes}></textarea></label>
|
||||
<label class="flex items-center gap-2 text-sm sm:col-span-2"><input type="checkbox" class="h-4 w-4 rounded border" bind:checked={addressForm.is_primary} /><span>Domicilio principal</span></label>
|
||||
<div class="flex justify-end gap-2 sm:col-span-2"><Button type="button" variant="outline" onclick={() => (activeModal = null)}>Cancelar</Button><Button type="submit" disabled={saving}>Guardar</Button></div>
|
||||
@@ -271,7 +282,7 @@
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Nombre *</span><input class={inputCls} bind:value={contactForm.first_name} required /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Apellidos</span><input class={inputCls} bind:value={contactForm.last_name} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Puesto</span><input class={inputCls} bind:value={contactForm.job_title} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Área</span><select class={inputCls} bind:value={contactForm.area}><option value={undefined}>—</option>{#each CONTACT_AREAS as a (a.value)}<option value={a.value}>{a.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Área / Departamento</span><select class={inputCls} bind:value={contactForm.area}><option value={undefined}>—</option>{#each crmCatalogs.options('area') as a (a.value)}<option value={a.value}>{a.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Email</span><input type="email" class={inputCls} bind:value={contactForm.email} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Teléfono</span><input class={inputCls} bind:value={contactForm.phone} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Extensión</span><input class={inputCls} bind:value={contactForm.extension} /></label>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import type { SupplierInput } from '$lib/api/crm';
|
||||
import { SUPPLIER_CLASSIFICATIONS, COVERAGE, ACCOUNT_STATUS, PERSON_TYPES } from '$lib/components/crm/format';
|
||||
import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
|
||||
|
||||
// listas separadas por coma también son bindables (el padre las convierte a arreglo)
|
||||
let {
|
||||
@@ -21,6 +22,15 @@
|
||||
|
||||
const inputCls =
|
||||
'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
const hasOtro = $derived((form.classifications ?? []).includes('otro'));
|
||||
|
||||
onMount(() => {
|
||||
void crmCatalogs.preload([
|
||||
'tipo_persona', 'estatus', 'clasificacion_proveedor', 'cobertura', 'moneda',
|
||||
'regimen_fiscal', 'metodo_pago', 'forma_pago'
|
||||
]);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if tab === 'generales'}
|
||||
@@ -28,25 +38,28 @@
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Razón social *</span><input class={inputCls} bind:value={form.name} required /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Nombre comercial</span><input class={inputCls} bind:value={form.trade_name} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">RFC</span><input class="font-mono {inputCls}" maxlength="13" bind:value={form.rfc} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de persona</span><select class={inputCls} bind:value={form.person_type}><option value={undefined}>—</option>{#each PERSON_TYPES as p (p.value)}<option value={p.value}>{p.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={form.status}>{#each ACCOUNT_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de persona</span><select class={inputCls} bind:value={form.person_type}><option value={undefined}>—</option>{#each crmCatalogs.options('tipo_persona') as p (p.value)}<option value={p.value}>{p.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={form.status}>{#each crmCatalogs.options('estatus') as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
|
||||
</div>
|
||||
<div class="mt-4">
|
||||
<p class="mb-2 text-sm font-medium">Clasificación (una o varias)</p>
|
||||
<p class="mb-2 text-sm font-medium">Clasificación del proveedor (una o varias)</p>
|
||||
<div class="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||
{#each SUPPLIER_CLASSIFICATIONS as c (c.value)}
|
||||
{#each crmCatalogs.options('clasificacion_proveedor') as c (c.value)}
|
||||
<label class="flex items-center gap-2 text-sm"><input type="checkbox" class="h-4 w-4 rounded border" value={c.value} bind:group={form.classifications} /><span>{c.label}</span></label>
|
||||
{/each}
|
||||
</div>
|
||||
{#if hasOtro}
|
||||
<label class="mt-3 flex max-w-md flex-col gap-1 text-sm"><span class="font-medium">Especifica la clasificación "Otro"</span><input class={inputCls} bind:value={form.classification_other} placeholder="Indica cuál" /></label>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if tab === 'comercial'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cobertura</span><select class={inputCls} bind:value={form.coverage}><option value={undefined}>—</option>{#each COVERAGE as c (c.value)}<option value={c.value}>{c.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda de cotización</span><input class={inputCls} maxlength="3" bind:value={form.quote_currency} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Países (separados por coma)</span><input class={inputCls} bind:value={countriesStr} placeholder="MX, US, PA" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Puertos</span><input class={inputCls} bind:value={portsStr} placeholder="Veracruz, Manzanillo" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Aeropuertos</span><input class={inputCls} bind:value={airportsStr} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Aduanas</span><input class={inputCls} bind:value={customsStr} placeholder="Nuevo Laredo, Colombia" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cobertura</span><select class={inputCls} bind:value={form.coverage}><option value={undefined}>—</option>{#each crmCatalogs.options('cobertura') as c (c.value)}<option value={c.value}>{c.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda de cotización</span><select class={inputCls} bind:value={form.quote_currency}><option value={undefined}>—</option>{#each crmCatalogs.options('moneda') as m (m.value)}<option value={m.value}>{m.value} — {m.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Países donde opera (separados por coma)</span><input class={inputCls} bind:value={countriesStr} placeholder="México, Estados Unidos" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Puertos donde opera</span><input class={inputCls} bind:value={portsStr} placeholder="Veracruz, Manzanillo" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Aeropuertos donde opera</span><input class={inputCls} bind:value={airportsStr} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Aduanas donde opera</span><input class={inputCls} bind:value={customsStr} placeholder="Nuevo Laredo, Colombia" /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Horario de atención</span><input class={inputCls} bind:value={form.business_hours} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tiempo prom. de respuesta</span><input class={inputCls} bind:value={form.avg_response_time} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Email</span><input type="email" class={inputCls} bind:value={form.email} /></label>
|
||||
@@ -56,16 +69,16 @@
|
||||
</div>
|
||||
{:else if tab === 'fiscal'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Régimen fiscal</span><input class={inputCls} bind:value={form.tax_regime} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Método de pago</span><input class={inputCls} bind:value={form.payment_method} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Forma de pago</span><input class={inputCls} bind:value={form.payment_form} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Régimen fiscal</span><select class={inputCls} bind:value={form.tax_regime}><option value={undefined}>—</option>{#each crmCatalogs.options('regimen_fiscal') as r (r.value)}<option value={r.value}>{r.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Método de pago</span><select class={inputCls} bind:value={form.payment_method}><option value={undefined}>—</option>{#each crmCatalogs.options('metodo_pago') as m (m.value)}<option value={m.value}>{m.value} — {m.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Forma de pago</span><select class={inputCls} bind:value={form.payment_form}><option value={undefined}>—</option>{#each crmCatalogs.options('forma_pago') as f (f.value)}<option value={f.value}>{f.value} — {f.label}</option>{/each}</select></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Límite de crédito</span><input type="number" min="0" step="0.01" class={inputCls} bind:value={form.credit_limit} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Días de crédito</span><input type="number" min="0" class={inputCls} bind:value={form.credit_days} /></label>
|
||||
<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Condiciones comerciales</span><textarea rows="3" class={inputCls} bind:value={form.commercial_terms}></textarea></label>
|
||||
</div>
|
||||
{:else if tab === 'observaciones'}
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Comentarios</span><textarea rows="4" class={inputCls} bind:value={form.notes}></textarea></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Comentarios generales</span><textarea rows="4" class={inputCls} bind:value={form.notes}></textarea></label>
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Notas internas</span><textarea rows="4" class={inputCls} bind:value={form.internal_notes}></textarea></label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -43,7 +43,7 @@ export const ACCOUNT_STATUS: Option[] = [
|
||||
export const COMMERCIAL_CLASSIFICATION: Option[] = [
|
||||
{ value: 'importador', label: 'Importador' },
|
||||
{ value: 'exportador', label: 'Exportador' },
|
||||
{ value: 'ambos', label: 'Importador / Exportador' }
|
||||
{ value: 'importador_exportador', label: 'Importador / Exportador' }
|
||||
];
|
||||
|
||||
export const ACCOUNT_TYPES: Option[] = [
|
||||
@@ -58,7 +58,7 @@ export const ACCOUNT_TYPES: Option[] = [
|
||||
export const CONTACT_METHODS: Option[] = [
|
||||
{ value: 'llamada', label: 'Llamada telefónica' },
|
||||
{ value: 'correo', label: 'Correo electrónico' },
|
||||
{ value: 'videollamada', label: 'Videoconferencia' },
|
||||
{ value: 'videoconferencia', label: 'Videoconferencia' },
|
||||
{ value: 'whatsapp', label: 'WhatsApp' },
|
||||
{ value: 'otro', label: 'Otro' }
|
||||
];
|
||||
|
||||
@@ -52,6 +52,7 @@ export function getNavMain(): NavMainItem[] {
|
||||
{ title: 'Prospectos (embudo)', url: '/dashboard/crm/prospectos' },
|
||||
{ title: 'Oportunidades', url: '/dashboard/crm/oportunidades' },
|
||||
{ title: 'Actividades', url: '/dashboard/crm/actividades' },
|
||||
{ title: 'Catálogos', url: '/dashboard/crm/catalogos' },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
77
frontend/src/lib/stores/crm-catalogs.svelte.ts
Normal file
77
frontend/src/lib/stores/crm-catalogs.svelte.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Store reactivo de catálogos de referencia del CRM.
|
||||
*
|
||||
* Carga desde el backend (/v1/crm/catalogs) y cachea por catálogo. Los
|
||||
* formularios leen `options(catalog)` (reactivo) sin refetch. Los catálogos
|
||||
* dependientes (Estado por País) se piden con `ensure(catalog, parentCode)`.
|
||||
*/
|
||||
import { referenceCatalogsAPI } from '$lib/api/crm/catalogs';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import type { Option } from '$lib/components/crm/format';
|
||||
|
||||
class CrmCatalogStore {
|
||||
private _cache = $state<Record<string, Option[]>>({});
|
||||
private _pending = new Set<string>();
|
||||
private _companyId: number | null = null;
|
||||
|
||||
/** Toma la compañía activa; si cambió, limpia el caché. Devuelve su id (o null). */
|
||||
private syncCompany(): number | null {
|
||||
const cid = companyStore.activeCompany?.id ?? null;
|
||||
if (cid !== this._companyId) {
|
||||
this._companyId = cid;
|
||||
this._cache = {};
|
||||
this._pending.clear();
|
||||
}
|
||||
return cid;
|
||||
}
|
||||
|
||||
private keyOf(catalog: string, parentCode?: string): string {
|
||||
return parentCode ? `${catalog}:${parentCode}` : catalog;
|
||||
}
|
||||
|
||||
/** Opciones de un catálogo ya cargado (vacío si aún no se ha cargado). */
|
||||
options(catalog: string, parentCode?: string): Option[] {
|
||||
return this._cache[this.keyOf(catalog, parentCode)] ?? [];
|
||||
}
|
||||
|
||||
/** Descripción de una clave (para listados/detalle). */
|
||||
label(catalog: string, code: string | null | undefined): string {
|
||||
if (!code) return '—';
|
||||
return this.options(catalog).find((o) => o.value === code)?.label ?? code;
|
||||
}
|
||||
|
||||
/** Carga un catálogo (con dependiente opcional) si aún no está en caché. */
|
||||
async ensure(catalog: string, parentCode?: string): Promise<void> {
|
||||
const cid = this.syncCompany();
|
||||
const key = this.keyOf(catalog, parentCode);
|
||||
if (cid == null || key in this._cache || this._pending.has(key)) return;
|
||||
this._pending.add(key);
|
||||
try {
|
||||
const items = await referenceCatalogsAPI.list(catalog, cid, parentCode);
|
||||
this._cache[key] = items.map((i) => ({ value: i.code, label: i.label }));
|
||||
} catch {
|
||||
this._cache[key] = [];
|
||||
} finally {
|
||||
this._pending.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Precarga varios catálogos globales en paralelo. */
|
||||
async preload(catalogs: string[]): Promise<void> {
|
||||
await Promise.all(catalogs.map((c) => this.ensure(c)));
|
||||
}
|
||||
|
||||
/** Invalida el caché de un catálogo (tras editar en administración). */
|
||||
invalidate(catalog?: string): void {
|
||||
if (!catalog) {
|
||||
this._cache = {};
|
||||
return;
|
||||
}
|
||||
for (const k of Object.keys(this._cache)) {
|
||||
if (k === catalog || k.startsWith(`${catalog}:`)) delete this._cache[k];
|
||||
}
|
||||
this._cache = { ...this._cache };
|
||||
}
|
||||
}
|
||||
|
||||
export const crmCatalogs = new CrmCatalogStore();
|
||||
217
frontend/src/routes/dashboard/crm/catalogos/+page.svelte
Normal file
217
frontend/src/routes/dashboard/crm/catalogos/+page.svelte
Normal file
@@ -0,0 +1,217 @@
|
||||
<script lang="ts">
|
||||
import { Database, Plus, Trash2, Pencil, Check, X, Lock } from '@lucide/svelte';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import * as Table from '$lib/components/ui/table';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { referenceCatalogsAPI, type CatalogItem, type CatalogMeta } from '$lib/api/crm/catalogs';
|
||||
import { crmCatalogs } from '$lib/stores/crm-catalogs.svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
const companyId = $derived(companyStore.activeCompany?.id ?? null);
|
||||
|
||||
let metas = $state<CatalogMeta[]>([]);
|
||||
let selected = $state<CatalogMeta | null>(null);
|
||||
let items = $state<CatalogItem[]>([]);
|
||||
let loading = $state(false);
|
||||
|
||||
let newCode = $state('');
|
||||
let newLabel = $state('');
|
||||
let adding = $state(false);
|
||||
let editId = $state<number | null>(null);
|
||||
let editLabel = $state('');
|
||||
let editActive = $state(true);
|
||||
|
||||
const inputCls =
|
||||
'rounded-md border bg-transparent px-2 py-1 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
$effect(() => {
|
||||
const cid = companyId;
|
||||
if (cid) void loadMetas(cid);
|
||||
});
|
||||
|
||||
async function loadMetas(cid: number) {
|
||||
try {
|
||||
metas = await referenceCatalogsAPI.meta(cid);
|
||||
if (!selected && metas.length) void selectCatalog(metas[0]);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'No se pudieron cargar los catálogos');
|
||||
}
|
||||
}
|
||||
|
||||
async function selectCatalog(m: CatalogMeta) {
|
||||
selected = m;
|
||||
editId = null;
|
||||
newCode = '';
|
||||
newLabel = '';
|
||||
if (!companyId) return;
|
||||
loading = true;
|
||||
try {
|
||||
items = await referenceCatalogsAPI.listAll(m.catalog, companyId);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'No se pudieron cargar las opciones');
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function addItem() {
|
||||
if (!companyId || !selected) return;
|
||||
const code = newCode.trim();
|
||||
const label = newLabel.trim();
|
||||
if (!code || !label) {
|
||||
toast.error('Clave y descripción son obligatorias');
|
||||
return;
|
||||
}
|
||||
adding = true;
|
||||
try {
|
||||
const res = await referenceCatalogsAPI.create(
|
||||
selected.catalog,
|
||||
companyId,
|
||||
{ code, label },
|
||||
selected.scope
|
||||
);
|
||||
if (res.error) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.success('Opción agregada');
|
||||
newCode = '';
|
||||
newLabel = '';
|
||||
crmCatalogs.invalidate(selected.catalog);
|
||||
await selectCatalog(selected);
|
||||
} finally {
|
||||
adding = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(it: CatalogItem) {
|
||||
editId = it.id;
|
||||
editLabel = it.label;
|
||||
editActive = it.is_active;
|
||||
}
|
||||
|
||||
async function saveEdit(it: CatalogItem) {
|
||||
if (!companyId || !selected) return;
|
||||
const res = await referenceCatalogsAPI.update(selected.catalog, it.id, companyId, {
|
||||
label: editLabel.trim() || it.label,
|
||||
is_active: editActive
|
||||
});
|
||||
if (res.error) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.success('Opción actualizada');
|
||||
editId = null;
|
||||
crmCatalogs.invalidate(selected.catalog);
|
||||
await selectCatalog(selected);
|
||||
}
|
||||
|
||||
async function del(it: CatalogItem) {
|
||||
if (!companyId || !selected) return;
|
||||
if (!confirm(`¿Eliminar la opción "${it.label}"?`)) return;
|
||||
const res = await referenceCatalogsAPI.remove(selected.catalog, it.id, companyId);
|
||||
if (res.error) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.success('Opción eliminada');
|
||||
crmCatalogs.invalidate(selected.catalog);
|
||||
await selectCatalog(selected);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div>
|
||||
<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Database class="h-6 w-6" /> Catálogos</h1>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
Administra las opciones de los catálogos del CRM. Los catálogos base del sistema (SAT/ISO) solo se pueden activar/desactivar; los de tu empresa se pueden insertar, editar y borrar.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if !companyId}
|
||||
<Card.Root><Card.Content class="pt-6 text-sm text-muted-foreground">Selecciona una compañía activa.</Card.Content></Card.Root>
|
||||
{:else}
|
||||
<div class="grid gap-6 lg:grid-cols-[260px_1fr]">
|
||||
<Card.Root>
|
||||
<Card.Header><Card.Title class="text-base">Catálogos</Card.Title></Card.Header>
|
||||
<Card.Content class="space-y-1">
|
||||
{#each metas as m (m.catalog)}
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-sm {selected?.catalog === m.catalog ? 'bg-primary/10 text-primary' : 'hover:bg-muted'}"
|
||||
onclick={() => selectCatalog(m)}
|
||||
>
|
||||
<span class="flex items-center gap-1">{#if m.is_system}<Lock class="h-3 w-3 opacity-60" />{/if}{m.label}</span>
|
||||
<span class="text-xs text-muted-foreground">{m.count}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="text-base">{selected?.label ?? 'Opciones'}</Card.Title>
|
||||
<Card.Description>
|
||||
{#if selected}
|
||||
{selected.scope === 'global' ? 'Catálogo global (Aduanasoft)' : 'Catálogo de tu empresa'} · {selected.count} opciones
|
||||
{#if selected.is_system} · base del sistema (no se borra){/if}
|
||||
{/if}
|
||||
</Card.Description>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<div class="mb-4 flex flex-wrap items-end gap-2">
|
||||
<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Clave</span><input class="font-mono {inputCls}" bind:value={newCode} placeholder="clave" /></label>
|
||||
<label class="flex flex-1 flex-col gap-1 text-sm"><span class="font-medium">Descripción</span><input class={inputCls} bind:value={newLabel} placeholder="Descripción visible" /></label>
|
||||
<Button size="sm" onclick={addItem} disabled={adding}><Plus class="mr-1 h-4 w-4" /> Agregar</Button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<p class="py-6 text-center text-sm text-muted-foreground">Cargando…</p>
|
||||
{:else if items.length === 0}
|
||||
<p class="py-6 text-center text-sm text-muted-foreground">Sin opciones. Agrega la primera arriba.</p>
|
||||
{:else}
|
||||
<div class="overflow-x-auto">
|
||||
<Table.Root>
|
||||
<Table.Header><Table.Row><Table.Head>Clave</Table.Head><Table.Head>Descripción</Table.Head><Table.Head>Origen</Table.Head><Table.Head>Activo</Table.Head><Table.Head class="text-right">Acciones</Table.Head></Table.Row></Table.Header>
|
||||
<Table.Body>
|
||||
{#each items as it (it.id)}
|
||||
<Table.Row>
|
||||
<Table.Cell class="font-mono text-xs">{it.code}</Table.Cell>
|
||||
<Table.Cell>
|
||||
{#if editId === it.id}
|
||||
<input class="{inputCls} w-full" bind:value={editLabel} />
|
||||
{:else}
|
||||
{it.label}
|
||||
{/if}
|
||||
</Table.Cell>
|
||||
<Table.Cell class="text-xs text-muted-foreground">{it.tenant_id === null ? 'Global' : 'Empresa'}{#if it.is_system} · base{/if}</Table.Cell>
|
||||
<Table.Cell>
|
||||
{#if editId === it.id}
|
||||
<input type="checkbox" class="h-4 w-4 rounded border" bind:checked={editActive} />
|
||||
{:else}
|
||||
<span class="inline-flex rounded-full px-2 py-0.5 text-xs {it.is_active ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400' : 'bg-muted text-muted-foreground'}">{it.is_active ? 'Sí' : 'No'}</span>
|
||||
{/if}
|
||||
</Table.Cell>
|
||||
<Table.Cell class="text-right">
|
||||
{#if editId === it.id}
|
||||
<Button variant="ghost" size="sm" onclick={() => saveEdit(it)} aria-label="Guardar"><Check class="h-4 w-4 text-emerald-600" /></Button>
|
||||
<Button variant="ghost" size="sm" onclick={() => (editId = null)} aria-label="Cancelar"><X class="h-4 w-4" /></Button>
|
||||
{:else}
|
||||
<Button variant="ghost" size="sm" onclick={() => startEdit(it)} aria-label="Editar"><Pencil class="h-4 w-4" /></Button>
|
||||
{#if !it.is_system}
|
||||
<Button variant="ghost" size="sm" onclick={() => del(it)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button>
|
||||
{/if}
|
||||
{/if}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
{/each}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
</div>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { Building2, Plus, Trash2, Search, ChevronRight } from '@lucide/svelte';
|
||||
import { Building2, Plus, Trash2, Search, Pencil } from '@lucide/svelte';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import * as Table from '$lib/components/ui/table';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
@@ -120,8 +120,8 @@
|
||||
<Table.Cell>{labelOf(COMMERCIAL_CLASSIFICATION, a.commercial_classification)}</Table.Cell>
|
||||
<Table.Cell>{labelOf(ACCOUNT_STATUS, a.status)}</Table.Cell>
|
||||
<Table.Cell class="text-right">
|
||||
<Button variant="ghost" size="sm" href={`/dashboard/crm/cuentas/${a.id}`} aria-label="Abrir">
|
||||
<ChevronRight class="h-4 w-4" />
|
||||
<Button variant="ghost" size="sm" href={`/dashboard/crm/cuentas/${a.id}`}>
|
||||
<Pencil class="mr-1 h-4 w-4" /> Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={() => remove(a)} aria-label="Eliminar">
|
||||
<Trash2 class="h-4 w-4 text-destructive" />
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import RelatedManager from '$lib/components/crm/RelatedManager.svelte';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { accountsAPI, type Account, type AccountInput } from '$lib/api/crm';
|
||||
import { RECORD_TYPES, ACCOUNT_STATUS, labelOf } from '$lib/components/crm/format';
|
||||
import { RECORD_TYPES, ACCOUNT_STATUS, labelOf, formatDate } from '$lib/components/crm/format';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
type TabDef = { id: string; label: string; kind: 'info' | 'related'; section?: 'addresses' | 'contacts' | 'documents' };
|
||||
@@ -86,6 +86,10 @@
|
||||
{labelOf(RECORD_TYPES, account.record_type)} · {labelOf(ACCOUNT_STATUS, account.status)}
|
||||
{#if account.rfc}· <span class="font-mono">{account.rfc}</span>{/if}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
ID #{account.id} · Creado {formatDate(account.created_at)}{#if account.created_by} por <span class="font-mono">{account.created_by}</span>{/if}
|
||||
· Últ. actualización {formatDate(account.updated_at)}{#if account.updated_by} por <span class="font-mono">{account.updated_by}</span>{/if}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { Truck, Plus, Trash2, Search, ChevronRight } from '@lucide/svelte';
|
||||
import { Truck, Plus, Trash2, Search, Pencil } from '@lucide/svelte';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import * as Table from '$lib/components/ui/table';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
@@ -106,8 +106,8 @@
|
||||
<Table.Cell>{labelOf(COVERAGE, s.coverage)}</Table.Cell>
|
||||
<Table.Cell class="font-mono text-xs">{s.rfc ?? '—'}</Table.Cell>
|
||||
<Table.Cell class="text-right">
|
||||
<Button variant="ghost" size="sm" href={`/dashboard/crm/proveedores/${s.id}`} aria-label="Abrir">
|
||||
<ChevronRight class="h-4 w-4" />
|
||||
<Button variant="ghost" size="sm" href={`/dashboard/crm/proveedores/${s.id}`}>
|
||||
<Pencil class="mr-1 h-4 w-4" /> Editar
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={() => remove(s)} aria-label="Eliminar">
|
||||
<Trash2 class="h-4 w-4 text-destructive" />
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import RelatedManager from '$lib/components/crm/RelatedManager.svelte';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
import { suppliersAPI, type Supplier, type SupplierInput } from '$lib/api/crm';
|
||||
import { COVERAGE, ACCOUNT_STATUS, labelOf } from '$lib/components/crm/format';
|
||||
import { COVERAGE, ACCOUNT_STATUS, labelOf, formatDate } from '$lib/components/crm/format';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
type TabDef = { id: string; label: string; kind: 'info' | 'related'; section?: 'addresses' | 'contacts' | 'documents' };
|
||||
@@ -104,7 +104,7 @@
|
||||
</h1>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
{labelOf(COVERAGE, supplier.coverage)} · {labelOf(ACCOUNT_STATUS, supplier.status)}
|
||||
{#if supplier.rfc}· <span class="font-mono">{supplier.rfc}</span>{/if}
|
||||
{#if supplier.rfc}· <span class="font-mono">{supplier.rfc}</span>{/if}<br /><span class="text-xs">ID #{supplier.id} · Alta {formatDate(supplier.created_at)}{#if supplier.created_by} por <span class="font-mono">{supplier.created_by}</span>{/if} · Últ. modificación {formatDate(supplier.updated_at)}{#if supplier.updated_by} por <span class="font-mono">{supplier.updated_by}</span>{/if}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user