Update: nueva version Horux Despachos
This commit is contained in:
26
packages/core/package.json
Normal file
26
packages/core/package.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@horux/core",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint src/",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@horux/shared": "workspace:*",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"nodemailer": "^8.0.0",
|
||||
"express": "^4.21.0",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/nodemailer": "^6.4.17",
|
||||
"@types/express": "^5.0.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
2
packages/core/src/auth/index.ts
Normal file
2
packages/core/src/auth/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './token';
|
||||
export * from './password';
|
||||
11
packages/core/src/auth/password.ts
Normal file
11
packages/core/src/auth/password.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const SALT_ROUNDS = 12;
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, SALT_ROUNDS);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
37
packages/core/src/auth/token.ts
Normal file
37
packages/core/src/auth/token.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import jwt, { type SignOptions } from 'jsonwebtoken';
|
||||
import { randomBytes } from 'crypto';
|
||||
import type { JWTPayload } from '@horux/shared';
|
||||
|
||||
export interface TokenConfig {
|
||||
secret: string;
|
||||
accessExpiresIn: string;
|
||||
refreshExpiresIn: string;
|
||||
}
|
||||
|
||||
export function generateAccessToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, config: TokenConfig): string {
|
||||
const options: SignOptions = {
|
||||
expiresIn: config.accessExpiresIn as SignOptions['expiresIn'],
|
||||
jwtid: randomBytes(8).toString('hex'),
|
||||
};
|
||||
return jwt.sign(payload, config.secret, options);
|
||||
}
|
||||
|
||||
export function generateRefreshToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, config: TokenConfig): string {
|
||||
const options: SignOptions = {
|
||||
expiresIn: config.refreshExpiresIn as SignOptions['expiresIn'],
|
||||
jwtid: randomBytes(8).toString('hex'),
|
||||
};
|
||||
return jwt.sign(payload, config.secret, options);
|
||||
}
|
||||
|
||||
export function verifyToken(token: string, secret: string): JWTPayload {
|
||||
return jwt.verify(token, secret) as JWTPayload;
|
||||
}
|
||||
|
||||
export function decodeToken(token: string): JWTPayload | null {
|
||||
try {
|
||||
return jwt.decode(token) as JWTPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
30
packages/core/src/crypto/aes-gcm.ts
Normal file
30
packages/core/src/crypto/aes-gcm.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes, createHash } from 'crypto';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const IV_LENGTH = 16;
|
||||
|
||||
export function deriveAesKey(secret: string): Buffer {
|
||||
return createHash('sha256').update(secret).digest();
|
||||
}
|
||||
|
||||
export function encryptAesGcm(data: Buffer, key: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
|
||||
const iv = randomBytes(IV_LENGTH);
|
||||
const cipher = createCipheriv(ALGORITHM, key, iv);
|
||||
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return { encrypted, iv, tag };
|
||||
}
|
||||
|
||||
export function decryptAesGcm(encrypted: Buffer, iv: Buffer, tag: Buffer, key: Buffer): Buffer {
|
||||
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||
}
|
||||
|
||||
export function encryptStringAesGcm(text: string, key: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
|
||||
return encryptAesGcm(Buffer.from(text, 'utf-8'), key);
|
||||
}
|
||||
|
||||
export function decryptToStringAesGcm(encrypted: Buffer, iv: Buffer, tag: Buffer, key: Buffer): string {
|
||||
return decryptAesGcm(encrypted, iv, tag, key).toString('utf-8');
|
||||
}
|
||||
1
packages/core/src/crypto/index.ts
Normal file
1
packages/core/src/crypto/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './aes-gcm';
|
||||
1
packages/core/src/email/index.ts
Normal file
1
packages/core/src/email/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './transport';
|
||||
60
packages/core/src/email/transport.ts
Normal file
60
packages/core/src/email/transport.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { createTransport, type Transporter } from 'nodemailer';
|
||||
|
||||
export interface SmtpConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
pass: string;
|
||||
from: string;
|
||||
}
|
||||
|
||||
export interface EmailTransport {
|
||||
send(to: string, subject: string, html: string): Promise<void>;
|
||||
}
|
||||
|
||||
export function createEmailTransport(config: SmtpConfig | null): EmailTransport {
|
||||
let transporter: Transporter | null = null;
|
||||
|
||||
function getTransporter(): Transporter {
|
||||
if (!transporter) {
|
||||
if (!config || !config.user || !config.pass) {
|
||||
console.warn('[EMAIL] SMTP not configured. Emails will be logged to console.');
|
||||
return {
|
||||
sendMail: async (opts: any) => {
|
||||
console.log('[EMAIL] Would send:', { to: opts.to, subject: opts.subject });
|
||||
return { messageId: 'mock' };
|
||||
},
|
||||
} as any;
|
||||
}
|
||||
|
||||
transporter = createTransport({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: false,
|
||||
requireTLS: true,
|
||||
auth: {
|
||||
user: config.user,
|
||||
pass: config.pass,
|
||||
},
|
||||
});
|
||||
}
|
||||
return transporter;
|
||||
}
|
||||
|
||||
return {
|
||||
async send(to: string, subject: string, html: string) {
|
||||
const transport = getTransporter();
|
||||
try {
|
||||
await transport.sendMail({
|
||||
from: config?.from ?? 'noreply@example.com',
|
||||
to,
|
||||
subject,
|
||||
html,
|
||||
text: html.replace(/<[^>]*>/g, ''),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[EMAIL] Error sending email:', error);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
3
packages/core/src/index.ts
Normal file
3
packages/core/src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './auth';
|
||||
export * from './email';
|
||||
export * from './crypto';
|
||||
17
packages/core/tsconfig.json
Normal file
17
packages/core/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
33
packages/shared-ui/package.json
Normal file
33
packages/shared-ui/package.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@horux/shared-ui",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint src/",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@horux/shared": "workspace:*",
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-label": "^2.1.0",
|
||||
"@radix-ui/react-popover": "^1.1.2",
|
||||
"@radix-ui/react-select": "^2.1.2",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-tabs": "^1.1.1",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.453.0",
|
||||
"react": "^18.3.1",
|
||||
"recharts": "^2.12.7",
|
||||
"tailwind-merge": "^2.5.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
1
packages/shared-ui/src/charts/index.ts
Normal file
1
packages/shared-ui/src/charts/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './kpi-card';
|
||||
78
packages/shared-ui/src/charts/kpi-card.tsx
Normal file
78
packages/shared-ui/src/charts/kpi-card.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Card, CardContent } from '../primitives';
|
||||
import { cn } from '../lib/cn';
|
||||
import { TrendingUp, TrendingDown, Minus } from 'lucide-react';
|
||||
|
||||
interface KpiCardProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
subtitle?: string;
|
||||
trend?: 'up' | 'down' | 'neutral';
|
||||
trendValue?: string;
|
||||
icon?: React.ReactNode;
|
||||
className?: string;
|
||||
href?: string;
|
||||
}
|
||||
|
||||
export function KpiCard({
|
||||
title,
|
||||
value,
|
||||
subtitle,
|
||||
trend,
|
||||
trendValue,
|
||||
icon,
|
||||
className,
|
||||
href,
|
||||
}: KpiCardProps) {
|
||||
const formatValue = (val: string | number) => {
|
||||
if (typeof val === 'number') {
|
||||
return new Intl.NumberFormat('es-MX', {
|
||||
style: 'currency',
|
||||
currency: 'MXN',
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0,
|
||||
}).format(val);
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
const Wrapper = href ? 'a' : 'div';
|
||||
const wrapperProps = href ? { href, className: 'block' } : {};
|
||||
|
||||
return (
|
||||
<Card className={cn(href && 'hover:border-primary/50 hover:shadow-md transition-all cursor-pointer', className)}>
|
||||
<Wrapper {...wrapperProps}>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
||||
{icon && <div className="text-muted-foreground">{icon}</div>}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<p className="text-2xl font-bold">{formatValue(value)}</p>
|
||||
{(subtitle || trend) && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
{trend && (
|
||||
<span
|
||||
className={cn(
|
||||
'flex items-center text-xs font-medium',
|
||||
trend === 'up' && 'text-success',
|
||||
trend === 'down' && 'text-destructive',
|
||||
trend === 'neutral' && 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{trend === 'up' && <TrendingUp className="mr-1 h-3 w-3" />}
|
||||
{trend === 'down' && <TrendingDown className="mr-1 h-3 w-3" />}
|
||||
{trend === 'neutral' && <Minus className="mr-1 h-3 w-3" />}
|
||||
{trendValue}
|
||||
</span>
|
||||
)}
|
||||
{subtitle && (
|
||||
<span className="text-xs text-muted-foreground">{subtitle}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Wrapper>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
2
packages/shared-ui/src/form/index.ts
Normal file
2
packages/shared-ui/src/form/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './period-selector';
|
||||
export * from './regimen-selector';
|
||||
235
packages/shared-ui/src/form/period-selector.tsx
Normal file
235
packages/shared-ui/src/form/period-selector.tsx
Normal file
@@ -0,0 +1,235 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '../primitives';
|
||||
import { ChevronLeft, ChevronRight, Calendar } from 'lucide-react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const MESES = [
|
||||
'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun',
|
||||
'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'
|
||||
];
|
||||
|
||||
function getMonthRange(year: number, month: number) {
|
||||
const start = `${year}-${String(month).padStart(2, '0')}-01`;
|
||||
const lastDay = new Date(year, month, 0).getDate();
|
||||
const end = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function getRange(startYear: number, startMonth: number, endYear: number, endMonth: number) {
|
||||
const start = getMonthRange(startYear, startMonth).start;
|
||||
const end = getMonthRange(endYear, endMonth).end;
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function parseDate(dateStr: string) {
|
||||
const d = new Date(dateStr + 'T00:00:00');
|
||||
return { year: d.getFullYear(), month: d.getMonth() + 1 };
|
||||
}
|
||||
|
||||
interface PeriodSelectorProps {
|
||||
fechaInicio: string;
|
||||
fechaFin: string;
|
||||
onChange: (fechaInicio: string, fechaFin: string) => void;
|
||||
}
|
||||
|
||||
export function PeriodSelector({ fechaInicio, fechaFin, onChange }: PeriodSelectorProps) {
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [pickerYear, setPickerYear] = useState(new Date().getFullYear());
|
||||
const [selecting, setSelecting] = useState<'idle' | 'from'>('idle');
|
||||
const [tempFrom, setTempFrom] = useState<{ year: number; month: number } | null>(null);
|
||||
|
||||
const startParsed = parseDate(fechaInicio);
|
||||
const endParsed = parseDate(fechaFin);
|
||||
const totalMonths = (endParsed.year - startParsed.year) * 12 + (endParsed.month - startParsed.month) + 1;
|
||||
|
||||
const handlePrev = () => {
|
||||
let sm = startParsed.month - totalMonths;
|
||||
let sy = startParsed.year;
|
||||
while (sm < 1) { sm += 12; sy--; }
|
||||
let em = endParsed.month - totalMonths;
|
||||
let ey = endParsed.year;
|
||||
while (em < 1) { em += 12; ey--; }
|
||||
const r = getRange(sy, sm, ey, em);
|
||||
onChange(r.start, r.end);
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
let sm = startParsed.month + totalMonths;
|
||||
let sy = startParsed.year;
|
||||
while (sm > 12) { sm -= 12; sy++; }
|
||||
let em = endParsed.month + totalMonths;
|
||||
let ey = endParsed.year;
|
||||
while (em > 12) { em -= 12; ey++; }
|
||||
const r = getRange(sy, sm, ey, em);
|
||||
onChange(r.start, r.end);
|
||||
};
|
||||
|
||||
const handleMonthClick = (month: number) => {
|
||||
if (selecting === 'idle') {
|
||||
// First click: set start month
|
||||
setTempFrom({ year: pickerYear, month });
|
||||
setSelecting('from');
|
||||
} else {
|
||||
// Second click: set end month, apply range
|
||||
let fy = tempFrom!.year;
|
||||
let fm = tempFrom!.month;
|
||||
let ty = pickerYear;
|
||||
let tm = month;
|
||||
|
||||
// Ensure from <= to
|
||||
if (ty < fy || (ty === fy && tm < fm)) {
|
||||
[fy, fm, ty, tm] = [ty, tm, fy, fm];
|
||||
}
|
||||
|
||||
const r = getRange(fy, fm, ty, tm);
|
||||
onChange(r.start, r.end);
|
||||
setSelecting('idle');
|
||||
setTempFrom(null);
|
||||
setPickerOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openPicker = () => {
|
||||
setPickerYear(startParsed.year);
|
||||
setSelecting('idle');
|
||||
setTempFrom(null);
|
||||
setPickerOpen(!pickerOpen);
|
||||
};
|
||||
|
||||
const isInRange = (month: number) => {
|
||||
const v = pickerYear * 12 + month;
|
||||
const sv = startParsed.year * 12 + startParsed.month;
|
||||
const ev = endParsed.year * 12 + endParsed.month;
|
||||
return v >= sv && v <= ev;
|
||||
};
|
||||
|
||||
const isStart = (month: number) =>
|
||||
pickerYear === startParsed.year && month === startParsed.month;
|
||||
|
||||
const isEnd = (month: number) =>
|
||||
pickerYear === endParsed.year && month === endParsed.month;
|
||||
|
||||
const isTempFrom = (month: number) =>
|
||||
selecting === 'from' && tempFrom?.year === pickerYear && tempFrom?.month === month;
|
||||
|
||||
const getDisplayText = () => {
|
||||
const sm = MESES[startParsed.month - 1];
|
||||
const em = MESES[endParsed.month - 1];
|
||||
if (startParsed.year === endParsed.year && startParsed.month === endParsed.month) {
|
||||
return `${sm} ${startParsed.year}`;
|
||||
}
|
||||
if (startParsed.year === endParsed.year) {
|
||||
return `${sm} – ${em} ${startParsed.year}`;
|
||||
}
|
||||
return `${sm} ${startParsed.year} – ${em} ${endParsed.year}`;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!target.closest('.period-selector-popup')) {
|
||||
setPickerOpen(false);
|
||||
setSelecting('idle');
|
||||
setTempFrom(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener('click', handler);
|
||||
return () => document.removeEventListener('click', handler);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="period-selector-popup relative flex items-center gap-1">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={handlePrev}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<button
|
||||
onClick={openPicker}
|
||||
className={cn(
|
||||
'flex items-center gap-2 text-sm font-medium px-3 py-1.5 rounded-md transition-colors whitespace-nowrap',
|
||||
pickerOpen ? 'bg-primary/10 text-primary' : 'hover:bg-accent'
|
||||
)}
|
||||
>
|
||||
<Calendar className="h-4 w-4 flex-shrink-0" />
|
||||
{getDisplayText()}
|
||||
</button>
|
||||
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleNext}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{pickerOpen && (
|
||||
<div className="absolute top-full left-0 mt-2 w-64 rounded-lg border bg-card shadow-lg z-50 p-4 space-y-3">
|
||||
{/* Year selector */}
|
||||
<div className="flex items-center justify-between">
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setPickerYear(pickerYear - 1)}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="text-sm font-semibold">{pickerYear}</span>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setPickerYear(pickerYear + 1)}>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Month grid */}
|
||||
<div className="grid grid-cols-4 gap-1">
|
||||
{MESES.map((m, i) => {
|
||||
const mo = i + 1;
|
||||
const tempSelected = isTempFrom(mo);
|
||||
|
||||
// When selecting (first click made), only show tempFrom — hide previous range
|
||||
const showRange = selecting === 'idle';
|
||||
const start = showRange && isStart(mo);
|
||||
const end = showRange && isEnd(mo);
|
||||
const inRange = showRange && isInRange(mo);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={m}
|
||||
onClick={() => handleMonthClick(mo)}
|
||||
className={cn(
|
||||
'text-xs py-2 px-2 rounded-md transition-colors',
|
||||
tempSelected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: start || end
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: inRange
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'hover:bg-accent'
|
||||
)}
|
||||
>
|
||||
{m}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Status + shortcut */}
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground pt-1 border-t">
|
||||
<span>
|
||||
{selecting === 'from'
|
||||
? `Desde: ${MESES[tempFrom!.month - 1]} ${tempFrom!.year} → elige fin`
|
||||
: 'Clic en mes inicio'}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-xs h-6"
|
||||
onClick={() => {
|
||||
const now = new Date();
|
||||
const r = getMonthRange(now.getFullYear(), now.getMonth() + 1);
|
||||
onChange(r.start, r.end);
|
||||
setPickerOpen(false);
|
||||
setSelecting('idle');
|
||||
}}
|
||||
>
|
||||
Hoy
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
packages/shared-ui/src/form/regimen-selector.tsx
Normal file
102
packages/shared-ui/src/form/regimen-selector.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ChevronDown, Check, Scale } from 'lucide-react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface RegimenOption {
|
||||
clave: string;
|
||||
descripcion: string;
|
||||
}
|
||||
|
||||
interface RegimenSelectorProps {
|
||||
regimenes: RegimenOption[];
|
||||
selected: string | null;
|
||||
onChange: (clave: string | null) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function RegimenSelector({ regimenes, selected, onChange, isLoading }: RegimenSelectorProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!target.closest('.regimen-selector')) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
return () => document.removeEventListener('click', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
if (isLoading || regimenes.length === 0) return null;
|
||||
|
||||
const selectedRegimen = selected ? regimenes.find(r => r.clave === selected) : null;
|
||||
const displayText = selectedRegimen
|
||||
? `${selectedRegimen.clave} - ${selectedRegimen.descripcion}`
|
||||
: 'Todos los regimenes';
|
||||
|
||||
return (
|
||||
<div className="regimen-selector relative">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
|
||||
selected
|
||||
? 'bg-primary/10 text-primary border border-primary/30'
|
||||
: 'hover:bg-accent'
|
||||
)}
|
||||
>
|
||||
<Scale className="h-4 w-4" />
|
||||
<span className="max-w-[200px] truncate">{displayText}</span>
|
||||
<ChevronDown className={cn('h-4 w-4 transition-transform', open && 'rotate-180')} />
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute top-full left-0 mt-2 w-80 rounded-lg border bg-card shadow-lg z-50">
|
||||
<div className="p-2 border-b">
|
||||
<p className="text-xs text-muted-foreground px-2">Regimen fiscal</p>
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto p-1">
|
||||
<button
|
||||
onClick={() => {
|
||||
onChange(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
|
||||
!selected && 'bg-primary/10'
|
||||
)}
|
||||
>
|
||||
<span className="flex-1 text-left font-medium">Todos los regimenes</span>
|
||||
{!selected && <Check className="h-4 w-4 text-primary" />}
|
||||
</button>
|
||||
|
||||
<div className="my-1 border-t" />
|
||||
|
||||
{regimenes.map((regimen) => (
|
||||
<button
|
||||
key={regimen.clave}
|
||||
onClick={() => {
|
||||
onChange(regimen.clave);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
|
||||
selected === regimen.clave && 'bg-primary/10'
|
||||
)}
|
||||
>
|
||||
<div className="h-7 w-7 rounded bg-muted flex items-center justify-center text-xs font-mono font-bold">
|
||||
{regimen.clave}
|
||||
</div>
|
||||
<span className="flex-1 text-left truncate">{regimen.descripcion}</span>
|
||||
{selected === regimen.clave && <Check className="h-4 w-4 text-primary" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2
packages/shared-ui/src/hooks/index.ts
Normal file
2
packages/shared-ui/src/hooks/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './use-debounce';
|
||||
export * from './use-table-sort';
|
||||
17
packages/shared-ui/src/hooks/use-debounce.ts
Normal file
17
packages/shared-ui/src/hooks/use-debounce.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
clearTimeout(handler);
|
||||
};
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
56
packages/shared-ui/src/hooks/use-table-sort.ts
Normal file
56
packages/shared-ui/src/hooks/use-table-sort.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
export type SortDir = 'asc' | 'desc';
|
||||
|
||||
/**
|
||||
* Ordenamiento client-side de una tabla.
|
||||
*
|
||||
* Uso:
|
||||
* const { sortedData, sortKey, sortDir, toggleSort, getSortIndicator } = useTableSort(
|
||||
* data,
|
||||
* {
|
||||
* fecha: (row) => new Date(row.fechaEmision).getTime(),
|
||||
* total: (row) => Number(row.totalMxn || 0),
|
||||
* },
|
||||
* 'fecha',
|
||||
* );
|
||||
*/
|
||||
export function useTableSort<T, K extends string>(
|
||||
data: T[] | undefined,
|
||||
accessors: Record<K, (row: T) => number | string>,
|
||||
initialKey: K,
|
||||
initialDir: SortDir = 'desc',
|
||||
) {
|
||||
const [sortKey, setSortKey] = useState<K>(initialKey);
|
||||
const [sortDir, setSortDir] = useState<SortDir>(initialDir);
|
||||
|
||||
const sortedData = useMemo(() => {
|
||||
if (!data) return data;
|
||||
const accessor = accessors[sortKey];
|
||||
const sign = sortDir === 'asc' ? 1 : -1;
|
||||
return [...data].sort((a, b) => {
|
||||
const va = accessor(a);
|
||||
const vb = accessor(b);
|
||||
if (typeof va === 'number' && typeof vb === 'number') {
|
||||
return (va - vb) * sign;
|
||||
}
|
||||
return String(va).localeCompare(String(vb)) * sign;
|
||||
});
|
||||
}, [data, sortKey, sortDir, accessors]);
|
||||
|
||||
const toggleSort = (key: K) => {
|
||||
if (sortKey === key) {
|
||||
setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
setSortKey(key);
|
||||
setSortDir('desc');
|
||||
}
|
||||
};
|
||||
|
||||
/** Retorna 'asc' | 'desc' | null según el header sea activo o no */
|
||||
const getSortIndicator = (key: K): SortDir | null => (sortKey === key ? sortDir : null);
|
||||
|
||||
return { sortedData, sortKey, sortDir, toggleSort, getSortIndicator };
|
||||
}
|
||||
5
packages/shared-ui/src/index.ts
Normal file
5
packages/shared-ui/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './lib';
|
||||
export * from './primitives';
|
||||
export * from './form';
|
||||
export * from './hooks';
|
||||
export * from './charts';
|
||||
6
packages/shared-ui/src/lib/cn.ts
Normal file
6
packages/shared-ui/src/lib/cn.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
1
packages/shared-ui/src/lib/index.ts
Normal file
1
packages/shared-ui/src/lib/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './cn';
|
||||
53
packages/shared-ui/src/primitives/button.tsx
Normal file
53
packages/shared-ui/src/primitives/button.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
|
||||
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
|
||||
outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
success: 'bg-success text-success-foreground hover:bg-success/90',
|
||||
},
|
||||
size: {
|
||||
default: 'h-10 px-4 py-2',
|
||||
sm: 'h-9 rounded-md px-3',
|
||||
lg: 'h-11 rounded-md px-8',
|
||||
icon: 'h-10 w-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
78
packages/shared-ui/src/primitives/card.tsx
Normal file
78
packages/shared-ui/src/primitives/card.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Card = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'rounded-lg border bg-card text-card-foreground shadow-sm',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('flex flex-col space-y-1.5 p-6', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'text-2xl font-semibold leading-none tracking-tight',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
));
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('flex items-center p-6 pt-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
122
packages/shared-ui/src/primitives/dialog.tsx
Normal file
122
packages/shared-ui/src/primitives/dialog.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col space-y-1.5 text-center sm:text-left',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'text-lg font-semibold leading-none tracking-tight',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
9
packages/shared-ui/src/primitives/index.ts
Normal file
9
packages/shared-ui/src/primitives/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export * from './button';
|
||||
export * from './card';
|
||||
export * from './dialog';
|
||||
export * from './input';
|
||||
export * from './label';
|
||||
export * from './popover';
|
||||
export * from './select';
|
||||
export * from './sortable-header';
|
||||
export * from './tabs';
|
||||
24
packages/shared-ui/src/primitives/input.tsx
Normal file
24
packages/shared-ui/src/primitives/input.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
25
packages/shared-ui/src/primitives/label.tsx
Normal file
25
packages/shared-ui/src/primitives/label.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const labelVariants = cva(
|
||||
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
30
packages/shared-ui/src/primitives/popover.tsx
Normal file
30
packages/shared-ui/src/primitives/popover.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import * as PopoverPrimitive from '@radix-ui/react-popover';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
const Popover = PopoverPrimitive.Root;
|
||||
|
||||
const PopoverTrigger = PopoverPrimitive.Trigger;
|
||||
|
||||
const PopoverContent = React.forwardRef<
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-[9999] w-72 rounded-md border bg-white dark:bg-gray-900 p-4 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
));
|
||||
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent };
|
||||
99
packages/shared-ui/src/primitives/select.tsx
Normal file
99
packages/shared-ui/src/primitives/select.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
|
||||
interface SelectContextValue {
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const SelectContext = React.createContext<SelectContextValue | undefined>(undefined);
|
||||
|
||||
interface SelectProps {
|
||||
value?: string;
|
||||
defaultValue?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Select({ value, defaultValue = '', onValueChange, children }: SelectProps) {
|
||||
const [internalValue, setInternalValue] = React.useState(defaultValue);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const currentValue = value ?? internalValue;
|
||||
|
||||
const handleValueChange = React.useCallback((newValue: string) => {
|
||||
setInternalValue(newValue);
|
||||
onValueChange?.(newValue);
|
||||
setOpen(false);
|
||||
}, [onValueChange]);
|
||||
|
||||
return (
|
||||
<SelectContext.Provider value={{ value: currentValue, onValueChange: handleValueChange, open, setOpen }}>
|
||||
<div className="relative">{children}</div>
|
||||
</SelectContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectTrigger({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
const context = React.useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectTrigger must be used within Select');
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => context.setOpen(!context.open)}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectValue({ placeholder }: { placeholder?: string }) {
|
||||
const context = React.useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectValue must be used within Select');
|
||||
|
||||
return <span>{context.value || placeholder}</span>;
|
||||
}
|
||||
|
||||
export function SelectContent({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
const context = React.useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectContent must be used within Select');
|
||||
|
||||
if (!context.open) return null;
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'absolute z-50 mt-1 max-h-60 w-full overflow-auto rounded-md border bg-white dark:bg-zinc-900 p-1 text-popover-foreground shadow-md',
|
||||
className
|
||||
)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectItem({ value, children, className }: { value: string; children: React.ReactNode; className?: string }) {
|
||||
const context = React.useContext(SelectContext);
|
||||
if (!context) throw new Error('SelectItem must be used within Select');
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={() => context.onValueChange(value)}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 px-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground',
|
||||
context.value === value && 'bg-accent text-accent-foreground',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
26
packages/shared-ui/src/primitives/sortable-header.tsx
Normal file
26
packages/shared-ui/src/primitives/sortable-header.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
|
||||
import type { SortDir } from '../hooks/use-table-sort';
|
||||
|
||||
interface SortableHeaderProps {
|
||||
label: string;
|
||||
active: SortDir | null;
|
||||
onClick: () => void;
|
||||
align?: 'left' | 'right';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SortableHeader({ label, active, onClick, align = 'left', className = '' }: SortableHeaderProps) {
|
||||
const Icon = active === 'asc' ? ArrowUp : active === 'desc' ? ArrowDown : ArrowUpDown;
|
||||
return (
|
||||
<th
|
||||
className={`pb-3 font-medium cursor-pointer select-none hover:text-foreground ${align === 'right' ? 'text-right' : ''} ${className}`}
|
||||
onClick={onClick}
|
||||
title={`Ordenar por ${label.toLowerCase()}`}
|
||||
>
|
||||
{label}
|
||||
<Icon className={`h-3 w-3 inline-block ml-1 ${active ? '' : 'opacity-40'}`} />
|
||||
</th>
|
||||
);
|
||||
}
|
||||
72
packages/shared-ui/src/primitives/tabs.tsx
Normal file
72
packages/shared-ui/src/primitives/tabs.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { cn } from '../lib/cn';
|
||||
|
||||
interface TabsContextValue {
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
}
|
||||
|
||||
const TabsContext = React.createContext<TabsContextValue | undefined>(undefined);
|
||||
|
||||
interface TabsProps {
|
||||
defaultValue: string;
|
||||
value?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Tabs({ defaultValue, value, onValueChange, children, className }: TabsProps) {
|
||||
const [internalValue, setInternalValue] = React.useState(defaultValue);
|
||||
const currentValue = value ?? internalValue;
|
||||
|
||||
const handleValueChange = React.useCallback((newValue: string) => {
|
||||
setInternalValue(newValue);
|
||||
onValueChange?.(newValue);
|
||||
}, [onValueChange]);
|
||||
|
||||
return (
|
||||
<TabsContext.Provider value={{ value: currentValue, onValueChange: handleValueChange }}>
|
||||
<div className={className}>{children}</div>
|
||||
</TabsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabsList({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn('inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground', className)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabsTrigger({ value, children, className }: { value: string; children: React.ReactNode; className?: string }) {
|
||||
const context = React.useContext(TabsContext);
|
||||
if (!context) throw new Error('TabsTrigger must be used within Tabs');
|
||||
|
||||
const isActive = context.value === value;
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => context.onValueChange(value)}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
|
||||
isActive && 'bg-background text-foreground shadow-sm',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabsContent({ value, children, className }: { value: string; children: React.ReactNode; className?: string }) {
|
||||
const context = React.useContext(TabsContext);
|
||||
if (!context) throw new Error('TabsContent must be used within Tabs');
|
||||
|
||||
if (context.value !== value) return null;
|
||||
|
||||
return <div className={cn('mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2', className)}>{children}</div>;
|
||||
}
|
||||
51
packages/shared-ui/tailwind-preset.js
Normal file
51
packages/shared-ui/tailwind-preset.js
Normal file
@@ -0,0 +1,51 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ["Inter", "sans-serif"],
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
19
packages/shared-ui/tsconfig.json
Normal file
19
packages/shared-ui/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"isolatedModules": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2022"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
14
packages/shared/package.json
Normal file
14
packages/shared/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@horux/shared",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint src/",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
208
packages/shared/src/constants/despacho-plans.ts
Normal file
208
packages/shared/src/constants/despacho-plans.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
export const DESPACHO_PLANS = {
|
||||
trial: {
|
||||
name: 'Trial',
|
||||
maxRfcs: 3,
|
||||
maxUsers: 1,
|
||||
maxCfdisPorContribuyente: 1_000_000,
|
||||
timbresIncluidosMes: 20,
|
||||
dbMode: 'MANAGED' as const,
|
||||
permiteServidorBackup: false,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat',
|
||||
],
|
||||
},
|
||||
mi_empresa: {
|
||||
name: 'Mi Empresa',
|
||||
maxRfcs: 1,
|
||||
maxUsers: 3,
|
||||
maxCfdisPorContribuyente: 1_000_000,
|
||||
timbresIncluidosMes: 50,
|
||||
dbMode: 'MANAGED' as const,
|
||||
permiteServidorBackup: false,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat',
|
||||
],
|
||||
},
|
||||
mi_empresa_plus: {
|
||||
name: 'Mi Empresa +',
|
||||
maxRfcs: 1,
|
||||
maxUsers: 3,
|
||||
maxCfdisPorContribuyente: 1_000_000,
|
||||
timbresIncluidosMes: 50,
|
||||
dbMode: 'MANAGED' as const,
|
||||
permiteServidorBackup: false,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat', 'api', 'ia_lolita',
|
||||
],
|
||||
},
|
||||
business_control: {
|
||||
name: 'Business Control',
|
||||
maxRfcs: 100,
|
||||
maxUsers: -1,
|
||||
maxCfdisPorContribuyente: 1_000_000,
|
||||
timbresIncluidosMes: 0,
|
||||
dbMode: 'BYO' as const,
|
||||
permiteServidorBackup: true,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat', 'api',
|
||||
],
|
||||
},
|
||||
// Custom — gratis, sin fecha fin, solo asignable por Admin Global.
|
||||
// Reusa el enum `custom` (legacy "precio variable" tenía 0 tenants).
|
||||
// Comportamiento idéntico a Mi Empresa (1 RFC, MANAGED, sin API ni Lolita)
|
||||
// pero NO se incluye en DESPACHO_PLAN_PRICES — no genera Subscription ni
|
||||
// cobro MP. Ningún cron lo expira (sin trialEndsAt, sin currentPeriodEnd).
|
||||
// Oculto del catálogo user-facing, visible solo en `/clientes` admin.
|
||||
custom: {
|
||||
name: 'Custom',
|
||||
maxRfcs: 1,
|
||||
maxUsers: 3,
|
||||
maxCfdisPorContribuyente: 1_000_000,
|
||||
timbresIncluidosMes: 50,
|
||||
dbMode: 'MANAGED' as const,
|
||||
permiteServidorBackup: false,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat',
|
||||
],
|
||||
},
|
||||
// Identificador interno: business_cloud (no se renombra el enum por
|
||||
// backward compat de suscripciones existentes). Nombre display: "Enterprise".
|
||||
business_cloud: {
|
||||
name: 'Enterprise',
|
||||
maxRfcs: 100,
|
||||
maxUsers: -1,
|
||||
maxCfdisPorContribuyente: 3_000_000,
|
||||
timbresIncluidosMes: 0,
|
||||
dbMode: 'BYO' as const,
|
||||
permiteServidorBackup: true,
|
||||
features: [
|
||||
'dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas',
|
||||
'calendario', 'conciliacion', 'documentos', 'facturacion',
|
||||
'forecasting', 'xml_sat', 'api',
|
||||
],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type DespachoPlan = keyof typeof DESPACHO_PLANS;
|
||||
|
||||
/**
|
||||
* Precios MXN (IVA incluido) para planes despacho pagables.
|
||||
*
|
||||
* - `monthly`: precio mensual. Solo aplica a planes con `permiteMonthly=true`
|
||||
* (Mi Empresa, Mi Empresa+). Para Business Control y Enterprise es null.
|
||||
* - `firstYear` / `renewal`: precios anuales. `firstYear` es lo que se cobra
|
||||
* al contratar; `renewal` lo que MP cobra automáticamente en renovaciones.
|
||||
* Cuando ambos son iguales no hay dualidad.
|
||||
*
|
||||
* Política de descuento (D1, 2026-04-26): Mi Empresa y Mi Empresa+ tienen
|
||||
* descuento del ~17% al pagar el año adelantado — el cobro anual es
|
||||
* equivalente a 10 meses (en lugar de 12).
|
||||
*
|
||||
* mi_empresa: $580/mes → $5,800/año (10 meses)
|
||||
* mi_empresa_plus: $900/mes → $9,000/año (10 meses)
|
||||
*/
|
||||
export const DESPACHO_PLAN_PRICES = {
|
||||
mi_empresa: {
|
||||
monthly: 580,
|
||||
firstYear: 5_800,
|
||||
renewal: 5_800,
|
||||
permiteMonthly: true,
|
||||
},
|
||||
mi_empresa_plus: {
|
||||
monthly: 900,
|
||||
firstYear: 9_000,
|
||||
renewal: 9_000,
|
||||
permiteMonthly: true,
|
||||
},
|
||||
business_control: {
|
||||
monthly: null,
|
||||
firstYear: 25_850,
|
||||
renewal: 25_850,
|
||||
permiteMonthly: false,
|
||||
},
|
||||
business_cloud: { // display: Enterprise
|
||||
monthly: null,
|
||||
firstYear: 43_000,
|
||||
renewal: 43_000,
|
||||
permiteMonthly: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type DespachoPaidPlan = keyof typeof DESPACHO_PLAN_PRICES;
|
||||
export type DespachoPricePhase = 'firstYear' | 'renewal';
|
||||
export type DespachoFrequency = 'monthly' | 'annual';
|
||||
|
||||
/**
|
||||
* Resuelve el precio MXN para un (plan, frequency, phase). Para monthly
|
||||
* la fase se ignora (no hay dualidad mensual). Para annual aplica
|
||||
* firstYear o renewal según corresponda. Throws si el plan no permite
|
||||
* la frecuencia solicitada.
|
||||
*/
|
||||
export function getPrecioDespacho(
|
||||
plan: DespachoPaidPlan,
|
||||
frequency: DespachoFrequency,
|
||||
phase: DespachoPricePhase = 'renewal',
|
||||
): number {
|
||||
const cfg = DESPACHO_PLAN_PRICES[plan];
|
||||
if (frequency === 'monthly') {
|
||||
if (!cfg.permiteMonthly || cfg.monthly == null) {
|
||||
throw new Error(`El plan ${plan} no permite frecuencia mensual`);
|
||||
}
|
||||
return cfg.monthly;
|
||||
}
|
||||
return cfg[phase];
|
||||
}
|
||||
|
||||
/** True si el plan acepta frecuencia mensual (Mi Empresa y Mi Empresa+). */
|
||||
export function permiteFrecuenciaMensual(plan: string): boolean {
|
||||
if (plan in DESPACHO_PLAN_PRICES) {
|
||||
return DESPACHO_PLAN_PRICES[plan as DespachoPaidPlan].permiteMonthly;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Costo mensual MXN por contribuyente extra que excede `maxRfcs` del
|
||||
* plan. Solo aplica a business_control y business_cloud (Enterprise).
|
||||
* Mi Empresa tiene límite duro de 1 RFC; no permite extras.
|
||||
*/
|
||||
export const DESPACHO_OVERAGE_PRICE_MENSUAL = 45;
|
||||
|
||||
/** True si el plan cobra distinto en el primer año vs renovaciones (anual). */
|
||||
export function despachoPlanTieneDualidad(plan: DespachoPaidPlan): boolean {
|
||||
const p = DESPACHO_PLAN_PRICES[plan];
|
||||
return p.firstYear !== p.renewal;
|
||||
}
|
||||
|
||||
export function getDespachoPlanLimits(plan: DespachoPlan) {
|
||||
return DESPACHO_PLANS[plan];
|
||||
}
|
||||
|
||||
export function hasDespachoFeature(plan: DespachoPlan, feature: string): boolean {
|
||||
return (DESPACHO_PLANS[plan]?.features as readonly string[])?.includes(feature) ?? false;
|
||||
}
|
||||
|
||||
export function isDespachoTenant(tenantRfc: string | null | undefined): boolean {
|
||||
return typeof tenantRfc === 'string' && tenantRfc.toUpperCase().startsWith('DESPACHO_');
|
||||
}
|
||||
|
||||
/** True si el plan es uno pagable de despacho (excluye trial). */
|
||||
export function isDespachoPaidPlan(plan: string): plan is DespachoPaidPlan {
|
||||
return plan === 'business_control' || plan === 'business_cloud'
|
||||
|| plan === 'mi_empresa' || plan === 'mi_empresa_plus';
|
||||
}
|
||||
|
||||
/** Planes que permiten cobrar overage por contribuyente extra. */
|
||||
export function permiteOverage(plan: string): boolean {
|
||||
return plan === 'business_control' || plan === 'business_cloud';
|
||||
}
|
||||
46
packages/shared/src/constants/plans.ts
Normal file
46
packages/shared/src/constants/plans.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
export const PLANS = {
|
||||
starter: {
|
||||
name: 'Starter',
|
||||
cfdiLimit: 0,
|
||||
usersLimit: 1,
|
||||
features: ['dashboard', 'cfdi_basic', 'iva_isr'],
|
||||
},
|
||||
business: {
|
||||
name: 'Business',
|
||||
cfdiLimit: 50,
|
||||
usersLimit: 3,
|
||||
features: ['dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas', 'calendario', 'conciliacion', 'forecasting', 'xml_sat', 'documentos'],
|
||||
},
|
||||
business_ia: {
|
||||
name: 'Business + IA',
|
||||
cfdiLimit: 50,
|
||||
usersLimit: 3,
|
||||
features: ['dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas', 'calendario', 'conciliacion', 'forecasting', 'xml_sat', 'documentos', 'ia_lolita'],
|
||||
},
|
||||
custom: {
|
||||
name: 'Custom',
|
||||
cfdiLimit: 50,
|
||||
usersLimit: 3,
|
||||
features: ['dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas', 'calendario', 'conciliacion', 'forecasting', 'xml_sat', 'documentos', 'ia_lolita'],
|
||||
},
|
||||
enterprise: {
|
||||
name: 'Enterprise',
|
||||
cfdiLimit: 100,
|
||||
usersLimit: -1,
|
||||
features: ['dashboard', 'cfdi_basic', 'iva_isr', 'reportes', 'alertas', 'calendario', 'conciliacion', 'forecasting', 'xml_sat', 'documentos', 'api', 'ia_lolita'],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type Plan = keyof typeof PLANS;
|
||||
|
||||
export function getPlanLimits(plan: Plan) {
|
||||
return PLANS[plan];
|
||||
}
|
||||
|
||||
export function hasFeature(plan: Plan, feature: string): boolean {
|
||||
// Defensive: un plan desconocido (típicamente un valor que no pertenece
|
||||
// al catálogo Horux 360 — p.ej. un plan despacho usado por error)
|
||||
// retorna false en vez de crashear con "Cannot read properties of undefined".
|
||||
// El caller debe usar el catálogo correcto según la vertical del tenant.
|
||||
return (PLANS[plan]?.features as readonly string[] | undefined)?.includes(feature) ?? false;
|
||||
}
|
||||
76
packages/shared/src/constants/roles.ts
Normal file
76
packages/shared/src/constants/roles.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { Role, PlatformRole } from '../types/auth';
|
||||
|
||||
export const GLOBAL_ADMIN_RFC = 'HTS240708LJA';
|
||||
|
||||
/** Roles que son superset (implican todos los demás platform roles). */
|
||||
const SUPERSET_ROLES: PlatformRole[] = ['platform_admin', 'platform_ti'];
|
||||
|
||||
/**
|
||||
* "Admin global" = staff interno de Horux 360 con rol `platform_admin` o `platform_ti`.
|
||||
*
|
||||
* Primero checa `platformRoles` del user (nueva fuente de verdad post-migración).
|
||||
* Si no hay platformRoles (JWT viejo, sesión pre-deploy), cae al check legacy
|
||||
* por RFC + rol owner del tenant HTS240708LJA.
|
||||
*
|
||||
* Código nuevo debería preferir `hasPlatformRoleFromArray(platformRoles, 'platform_admin')`.
|
||||
*/
|
||||
export function isGlobalAdminRfc(
|
||||
tenantRfc: string | undefined,
|
||||
role: string | undefined,
|
||||
platformRoles?: PlatformRole[] | null,
|
||||
): boolean {
|
||||
// Nueva fuente: platform_admin o platform_ti en user_platform_roles
|
||||
if (platformRoles && SUPERSET_ROLES.some(r => platformRoles.includes(r))) return true;
|
||||
// Fallback legacy: owner del tenant con RFC admin global
|
||||
return role === 'owner' && tenantRfc === GLOBAL_ADMIN_RFC;
|
||||
}
|
||||
|
||||
/** ¿El user tiene algún rol de plataforma (staff interno)? */
|
||||
export function isPlatformStaffFromRoles(platformRoles?: PlatformRole[] | null): boolean {
|
||||
return !!platformRoles && platformRoles.length > 0;
|
||||
}
|
||||
|
||||
/** ¿El user tiene el rol de plataforma indicado? admin y ti implican todos. */
|
||||
export function hasPlatformRoleFromArray(
|
||||
platformRoles: PlatformRole[] | undefined | null,
|
||||
role: PlatformRole,
|
||||
): boolean {
|
||||
if (!platformRoles) return false;
|
||||
if (SUPERSET_ROLES.some(r => platformRoles.includes(r))) return true;
|
||||
return platformRoles.includes(role);
|
||||
}
|
||||
|
||||
export const ROLES = {
|
||||
owner: {
|
||||
name: 'Dueño',
|
||||
permissions: ['read', 'write', 'delete', 'manage_users', 'manage_settings'],
|
||||
},
|
||||
cfo: {
|
||||
name: 'CFO',
|
||||
permissions: ['read', 'write', 'delete', 'manage_users', 'manage_settings'],
|
||||
},
|
||||
contador: {
|
||||
name: 'Contador',
|
||||
permissions: ['read', 'write', 'resolve_alertas'],
|
||||
},
|
||||
auxiliar: {
|
||||
name: 'Auxiliar',
|
||||
permissions: ['read', 'write', 'resolve_alertas'],
|
||||
},
|
||||
visor: {
|
||||
name: 'Visor',
|
||||
permissions: ['read'],
|
||||
},
|
||||
supervisor: {
|
||||
name: 'Supervisor',
|
||||
permissions: ['read', 'write', 'resolve_alertas', 'manage_carteras'],
|
||||
},
|
||||
cliente: {
|
||||
name: 'Cliente',
|
||||
permissions: ['read'],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function hasPermission(role: Role, permission: string): boolean {
|
||||
return ROLES[role].permissions.includes(permission as any);
|
||||
}
|
||||
18
packages/shared/src/index.ts
Normal file
18
packages/shared/src/index.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
// Types
|
||||
export * from './types/auth';
|
||||
export * from './types/tenant';
|
||||
export * from './types/user';
|
||||
export * from './types/cfdi';
|
||||
export * from './types/dashboard';
|
||||
export * from './types/impuestos';
|
||||
export * from './types/alertas';
|
||||
export * from './types/reportes';
|
||||
export * from './types/calendario';
|
||||
export * from './types/sat';
|
||||
export * from './types/documentos';
|
||||
export * from './types/despacho';
|
||||
|
||||
// Constants
|
||||
export * from './constants/plans';
|
||||
export * from './constants/despacho-plans';
|
||||
export * from './constants/roles';
|
||||
35
packages/shared/src/types/alertas.ts
Normal file
35
packages/shared/src/types/alertas.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export type TipoAlerta = 'vencimiento' | 'discrepancia' | 'iva_favor' | 'declaracion' | 'limite_cfdi' | 'custom';
|
||||
export type PrioridadAlerta = 'alta' | 'media' | 'baja';
|
||||
|
||||
export interface AlertaCreate {
|
||||
tipo: TipoAlerta;
|
||||
titulo: string;
|
||||
mensaje: string;
|
||||
prioridad: PrioridadAlerta;
|
||||
fechaVencimiento?: string;
|
||||
}
|
||||
|
||||
export interface AlertaUpdate {
|
||||
leida?: boolean;
|
||||
resuelta?: boolean;
|
||||
}
|
||||
|
||||
export interface AlertaFull {
|
||||
id: number;
|
||||
tipo: TipoAlerta;
|
||||
titulo: string;
|
||||
mensaje: string;
|
||||
prioridad: PrioridadAlerta;
|
||||
fechaVencimiento: string | null;
|
||||
leida: boolean;
|
||||
resuelta: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface AlertasStats {
|
||||
total: number;
|
||||
noLeidas: number;
|
||||
alta: number;
|
||||
media: number;
|
||||
baja: number;
|
||||
}
|
||||
78
packages/shared/src/types/auth.ts
Normal file
78
packages/shared/src/types/auth.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
user: UserInfo;
|
||||
}
|
||||
|
||||
export interface RegisterRequest {
|
||||
empresa: {
|
||||
nombre: string;
|
||||
rfc: string;
|
||||
};
|
||||
usuario: {
|
||||
nombre: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TenantMembership {
|
||||
id: string;
|
||||
nombre: string;
|
||||
rfc: string;
|
||||
plan: string;
|
||||
role: Role;
|
||||
isOwner: boolean;
|
||||
}
|
||||
|
||||
export interface UserInfo {
|
||||
id: string;
|
||||
email: string;
|
||||
nombre: string;
|
||||
/** Rol en el tenant ACTIVO (el que resolvió el JWT). */
|
||||
role: Role;
|
||||
/** Tenant activo (el que resolvió el JWT). */
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
tenantRfc: string;
|
||||
plan: string;
|
||||
platformRoles?: PlatformRole[];
|
||||
/**
|
||||
* Todos los tenants a los que pertenece este user. Si len > 1, la UI muestra
|
||||
* el tenant switcher. Derivado de la tabla tenant_memberships (active=true).
|
||||
*/
|
||||
tenants?: TenantMembership[];
|
||||
}
|
||||
|
||||
export interface JWTPayload {
|
||||
userId: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
tenantId: string;
|
||||
platformRoles?: PlatformRole[];
|
||||
/**
|
||||
* Version del user al emitir el JWT. Si el user incrementa su tokenVersion
|
||||
* (cambio de password, logout-all), todos los JWT con version menor dejan
|
||||
* de validar. Default 0 para compat con JWT emitidos antes del rollout.
|
||||
*/
|
||||
tokenVersion?: number;
|
||||
iat?: number;
|
||||
exp?: number;
|
||||
}
|
||||
|
||||
export type Role = 'owner' | 'cfo' | 'contador' | 'auxiliar' | 'visor' | 'supervisor' | 'cliente';
|
||||
|
||||
/**
|
||||
* Roles de plataforma (staff interno de Horux 360). Ortogonal al `Role` per-tenant.
|
||||
* Un user puede tener 0, 1 o varios.
|
||||
*
|
||||
* Superset roles (implican todos los otros):
|
||||
* - `platform_admin` — admin global
|
||||
* - `platform_ti` — equipo de TI, mismos permisos que admin. Diferencia semántica para trazabilidad.
|
||||
*/
|
||||
export type PlatformRole = 'platform_admin' | 'platform_ti' | 'platform_support' | 'platform_sales' | 'platform_finance';
|
||||
37
packages/shared/src/types/calendario.ts
Normal file
37
packages/shared/src/types/calendario.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
export type TipoEvento = 'declaracion' | 'pago' | 'obligacion' | 'informativa' | 'custom' | 'tarea';
|
||||
export type Recurrencia = 'mensual' | 'bimestral' | 'trimestral' | 'anual' | 'unica';
|
||||
|
||||
export interface EventoFiscal {
|
||||
id?: number;
|
||||
titulo: string;
|
||||
descripcion: string;
|
||||
tipo: TipoEvento;
|
||||
fechaLimite: string;
|
||||
recurrencia: Recurrencia | string;
|
||||
completado: boolean;
|
||||
notas?: string | null;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface EventoCreate {
|
||||
titulo: string;
|
||||
descripcion: string;
|
||||
tipo: TipoEvento;
|
||||
fechaLimite: string;
|
||||
recurrencia: Recurrencia;
|
||||
notas?: string;
|
||||
}
|
||||
|
||||
export interface EventoUpdate {
|
||||
titulo?: string;
|
||||
descripcion?: string;
|
||||
fechaLimite?: string;
|
||||
completado?: boolean;
|
||||
notas?: string;
|
||||
}
|
||||
|
||||
export interface CalendarioMes {
|
||||
año: number;
|
||||
mes: number;
|
||||
eventos: EventoFiscal[];
|
||||
}
|
||||
176
packages/shared/src/types/cfdi.ts
Normal file
176
packages/shared/src/types/cfdi.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
export type TipoCfdi = 'EMITIDO' | 'RECIBIDO';
|
||||
export type TipoComprobante = 'I' | 'E' | 'T' | 'P' | 'N';
|
||||
export type EstadoCfdi = 'Vigente' | 'Cancelado' | '0' | '1';
|
||||
|
||||
export interface Cfdi {
|
||||
id: number;
|
||||
year: string | null;
|
||||
month: string | null;
|
||||
type: TipoCfdi;
|
||||
uuid: string;
|
||||
serie: string | null;
|
||||
folio: string | null;
|
||||
status: EstadoCfdi;
|
||||
fechaEmision: string;
|
||||
rfcEmisor: string;
|
||||
nombreEmisor: string;
|
||||
rfcReceptor: string;
|
||||
nombreReceptor: string;
|
||||
subtotal: number;
|
||||
subtotalMxn: number;
|
||||
descuento: number;
|
||||
descuentoMxn: number;
|
||||
total: number;
|
||||
totalMxn: number;
|
||||
saldoInsoluto: string | null;
|
||||
moneda: string;
|
||||
tipoCambio: number;
|
||||
tipoComprobante: string | null;
|
||||
metodoPago: string | null;
|
||||
formaPago: string | null;
|
||||
usoCfdi: string | null;
|
||||
pac: string | null;
|
||||
fechaCertSat: string | null;
|
||||
fechaCancelacion: string | null;
|
||||
uuidRelacionado: string | null;
|
||||
// Impuestos del comprobante
|
||||
isrRetencion: number;
|
||||
isrRetencionMxn: number;
|
||||
ivaTraslado: number;
|
||||
ivaTrasladoMxn: number;
|
||||
ivaRetencion: number;
|
||||
ivaRetencionMxn: number;
|
||||
iepsTraslado: number;
|
||||
iepsTrasladoMxn: number;
|
||||
iepsRetencion: number;
|
||||
iepsRetencionMxn: number;
|
||||
impuestosLocalesTrasladado: number;
|
||||
impuestosLocalesTrasladoMxn: number;
|
||||
impuestosLocalesRetenidos: number;
|
||||
impuestosLocalesRetenidosMxn: number;
|
||||
// Complemento de pagos
|
||||
montoPago: number;
|
||||
montoPagoMxn: number;
|
||||
fechaPagoP: string | null;
|
||||
numParcialidad: string | null;
|
||||
isrRetencionPago: number;
|
||||
isrRetencionPagoMxn: number;
|
||||
ivaTrasladoPago: number;
|
||||
ivaTrasladoPagoMxn: number;
|
||||
ivaRetencionPago: number;
|
||||
ivaRetencionPagoMxn: number;
|
||||
iepsTrasladoPago: number;
|
||||
iepsTrasladoPagoMxn: number;
|
||||
iepsRetencionPago: number;
|
||||
iepsRetencionPagoMxn: number;
|
||||
saldoPendiente: number;
|
||||
saldoPendienteMxn: number;
|
||||
fechaLiquidacion: string | null;
|
||||
fechaPago: string | null;
|
||||
fechaInicialPago: string | null;
|
||||
fechaFinalPago: string | null;
|
||||
numDiasPagados: number;
|
||||
// Nómina
|
||||
numSeguroSocial: string | null;
|
||||
puesto: string | null;
|
||||
salarioBaseCotApor: number;
|
||||
salarioBaseCotAporMxn: number;
|
||||
salarioDiarioIntegrado: number;
|
||||
salarioDiarioIntegradoMxn: number;
|
||||
totalPercepciones: number;
|
||||
totalPercepcionesMxn: number;
|
||||
totalDeducciones: number;
|
||||
totalDeduccionesMxn: number;
|
||||
impRetenidosNomina: number;
|
||||
impRetenidosNominaMxn: number;
|
||||
otrasDeduccionesNomina: number;
|
||||
otrasDeduccionesNominaMxn: number;
|
||||
subsidioCausado: number;
|
||||
subsidioCausadoMxn: number;
|
||||
// Conciliación
|
||||
conciliado: string | null;
|
||||
// Régimen fiscal
|
||||
regimenFiscalEmisor: string | null;
|
||||
regimenFiscalReceptor: string | null;
|
||||
// FK a tabla rfcs
|
||||
rfcEmisorId: number | null;
|
||||
rfcReceptorId: number | null;
|
||||
// Archivos y sync
|
||||
xmlUrl: string | null;
|
||||
pdfUrl: string | null;
|
||||
xmlOriginal: string | null;
|
||||
cfdiTipoRelacion: string | null;
|
||||
cfdisRelacionados: string | null;
|
||||
lastSatSync: string | null;
|
||||
satSyncJobId: string | null;
|
||||
source: string | null;
|
||||
facturapiId: string | null;
|
||||
contribuyenteId: string | null;
|
||||
creadoEn: string;
|
||||
actualizadoEn: string;
|
||||
}
|
||||
|
||||
export interface CfdiFilters {
|
||||
tipo?: TipoCfdi;
|
||||
tipoComprobante?: TipoComprobante;
|
||||
estado?: EstadoCfdi;
|
||||
fechaInicio?: string;
|
||||
fechaFin?: string;
|
||||
rfc?: string;
|
||||
emisor?: string;
|
||||
receptor?: string;
|
||||
search?: string;
|
||||
contribuyenteId?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface CfdiConcepto {
|
||||
id: number;
|
||||
cfdiId: number;
|
||||
claveProdServ: string | null;
|
||||
noIdentificacion: string | null;
|
||||
descripcion: string;
|
||||
cantidad: number;
|
||||
claveUnidad: string | null;
|
||||
unidad: string | null;
|
||||
valorUnitario: number;
|
||||
valorUnitarioMxn: number;
|
||||
importe: number;
|
||||
importeMxn: number;
|
||||
descuento: number;
|
||||
descuentoMxn: number;
|
||||
isrRetencion: number;
|
||||
isrRetencionMxn: number;
|
||||
ivaTraslado: number;
|
||||
ivaTrasladoMxn: number;
|
||||
ivaRetencion: number;
|
||||
ivaRetencionMxn: number;
|
||||
iepsTraslado: number;
|
||||
iepsTrasladoMxn: number;
|
||||
iepsRetencion: number;
|
||||
iepsRetencionMxn: number;
|
||||
impuestosLocalesTrasladado: number;
|
||||
impuestosLocalesTrasladoMxn: number;
|
||||
impuestosLocalesRetenidos: number;
|
||||
impuestosLocalesRetenidosMxn: number;
|
||||
totalPercepciones: number;
|
||||
totalPercepcionesMxn: number;
|
||||
totalDeducciones: number;
|
||||
totalDeduccionesMxn: number;
|
||||
impRetenidosNomina: number;
|
||||
impRetenidosNominaMxn: number;
|
||||
otrasDeduccionesNomina: number;
|
||||
otrasDeduccionesNominaMxn: number;
|
||||
subsidioCausado: number;
|
||||
subsidioCausadoMxn: number;
|
||||
creadoEn: string;
|
||||
}
|
||||
|
||||
export interface CfdiListResponse {
|
||||
data: Cfdi[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
}
|
||||
73
packages/shared/src/types/dashboard.ts
Normal file
73
packages/shared/src/types/dashboard.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
export interface IngresoRegimen {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
monto: number;
|
||||
}
|
||||
|
||||
export interface EgresoRegimen {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
monto: number;
|
||||
}
|
||||
|
||||
export interface IvaBalanceRegimen {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
monto: number;
|
||||
}
|
||||
|
||||
export interface KpiData {
|
||||
ingresos: number;
|
||||
ingresosPorRegimen: IngresoRegimen[];
|
||||
egresos: number;
|
||||
egresosPorRegimen: EgresoRegimen[];
|
||||
adquisicionMercancias: number;
|
||||
adquisicionMercanciasPorRegimen?: { regimenClave: string; monto: number }[];
|
||||
utilidad: number;
|
||||
margen: number;
|
||||
ivaBalance: number;
|
||||
ivaBalancePorRegimen: IvaBalanceRegimen[];
|
||||
ivaAFavorAcumulado: number;
|
||||
ivaAFavorHistorico: number;
|
||||
cfdisEmitidos: number;
|
||||
cfdisEmitidosPorRegimen: { regimen: string; total: number }[];
|
||||
cfdisRecibidos: number;
|
||||
cfdisRecibidosPorRegimen: { regimen: string; total: number }[];
|
||||
}
|
||||
|
||||
export interface IngresosEgresosData {
|
||||
mes: string;
|
||||
ingresos: number;
|
||||
egresos: number;
|
||||
}
|
||||
|
||||
export interface ResumenFiscal {
|
||||
ivaPorPagar: number;
|
||||
ivaAFavor: number;
|
||||
isrPorPagar: number;
|
||||
declaracionesPendientes: number;
|
||||
proximaObligacion: {
|
||||
titulo: string;
|
||||
fecha: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface Alerta {
|
||||
id: number;
|
||||
tipo: 'vencimiento' | 'discrepancia' | 'iva_favor' | 'declaracion';
|
||||
titulo: string;
|
||||
mensaje: string;
|
||||
prioridad: 'alta' | 'media' | 'baja';
|
||||
fechaVencimiento: string | null;
|
||||
leida: boolean;
|
||||
resuelta: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type PeriodoFiltro = 'semana' | 'mes' | 'trimestre' | 'año' | 'custom';
|
||||
|
||||
export interface DashboardFilters {
|
||||
periodo: PeriodoFiltro;
|
||||
fechaInicio?: string;
|
||||
fechaFin?: string;
|
||||
}
|
||||
42
packages/shared/src/types/despacho.ts
Normal file
42
packages/shared/src/types/despacho.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export type DespachoRole = 'owner' | 'supervisor' | 'auxiliar' | 'cliente';
|
||||
|
||||
export type VerticalProfile = 'CONTABLE' | 'JURIDICO' | 'ARQUITECTURA';
|
||||
|
||||
export type DbMode = 'BYO' | 'MANAGED';
|
||||
|
||||
export interface DespachoInfo {
|
||||
id: string;
|
||||
nombre: string;
|
||||
rfc: string;
|
||||
verticalProfile: VerticalProfile;
|
||||
dbMode: DbMode | null;
|
||||
plan: string;
|
||||
}
|
||||
|
||||
export type DespachoSignupPlan = 'trial' | 'business_control' | 'business_cloud';
|
||||
|
||||
export interface DespachoSignupRequest {
|
||||
despacho: {
|
||||
nombre: string;
|
||||
rfc?: string;
|
||||
regimenFiscal?: string;
|
||||
codigoPostal?: string;
|
||||
verticalProfile: VerticalProfile;
|
||||
plan?: DespachoSignupPlan;
|
||||
};
|
||||
owner: {
|
||||
nombre: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ContribuyenteInfo {
|
||||
id: string;
|
||||
rfc: string;
|
||||
razonSocial: string;
|
||||
regimenFiscal: string;
|
||||
codigoPostal?: string;
|
||||
supervisorUserId?: string;
|
||||
active: boolean;
|
||||
}
|
||||
14
packages/shared/src/types/documentos.ts
Normal file
14
packages/shared/src/types/documentos.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export interface OpinionCumplimiento {
|
||||
id: number;
|
||||
rfc: string;
|
||||
razonSocial: string;
|
||||
estatus: string;
|
||||
folio: string;
|
||||
cadenaOriginal: string;
|
||||
fechaConsulta: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface OpinionCumplimientoFull extends OpinionCumplimiento {
|
||||
pdf: Buffer;
|
||||
}
|
||||
100
packages/shared/src/types/impuestos.ts
Normal file
100
packages/shared/src/types/impuestos.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
export type EstadoDeclaracion = 'pendiente' | 'declarado' | 'acreditado';
|
||||
|
||||
export interface IvaMensual {
|
||||
id: number;
|
||||
año: number;
|
||||
mes: number;
|
||||
ivaTrasladado: number;
|
||||
ivaAcreditable: number;
|
||||
ivaRetenido: number;
|
||||
resultado: number;
|
||||
acumulado: number;
|
||||
estado: EstadoDeclaracion;
|
||||
fechaDeclaracion: string | null;
|
||||
}
|
||||
|
||||
export interface IsrMensual {
|
||||
id: number;
|
||||
año: number;
|
||||
mes: number;
|
||||
ingresosAcumulados: number; // mensual — naming legacy, no se renombra en este spec
|
||||
deducciones: number; // mensual
|
||||
baseGravable: number; // mensual — sigue retornándose para no romper consumidores externos, pero ya no se muestra en la UI
|
||||
// Nuevos: running totals desde enero hasta el mes de esta fila
|
||||
ingresosAcum: number;
|
||||
deduccionesAcum: number;
|
||||
baseGravableAcum: number; // sin clamp; puede ser negativo
|
||||
isrCausado: number;
|
||||
isrRetenido: number;
|
||||
isrAPagar: number;
|
||||
estado: EstadoDeclaracion;
|
||||
fechaDeclaracion: string | null;
|
||||
}
|
||||
|
||||
export interface IvaRegimenDetalle {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
monto: number;
|
||||
}
|
||||
|
||||
export interface ResumenIva {
|
||||
trasladado: number;
|
||||
trasladadoPorRegimen: IvaRegimenDetalle[];
|
||||
acreditable: number;
|
||||
acreditablePorRegimen: IvaRegimenDetalle[];
|
||||
retenido: number;
|
||||
retenidoPorRegimen: IvaRegimenDetalle[];
|
||||
resultado: number;
|
||||
acumuladoAnual: number;
|
||||
}
|
||||
|
||||
export interface IsrRegimenDetalle {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
monto: number;
|
||||
}
|
||||
|
||||
export interface BaseGravableRegimen {
|
||||
regimenClave: string;
|
||||
regimenDescripcion: string;
|
||||
ingresos: number;
|
||||
deducciones: number;
|
||||
baseGravable: number;
|
||||
isrCausado: number;
|
||||
formula: 'ingresos' | 'ingresos-deducciones';
|
||||
}
|
||||
|
||||
export interface ResumenIsr {
|
||||
ingresosAcumulados: number;
|
||||
ingresosPorRegimen: IsrRegimenDetalle[];
|
||||
deducciones: number;
|
||||
deduccionesPorRegimen: IsrRegimenDetalle[];
|
||||
baseGravable: number;
|
||||
baseGravablePorRegimen: BaseGravableRegimen[];
|
||||
isrCausado: number;
|
||||
isrRetenido: number;
|
||||
isrAPagar: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desglose del cálculo provisional ISR del mes final del filtro:
|
||||
* delPeriodo = solo el mes final del filtro (1 mes)
|
||||
* anteriores = enero hasta el mes anterior al final (puede estar vacío)
|
||||
* total = enero hasta el mes final inclusive
|
||||
*
|
||||
* Reglas:
|
||||
* - delPeriodo + anteriores = total para campos aditivos (ingresos, deducciones, retenciones).
|
||||
* - Para baseGravable e isrCausado el total se calcula sobre el rango entero
|
||||
* (no es la suma algebraica de delPeriodo + anteriores).
|
||||
* - baseGravable puede ser negativa en cualquiera de los tres rangos.
|
||||
* - isrCausado se clampa a 0 cuando la baseGravable acumulada es negativa.
|
||||
*/
|
||||
export interface ResumenIsrDesglosado {
|
||||
delPeriodo: ResumenIsr;
|
||||
anteriores: ResumenIsr;
|
||||
total: ResumenIsr;
|
||||
/** Mes final del filtro (1-12) */
|
||||
mesFinal: number;
|
||||
/** Año fiscal del filtro */
|
||||
anio: number;
|
||||
}
|
||||
46
packages/shared/src/types/reportes.ts
Normal file
46
packages/shared/src/types/reportes.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
export interface EstadoResultados {
|
||||
periodo: { inicio: string; fin: string };
|
||||
ingresos: { concepto: string; monto: number }[];
|
||||
egresos: { concepto: string; monto: number }[];
|
||||
totalIngresos: number;
|
||||
totalEgresos: number;
|
||||
utilidadBruta: number;
|
||||
impuestos: number;
|
||||
utilidadNeta: number;
|
||||
}
|
||||
|
||||
export interface FlujoEfectivo {
|
||||
periodo: { inicio: string; fin: string };
|
||||
saldoInicial: number;
|
||||
entradas: { concepto: string; monto: number }[];
|
||||
salidas: { concepto: string; monto: number }[];
|
||||
totalEntradas: number;
|
||||
totalSalidas: number;
|
||||
flujoNeto: number;
|
||||
saldoFinal: number;
|
||||
}
|
||||
|
||||
export interface ComparativoPeriodos {
|
||||
periodos: string[];
|
||||
ingresos: number[];
|
||||
egresos: number[];
|
||||
utilidad: number[];
|
||||
variacionIngresos: number;
|
||||
variacionEgresos: number;
|
||||
variacionUtilidad: number;
|
||||
}
|
||||
|
||||
export interface ConcentradoRfc {
|
||||
rfc: string;
|
||||
nombre: string;
|
||||
tipo: 'cliente' | 'proveedor';
|
||||
totalFacturado: number;
|
||||
totalIva: number;
|
||||
cantidadCfdis: number;
|
||||
}
|
||||
|
||||
export interface ReporteFilters {
|
||||
fechaInicio: string;
|
||||
fechaFin: string;
|
||||
tipo?: 'mensual' | 'trimestral' | 'anual';
|
||||
}
|
||||
132
packages/shared/src/types/sat.ts
Normal file
132
packages/shared/src/types/sat.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
// ============================================
|
||||
// FIEL (e.firma) Types
|
||||
// ============================================
|
||||
|
||||
export interface FielUploadRequest {
|
||||
cerFile: string; // Base64
|
||||
keyFile: string; // Base64
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface FielStatus {
|
||||
configured: boolean;
|
||||
rfc?: string;
|
||||
serialNumber?: string;
|
||||
validFrom?: string;
|
||||
validUntil?: string;
|
||||
isExpired?: boolean;
|
||||
daysUntilExpiration?: number;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// SAT Sync Types
|
||||
// ============================================
|
||||
|
||||
export type SatSyncType = 'initial' | 'daily' | 'incremental';
|
||||
export type SatSyncStatus = 'pending' | 'running' | 'completed' | 'failed';
|
||||
export type CfdiSyncType = 'emitidos' | 'recibidos';
|
||||
|
||||
export interface SatSyncJob {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
type: SatSyncType;
|
||||
status: SatSyncStatus;
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
cfdiType?: CfdiSyncType;
|
||||
satRequestId?: string;
|
||||
satPackageIds: string[];
|
||||
cfdisFound: number;
|
||||
cfdisDownloaded: number;
|
||||
cfdisInserted: number;
|
||||
cfdisUpdated: number;
|
||||
progressPercent: number;
|
||||
errorMessage?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
createdAt: string;
|
||||
retryCount: number;
|
||||
}
|
||||
|
||||
export interface SatSyncStatusResponse {
|
||||
hasActiveSync: boolean;
|
||||
currentJob?: SatSyncJob;
|
||||
lastCompletedJob?: SatSyncJob;
|
||||
totalCfdisSynced: number;
|
||||
}
|
||||
|
||||
export interface SatSyncHistoryResponse {
|
||||
jobs: SatSyncJob[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface StartSyncRequest {
|
||||
type?: SatSyncType;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}
|
||||
|
||||
export interface StartSyncResponse {
|
||||
jobId: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// SAT Web Service Types
|
||||
// ============================================
|
||||
|
||||
export interface SatAuthResponse {
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
export interface SatDownloadRequest {
|
||||
rfcSolicitante: string;
|
||||
fechaInicio: Date;
|
||||
fechaFin: Date;
|
||||
tipoSolicitud: 'CFDI' | 'Metadata';
|
||||
tipoComprobante?: 'I' | 'E' | 'T' | 'N' | 'P';
|
||||
rfcEmisor?: string;
|
||||
rfcReceptor?: string;
|
||||
}
|
||||
|
||||
export interface SatDownloadRequestResponse {
|
||||
idSolicitud: string;
|
||||
codEstatus: string;
|
||||
mensaje: string;
|
||||
}
|
||||
|
||||
export interface SatVerifyResponse {
|
||||
codEstatus: string;
|
||||
estadoSolicitud: number; // 1=Aceptada, 2=EnProceso, 3=Terminada, 4=Error, 5=Rechazada, 6=Vencida
|
||||
codigoEstadoSolicitud: string;
|
||||
numeroCfdis: number;
|
||||
mensaje: string;
|
||||
paquetes: string[];
|
||||
}
|
||||
|
||||
export interface SatPackageResponse {
|
||||
paquete: string; // Base64 ZIP
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// SAT Error Codes
|
||||
// ============================================
|
||||
|
||||
export const SAT_STATUS_CODES: Record<string, string> = {
|
||||
'5000': 'Solicitud recibida con éxito',
|
||||
'5002': 'Se agotó el límite de solicitudes',
|
||||
'5004': 'No se encontraron CFDIs',
|
||||
'5005': 'Solicitud duplicada',
|
||||
};
|
||||
|
||||
export const SAT_REQUEST_STATUS: Record<number, string> = {
|
||||
1: 'Aceptada',
|
||||
2: 'En proceso',
|
||||
3: 'Terminada',
|
||||
4: 'Error',
|
||||
5: 'Rechazada',
|
||||
6: 'Vencida',
|
||||
};
|
||||
48
packages/shared/src/types/tenant.ts
Normal file
48
packages/shared/src/types/tenant.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { Plan } from '../constants/plans';
|
||||
|
||||
export interface Tenant {
|
||||
id: string;
|
||||
nombre: string;
|
||||
rfc: string;
|
||||
plan: Plan;
|
||||
databaseName: string;
|
||||
cfdiLimit: number;
|
||||
usersLimit: number;
|
||||
active: boolean;
|
||||
createdAt: Date;
|
||||
expiresAt: Date | null;
|
||||
}
|
||||
|
||||
export interface TenantUsage {
|
||||
cfdiCount: number;
|
||||
cfdiLimit: number;
|
||||
usersCount: number;
|
||||
usersLimit: number;
|
||||
plan: Plan;
|
||||
}
|
||||
|
||||
export interface Subscription {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
plan: Plan;
|
||||
mpPreapprovalId?: string;
|
||||
status: 'pending' | 'authorized' | 'paused' | 'cancelled';
|
||||
amount: number;
|
||||
frequency: 'monthly' | 'yearly';
|
||||
currentPeriodStart?: string;
|
||||
currentPeriodEnd?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
subscriptionId?: string;
|
||||
mpPaymentId?: string;
|
||||
amount: number;
|
||||
status: 'approved' | 'pending' | 'rejected' | 'refunded';
|
||||
paymentMethod?: string;
|
||||
paidAt?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
61
packages/shared/src/types/user.ts
Normal file
61
packages/shared/src/types/user.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import type { Role } from './auth';
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
email: string;
|
||||
nombre: string;
|
||||
role: Role;
|
||||
active: boolean;
|
||||
lastLogin: Date | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface CreateUserRequest {
|
||||
email: string;
|
||||
nombre: string;
|
||||
role: Role;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserRequest {
|
||||
nombre?: string;
|
||||
role?: Role;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface UserInvite {
|
||||
email: string;
|
||||
nombre: string;
|
||||
role: 'contador' | 'visor' | 'auxiliar' | 'supervisor' | 'cliente';
|
||||
supervisorUserId?: string;
|
||||
}
|
||||
|
||||
export interface UserListItem {
|
||||
id: string;
|
||||
email: string;
|
||||
nombre: string;
|
||||
role: Role;
|
||||
active: boolean;
|
||||
lastLogin: string | null;
|
||||
createdAt: string;
|
||||
tenantId?: string;
|
||||
tenantName?: string;
|
||||
}
|
||||
|
||||
export interface UserUpdate {
|
||||
nombre?: string;
|
||||
role?: Role;
|
||||
active?: boolean;
|
||||
tenantId?: string;
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
id: number;
|
||||
userId: string;
|
||||
userName: string;
|
||||
action: string;
|
||||
details: string;
|
||||
ip: string;
|
||||
createdAt: string;
|
||||
}
|
||||
17
packages/shared/tsconfig.json
Normal file
17
packages/shared/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"outDir": "./dist"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
21
packages/vertical-contable/package.json
Normal file
21
packages/vertical-contable/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@horux/vertical-contable",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint src/",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@horux/shared": "workspace:*",
|
||||
"@horux/core": "workspace:*",
|
||||
"facturapi": "^4.14.0",
|
||||
"playwright": "^1.59.0",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
1
packages/vertical-contable/src/index.ts
Normal file
1
packages/vertical-contable/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
17
packages/vertical-contable/tsconfig.json
Normal file
17
packages/vertical-contable/tsconfig.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in New Issue
Block a user