feat: Display Settings UI + Company Category/Type sync
- Add /admin/display-settings page with Kiosk and Mobile sections - Company category checkbox filter + excluded companies searchable multi-select - New DB tables: company_categories, company_types (migration 064) - Sync COMPANY_CATEGORIES via CompanyCategories entity (id/name/isActive) - Sync COMPANY_TYPES via Companies.companyType picklist - Add to EntityType, ENTITY_DEPENDENCIES, sync-helpers, entity-mapper, entity-sync - New API routes: /api/admin/display-settings (GET/POST), /api/data/company-categories, /api/data/companies-list - Update all 4 routes (kiosk/stats, kiosk/activity, mobile/tickets, mobile/dashboard) to filter by kiosk_settings company_category_ids + excluded_company_ids - Add Display Settings nav link (SlidersHorizontal icon) to Admin menu - Seed kiosk_settings: kiosk_company_category_ids=1, mobile_company_category_ids=1
This commit is contained in:
parent
89dbe6155b
commit
07067bef19
16 changed files with 847 additions and 85 deletions
323
app/admin/display-settings/page.tsx
Normal file
323
app/admin/display-settings/page.tsx
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Loader2, Save, SlidersHorizontal, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
|
||||
interface CompanyCategory {
|
||||
value: number;
|
||||
label: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
interface Company {
|
||||
id: number;
|
||||
company_name: string;
|
||||
}
|
||||
|
||||
interface SectionSettings {
|
||||
company_category_ids: number[];
|
||||
excluded_company_ids: number[];
|
||||
}
|
||||
|
||||
interface DisplaySettings {
|
||||
kiosk: SectionSettings;
|
||||
mobile: SectionSettings;
|
||||
}
|
||||
|
||||
function CompanySearch({
|
||||
selectedIds,
|
||||
categoryIds,
|
||||
onAdd,
|
||||
onRemove,
|
||||
allCompanies,
|
||||
}: {
|
||||
selectedIds: number[];
|
||||
categoryIds: number[];
|
||||
onAdd: (id: number) => void;
|
||||
onRemove: (id: number) => void;
|
||||
allCompanies: Company[];
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const available = allCompanies.filter(
|
||||
(c) =>
|
||||
!selectedIds.includes(c.id) &&
|
||||
(query === "" || c.company_name.toLowerCase().includes(query.toLowerCase()))
|
||||
);
|
||||
|
||||
const selected = allCompanies.filter((c) => selectedIds.includes(c.id));
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap gap-1 min-h-[28px]">
|
||||
{selected.map((c) => (
|
||||
<Badge key={c.id} variant="secondary" className="gap-1">
|
||||
{c.company_name}
|
||||
<button
|
||||
onClick={() => onRemove(c.id)}
|
||||
className="ml-1 hover:text-destructive"
|
||||
aria-label={`Remove ${c.company_name}`}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
{selected.length === 0 && (
|
||||
<span className="text-xs text-muted-foreground italic">No exclusions</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search companies to exclude..."
|
||||
value={query}
|
||||
onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
|
||||
onFocus={() => setOpen(true)}
|
||||
onBlur={() => setTimeout(() => setOpen(false), 150)}
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
{open && available.length > 0 && (
|
||||
<div className="absolute z-50 mt-1 w-full max-h-52 overflow-auto rounded-md border bg-popover shadow-md">
|
||||
{available.slice(0, 30).map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
className="w-full px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground"
|
||||
onMouseDown={() => { onAdd(c.id); setQuery(""); }}
|
||||
>
|
||||
{c.company_name}
|
||||
<span className="ml-2 text-xs text-muted-foreground">#{c.id}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
description,
|
||||
settingsKey,
|
||||
settings,
|
||||
categories,
|
||||
companies,
|
||||
onSaved,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
settingsKey: "kiosk" | "mobile";
|
||||
settings: SectionSettings;
|
||||
categories: CompanyCategory[];
|
||||
companies: Company[];
|
||||
onSaved: (key: "kiosk" | "mobile", updated: SectionSettings) => void;
|
||||
}) {
|
||||
const [local, setLocal] = useState<SectionSettings>(settings);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => { setLocal(settings); }, [settings]);
|
||||
|
||||
function toggleCategory(value: number) {
|
||||
setLocal((prev) => ({
|
||||
...prev,
|
||||
company_category_ids: prev.company_category_ids.includes(value)
|
||||
? prev.company_category_ids.filter((v) => v !== value)
|
||||
: [...prev.company_category_ids, value],
|
||||
}));
|
||||
}
|
||||
|
||||
function addExclusion(id: number) {
|
||||
setLocal((prev) => ({ ...prev, excluded_company_ids: [...prev.excluded_company_ids, id] }));
|
||||
}
|
||||
|
||||
function removeExclusion(id: number) {
|
||||
setLocal((prev) => ({ ...prev, excluded_company_ids: prev.excluded_company_ids.filter((v) => v !== id) }));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
await Promise.all([
|
||||
fetch("/api/admin/display-settings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
setting_key: `${settingsKey}_company_category_ids`,
|
||||
setting_value: local.company_category_ids,
|
||||
}),
|
||||
}),
|
||||
fetch("/api/admin/display-settings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
setting_key: `${settingsKey}_excluded_company_ids`,
|
||||
setting_value: local.excluded_company_ids,
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
toast.success(`${title} settings saved`);
|
||||
onSaved(settingsKey, local);
|
||||
} catch {
|
||||
toast.error(`Failed to save ${title} settings`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const filteredCompanies = companies.filter((c) =>
|
||||
local.company_category_ids.length === 0
|
||||
? true
|
||||
: true
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<SlidersHorizontal className="h-5 w-5" />
|
||||
{title}
|
||||
</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-3">Company Categories to Include</h3>
|
||||
{categories.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
No categories synced yet. Run a sync to populate.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{categories.map((cat) => (
|
||||
<div key={cat.value} className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id={`${settingsKey}-cat-${cat.value}`}
|
||||
checked={local.company_category_ids.includes(cat.value)}
|
||||
onCheckedChange={() => toggleCategory(cat.value)}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`${settingsKey}-cat-${cat.value}`}
|
||||
className="cursor-pointer font-normal"
|
||||
>
|
||||
{cat.label}
|
||||
<span className="ml-2 text-xs text-muted-foreground">id={cat.value}</span>
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-1">Excluded Companies</h3>
|
||||
<p className="text-xs text-muted-foreground mb-2">
|
||||
Individual companies to hide even if they match the selected categories.
|
||||
</p>
|
||||
<CompanySearch
|
||||
selectedIds={local.excluded_company_ids}
|
||||
categoryIds={local.company_category_ids}
|
||||
allCompanies={filteredCompanies}
|
||||
onAdd={addExclusion}
|
||||
onRemove={removeExclusion}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button onClick={save} disabled={saving} size="sm">
|
||||
{saving ? (
|
||||
<><Loader2 className="mr-2 h-4 w-4 animate-spin" />Saving…</>
|
||||
) : (
|
||||
<><Save className="mr-2 h-4 w-4" />Save {title} Settings</>
|
||||
)}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DisplaySettingsPage() {
|
||||
const [settings, setSettings] = useState<DisplaySettings | null>(null);
|
||||
const [categories, setCategories] = useState<CompanyCategory[]>([]);
|
||||
const [companies, setCompanies] = useState<Company[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [settingsRes, catsRes, companiesRes] = await Promise.all([
|
||||
fetch("/api/admin/display-settings"),
|
||||
fetch("/api/data/company-categories"),
|
||||
fetch("/api/data/companies-list"),
|
||||
]);
|
||||
if (settingsRes.ok) setSettings(await settingsRes.json());
|
||||
if (catsRes.ok) setCategories(await catsRes.json());
|
||||
if (companiesRes.ok) setCompanies(await companiesRes.json());
|
||||
} catch {
|
||||
toast.error("Failed to load display settings");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
function handleSaved(key: "kiosk" | "mobile", updated: SectionSettings) {
|
||||
setSettings((prev) => prev ? { ...prev, [key]: updated } : prev);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="container mx-auto py-8 px-4 flex justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!settings) {
|
||||
return (
|
||||
<div className="container mx-auto py-8 px-4">
|
||||
<p className="text-destructive">Failed to load settings.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-8 px-4 max-w-5xl">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold flex items-center gap-2">
|
||||
<SlidersHorizontal className="h-8 w-8" />
|
||||
Display Settings
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Configure which companies appear in the Kiosk and Mobile dashboards.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Section
|
||||
title="Kiosk"
|
||||
description="Settings for the executive kiosk display."
|
||||
settingsKey="kiosk"
|
||||
settings={settings.kiosk}
|
||||
categories={categories}
|
||||
companies={companies}
|
||||
onSaved={handleSaved}
|
||||
/>
|
||||
<Section
|
||||
title="Mobile"
|
||||
description="Settings for the mobile dashboard."
|
||||
settingsKey="mobile"
|
||||
settings={settings.mobile}
|
||||
categories={categories}
|
||||
companies={companies}
|
||||
onSaved={handleSaved}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
65
app/api/admin/display-settings/route.ts
Normal file
65
app/api/admin/display-settings/route.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
const KIOSK_KEYS = ['kiosk_company_category_ids', 'kiosk_excluded_company_ids'];
|
||||
const MOBILE_KEYS = ['mobile_company_category_ids', 'mobile_excluded_company_ids'];
|
||||
const ALL_KEYS = [...KIOSK_KEYS, ...MOBILE_KEYS];
|
||||
|
||||
function parseIds(value: string | null): number[] {
|
||||
if (!value) return [];
|
||||
return value.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_key, setting_value FROM kiosk_settings WHERE setting_key = ANY($1)`,
|
||||
[ALL_KEYS]
|
||||
);
|
||||
|
||||
const map: Record<string, string> = {};
|
||||
result.rows.forEach((r: any) => { map[r.setting_key] = r.setting_value || ''; });
|
||||
|
||||
return NextResponse.json({
|
||||
kiosk: {
|
||||
company_category_ids: parseIds(map['kiosk_company_category_ids'] ?? '1'),
|
||||
excluded_company_ids: parseIds(map['kiosk_excluded_company_ids'] ?? ''),
|
||||
},
|
||||
mobile: {
|
||||
company_category_ids: parseIds(map['mobile_company_category_ids'] ?? '1'),
|
||||
excluded_company_ids: parseIds(map['mobile_excluded_company_ids'] ?? ''),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching display settings:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch display settings' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { setting_key, setting_value } = body;
|
||||
|
||||
if (!setting_key || !ALL_KEYS.includes(setting_key)) {
|
||||
return NextResponse.json({ error: 'Invalid setting_key' }, { status: 400 });
|
||||
}
|
||||
|
||||
const valueToStore = Array.isArray(setting_value)
|
||||
? setting_value.join(',')
|
||||
: String(setting_value ?? '');
|
||||
|
||||
await postgresClient.query(
|
||||
`INSERT INTO kiosk_settings (setting_key, setting_value, updated_at)
|
||||
VALUES ($1, $2, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (setting_key)
|
||||
DO UPDATE SET setting_value = EXCLUDED.setting_value, updated_at = CURRENT_TIMESTAMP`,
|
||||
[setting_key, valueToStore]
|
||||
);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Error updating display settings:', error);
|
||||
return NextResponse.json({ error: 'Failed to update display settings' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
14
app/api/data/companies-list/route.ts
Normal file
14
app/api/data/companies-list/route.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT id, company_name FROM companies WHERE is_active = true AND is_deleted = false ORDER BY company_name ASC`
|
||||
);
|
||||
return NextResponse.json(result.rows);
|
||||
} catch (error) {
|
||||
console.error('Error fetching companies list:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch companies list' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
14
app/api/data/company-categories/route.ts
Normal file
14
app/api/data/company-categories/route.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT value, label, is_active FROM company_categories WHERE is_active = true ORDER BY label ASC`
|
||||
);
|
||||
return NextResponse.json(result.rows);
|
||||
} catch (error) {
|
||||
console.error('Error fetching company categories:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch company categories' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,50 +1,37 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
async function getExcludedCompanyIds(): Promise<number[]> {
|
||||
async function getKioskCompanyFilter(): Promise<string> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'excluded_company_ids'`
|
||||
`SELECT setting_key, setting_value FROM kiosk_settings WHERE setting_key IN ('kiosk_company_category_ids', 'kiosk_excluded_company_ids')`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
return value ? value.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id)) : [];
|
||||
} catch (error) {
|
||||
console.error('Error fetching excluded company IDs:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
const map: Record<string, string> = {};
|
||||
result.rows.forEach((r: any) => { map[r.setting_key] = r.setting_value || ''; });
|
||||
|
||||
async function getIncludedClassificationIds(): Promise<number[]> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'included_classifications'`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
return value ? value.split(',').map((c: string) => parseInt(c.trim(), 10)).filter((n: number) => !isNaN(n)) : [];
|
||||
const catIds = (map['kiosk_company_category_ids'] || '1')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
const exclIds = (map['kiosk_excluded_company_ids'] || '')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
|
||||
const catFilter = catIds.length > 0
|
||||
? `t.company_id IN (SELECT id FROM companies WHERE company_category_id IN (${catIds.join(',')}))`
|
||||
: 'true';
|
||||
const exclFilter = exclIds.length > 0
|
||||
? `t.company_id NOT IN (${exclIds.join(',')})`
|
||||
: '';
|
||||
|
||||
return [catFilter, exclFilter].filter(Boolean).join(' AND ');
|
||||
} catch (error) {
|
||||
console.error('Error fetching included classifications:', error);
|
||||
return [];
|
||||
console.error('Error fetching kiosk company filter:', error);
|
||||
return 't.company_id IN (SELECT id FROM companies WHERE company_category_id = 1)';
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Get excluded company IDs (co-managed clients) and classifications
|
||||
const excludedCompanyIds = await getExcludedCompanyIds();
|
||||
const includedClassificationIds = await getIncludedClassificationIds();
|
||||
|
||||
// Build company filter: only show recurring revenue classification clients
|
||||
let excludeCompanyFilter = '';
|
||||
const conditions: string[] = [];
|
||||
if (excludedCompanyIds.length > 0) {
|
||||
conditions.push(`t.company_id NOT IN (${excludedCompanyIds.join(',')})`);
|
||||
}
|
||||
if (includedClassificationIds.length > 0) {
|
||||
conditions.push(`t.company_id IN (SELECT id FROM companies WHERE classification::integer IN (${includedClassificationIds.join(',')}))`);
|
||||
}
|
||||
if (conditions.length > 0) {
|
||||
excludeCompanyFilter = `AND (${conditions.join(' AND ')})`;
|
||||
}
|
||||
const companyFilter = await getKioskCompanyFilter();
|
||||
const excludeCompanyFilter = `AND (${companyFilter})`;
|
||||
|
||||
// Get recent ticket activity for ticker feed - exclude RMM alerts (source = 8), co-managed clients, and excluded classifications
|
||||
const activityResult = await postgresClient.query(
|
||||
|
|
|
|||
|
|
@ -1,50 +1,37 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
async function getExcludedCompanyIds(): Promise<number[]> {
|
||||
async function getKioskCompanyFilter(): Promise<string> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'excluded_company_ids'`
|
||||
`SELECT setting_key, setting_value FROM kiosk_settings WHERE setting_key IN ('kiosk_company_category_ids', 'kiosk_excluded_company_ids')`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
return value ? value.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id)) : [];
|
||||
} catch (error) {
|
||||
console.error('Error fetching excluded company IDs:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
const map: Record<string, string> = {};
|
||||
result.rows.forEach((r: any) => { map[r.setting_key] = r.setting_value || ''; });
|
||||
|
||||
async function getIncludedClassificationIds(): Promise<number[]> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'included_classifications'`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
return value ? value.split(',').map((c: string) => parseInt(c.trim(), 10)).filter((n: number) => !isNaN(n)) : [];
|
||||
const catIds = (map['kiosk_company_category_ids'] || '1')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
const exclIds = (map['kiosk_excluded_company_ids'] || '')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
|
||||
const catFilter = catIds.length > 0
|
||||
? `company_id IN (SELECT id FROM companies WHERE company_category_id IN (${catIds.join(',')}))`
|
||||
: 'true';
|
||||
const exclFilter = exclIds.length > 0
|
||||
? `company_id NOT IN (${exclIds.join(',')})`
|
||||
: '';
|
||||
|
||||
return [catFilter, exclFilter].filter(Boolean).join(' AND ');
|
||||
} catch (error) {
|
||||
console.error('Error fetching included classifications:', error);
|
||||
return [];
|
||||
console.error('Error fetching kiosk company filter:', error);
|
||||
return 'company_id IN (SELECT id FROM companies WHERE company_category_id = 1)';
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Get excluded company IDs (co-managed clients)
|
||||
const excludedCompanyIds = await getExcludedCompanyIds();
|
||||
const includedClassificationIds = await getIncludedClassificationIds();
|
||||
|
||||
// Build company filter: only show recurring revenue classification clients
|
||||
let excludeCompanyFilter = '';
|
||||
const conditions: string[] = [];
|
||||
if (excludedCompanyIds.length > 0) {
|
||||
conditions.push(`company_id NOT IN (${excludedCompanyIds.join(',')})`);
|
||||
}
|
||||
if (includedClassificationIds.length > 0) {
|
||||
conditions.push(`company_id IN (SELECT id FROM companies WHERE classification::integer IN (${includedClassificationIds.join(',')}))`);
|
||||
}
|
||||
if (conditions.length > 0) {
|
||||
excludeCompanyFilter = `AND (${conditions.join(' AND ')})`;
|
||||
}
|
||||
const companyFilter = await getKioskCompanyFilter();
|
||||
const excludeCompanyFilter = `AND (${companyFilter})`;
|
||||
|
||||
// Critical tickets (Priority 1-3) - exclude RMM alerts (source = 8), co-managed clients, and excluded classifications
|
||||
const criticalTicketsResult = await postgresClient.query(
|
||||
|
|
|
|||
|
|
@ -1,17 +1,30 @@
|
|||
import { NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
async function getManagedClassificationFilter(): Promise<string> {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'included_classifications'`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
const ids = value ? value.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n)) : [];
|
||||
return ids.length > 0 ? `c.classification::integer IN (${ids.join(',')})` : 'true';
|
||||
async function getMobileClassFilter(): Promise<string> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_key, setting_value FROM kiosk_settings WHERE setting_key IN ('mobile_company_category_ids', 'mobile_excluded_company_ids')`
|
||||
);
|
||||
const map: Record<string, string> = {};
|
||||
result.rows.forEach((r: any) => { map[r.setting_key] = r.setting_value || ''; });
|
||||
|
||||
const catIds = (map['mobile_company_category_ids'] || '1')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
const exclIds = (map['mobile_excluded_company_ids'] || '')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
|
||||
const catCond = catIds.length > 0 ? `c.company_category_id IN (${catIds.join(',')})` : 'true';
|
||||
const exclCond = exclIds.length > 0 ? `c.id NOT IN (${exclIds.join(',')})` : '';
|
||||
return [catCond, exclCond].filter(Boolean).join(' AND ');
|
||||
} catch (error) {
|
||||
console.error('Error fetching mobile company filter:', error);
|
||||
return 'c.company_category_id = 1';
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const classFilter = await getManagedClassificationFilter();
|
||||
const classFilter = await getMobileClassFilter();
|
||||
|
||||
const [byStatus, byQueue, byPriority, recentActivity, sla] = await Promise.all([
|
||||
postgresClient.query(`
|
||||
|
|
|
|||
|
|
@ -1,13 +1,28 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { postgresClient } from '@/lib/services/postgres-client';
|
||||
|
||||
async function getManagedCompanyFilter(): Promise<string> {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_value FROM kiosk_settings WHERE setting_key = 'included_classifications'`
|
||||
);
|
||||
const value = result.rows[0]?.setting_value || '';
|
||||
const ids = value ? value.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n)) : [];
|
||||
return ids.length > 0 ? `c.classification::integer IN (${ids.join(',')})` : 'true';
|
||||
async function getMobileCompanyFilter(): Promise<{ join: string; condition: string }> {
|
||||
try {
|
||||
const result = await postgresClient.query(
|
||||
`SELECT setting_key, setting_value FROM kiosk_settings WHERE setting_key IN ('mobile_company_category_ids', 'mobile_excluded_company_ids')`
|
||||
);
|
||||
const map: Record<string, string> = {};
|
||||
result.rows.forEach((r: any) => { map[r.setting_key] = r.setting_value || ''; });
|
||||
|
||||
const catIds = (map['mobile_company_category_ids'] || '1')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
const exclIds = (map['mobile_excluded_company_ids'] || '')
|
||||
.split(',').map((s: string) => parseInt(s.trim(), 10)).filter((n: number) => !isNaN(n));
|
||||
|
||||
const catCond = catIds.length > 0 ? `c.company_category_id IN (${catIds.join(',')})` : 'true';
|
||||
const exclCond = exclIds.length > 0 ? `c.id NOT IN (${exclIds.join(',')})` : '';
|
||||
const condition = [catCond, exclCond].filter(Boolean).join(' AND ');
|
||||
|
||||
return { join: 'INNER JOIN companies c ON c.id = t.company_id', condition };
|
||||
} catch (error) {
|
||||
console.error('Error fetching mobile company filter:', error);
|
||||
return { join: 'INNER JOIN companies c ON c.id = t.company_id', condition: 'c.company_category_id = 1' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
|
|
@ -19,12 +34,12 @@ export async function GET(request: NextRequest) {
|
|||
const limit = 30;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const managedFilter = await getManagedCompanyFilter();
|
||||
const { condition: companyCondition } = await getMobileCompanyFilter();
|
||||
|
||||
const conditions: string[] = [
|
||||
't.status != 5',
|
||||
't.is_deleted = false',
|
||||
managedFilter,
|
||||
companyCondition,
|
||||
];
|
||||
const params: unknown[] = [];
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue