Coeinterns commited on
Commit
27f1135
Β·
unverified Β·
2 Parent(s): df5c3a1c58f0d0

Merge pull request #2 from coeinterns/develop

Browse files
api_server.py CHANGED
@@ -168,6 +168,9 @@ app.include_router(admin_rules_router)
168
  from routers.rule_requests import router as rule_requests_router
169
  app.include_router(rule_requests_router)
170
 
 
 
 
171
 
172
  # ===== Health & Info =====
173
 
 
168
  from routers.rule_requests import router as rule_requests_router
169
  app.include_router(rule_requests_router)
170
 
171
+ # 18. Practices Router
172
+ from routers.practices import router as practices_router
173
+ app.include_router(practices_router)
174
 
175
  # ===== Health & Info =====
176
 
auth/rule_models.py CHANGED
@@ -26,7 +26,7 @@ against categories. Only the export/report layer needs groups.
26
  """
27
 
28
  from __future__ import annotations
29
-
30
  import uuid
31
  from datetime import datetime
32
  from typing import Optional
@@ -460,3 +460,66 @@ class RuleChangeRequest(Base):
460
  "created_at": self.created_at.isoformat() if self.created_at else None,
461
  "updated_at": self.updated_at.isoformat() if self.updated_at else None,
462
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
27
 
28
  from __future__ import annotations
29
+ from sqlalchemy import UniqueConstraint
30
  import uuid
31
  from datetime import datetime
32
  from typing import Optional
 
460
  "created_at": self.created_at.isoformat() if self.created_at else None,
461
  "updated_at": self.updated_at.isoformat() if self.updated_at else None,
462
  }
463
+
464
+ class Practice(Base):
465
+ """
466
+ A CA firm / mortgage practice that uses BeFree.
467
+ Replaces the MOCK_PRACTICES hardcoded array on the frontend.
468
+ """
469
+ __tablename__ = "practices"
470
+
471
+ id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
472
+ name = Column(String(200), unique=True, nullable=False, index=True)
473
+ is_active = Column(Boolean, nullable=False, default=True)
474
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
475
+ updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
476
+ created_by = Column(String(200), nullable=True)
477
+
478
+ overrides = relationship("PracticeCategoryOverride", back_populates="practice")
479
+
480
+ def to_dict(self) -> dict:
481
+ return {
482
+ "id": self.id,
483
+ "name": self.name,
484
+ "is_active": self.is_active,
485
+ "created_at": self.created_at.isoformat() if self.created_at else None,
486
+ }
487
+
488
+
489
+ class PracticeCategoryOverride(Base):
490
+ """
491
+ Per-practice override: moves a category into a different group
492
+ at classification time, without touching global category data.
493
+
494
+ override_group_id = NULL means exclude from report entirely.
495
+ """
496
+ __tablename__ = "practice_category_overrides"
497
+
498
+ id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
499
+ practice_id = Column(String, ForeignKey("practices.id", ondelete="CASCADE"), nullable=False, index=True)
500
+ category_id = Column(String, ForeignKey("classification_categories.id", ondelete="CASCADE"), nullable=False, index=True)
501
+ override_group_id = Column(String, ForeignKey("classification_groups.id", ondelete="SET NULL"), nullable=True)
502
+ is_active = Column(Boolean, nullable=False, default=True)
503
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
504
+ updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
505
+ created_by = Column(String(200), nullable=True)
506
+
507
+ practice = relationship("Practice", back_populates="overrides")
508
+ category = relationship("ClassificationCategory")
509
+ override_group = relationship("ClassificationGroup")
510
+
511
+ __table_args__ = (
512
+ UniqueConstraint("practice_id", "category_id", name="uq_practice_category_override"),
513
+ )
514
+
515
+ def to_dict(self) -> dict:
516
+ return {
517
+ "id": self.id,
518
+ "practice_id": self.practice_id,
519
+ "practice_name": self.practice.name if self.practice else None,
520
+ "category_id": self.category_id,
521
+ "category_name": self.category.name if self.category else None,
522
+ "override_group_id": self.override_group_id,
523
+ "override_group": self.override_group.name if self.override_group else None,
524
+ "is_active": self.is_active,
525
+ }
befree-frontend/features/review/ReviewFeature.tsx CHANGED
@@ -4,11 +4,11 @@ import { useParams, useSearchParams } from 'next/navigation';
4
  import { useEffect, Suspense, useMemo, useState, useRef } from 'react';
5
  import { useRouter } from 'next/navigation';
6
  import { motion } from 'framer-motion';
7
- import { useReviewSession, useTransactions, useReviewMetrics, statementKeys, useFinaliseStatement, useSettings } from '@/hooks/useStatementAPI';
8
  import { useQueryClient } from '@tanstack/react-query';
9
  import { useToast } from '@/components/ui/use-toast';
10
  import { Button } from '@/components/ui/button';
11
- import { Send, Loader2, Columns } from 'lucide-react';
12
  import { useBeFreeStore } from '@/store/befree-store';
13
  import { PDFViewer } from '@/components/pdf/PDFViewer';
14
  import { TransactionTable } from '@/components/tables/TransactionTable';
@@ -29,6 +29,42 @@ function ReviewFeatureInner() {
29
  const finaliseMutation = useFinaliseStatement(statementId);
30
  const { data: settingsData } = useSettings();
31
  const [extractLast3Months, setExtractLast3Months] = useState(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  useEffect(() => {
34
  if (settingsData) {
@@ -123,7 +159,10 @@ function ReviewFeatureInner() {
123
 
124
  const handleFinalise = async () => {
125
  try {
126
- await finaliseMutation.mutateAsync({ extract_last_3_months: extractLast3Months });
 
 
 
127
  toast({ title: 'Statement sent to classification', variant: 'success' });
128
  router.push(`/statements/${statementId}/classify`);
129
  } catch (error) {
@@ -233,6 +272,97 @@ function ReviewFeatureInner() {
233
  </label>
234
  </div>
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  <p className="text-gray-600 text-xs leading-relaxed border-t border-slate-100 pt-3">
237
  Your {metricsData?.totalTransactions ?? visibleTransactions.length} corrected transactions will be locked and sent to the classification pipeline. You won't be able to edit the extraction table after this.
238
  </p>
 
4
  import { useEffect, Suspense, useMemo, useState, useRef } from 'react';
5
  import { useRouter } from 'next/navigation';
6
  import { motion } from 'framer-motion';
7
+ import { useReviewSession, useTransactions, useReviewMetrics, statementKeys, useFinaliseStatement, useSettings, usePractices } from '@/hooks/useStatementAPI';
8
  import { useQueryClient } from '@tanstack/react-query';
9
  import { useToast } from '@/components/ui/use-toast';
10
  import { Button } from '@/components/ui/button';
11
+ import { Send, Loader2, Columns, ChevronDown } from 'lucide-react';
12
  import { useBeFreeStore } from '@/store/befree-store';
13
  import { PDFViewer } from '@/components/pdf/PDFViewer';
14
  import { TransactionTable } from '@/components/tables/TransactionTable';
 
29
  const finaliseMutation = useFinaliseStatement(statementId);
30
  const { data: settingsData } = useSettings();
31
  const [extractLast3Months, setExtractLast3Months] = useState(true);
32
+ const [practiceSpecific, setPracticeSpecific] = useState(false);
33
+ const [selectedPractices, setSelectedPractices] = useState<string[]>([]);
34
+ const [practiceSearch, setPracticeSearch] = useState('');
35
+ const [isPracticeDropdownOpen, setIsPracticeDropdownOpen] = useState(false);
36
+
37
+ const { data: practicesData, isLoading: practicesLoading } = usePractices();
38
+ const practices = practicesData?.practices ?? [];
39
+
40
+ const filteredPractices = practices.filter((p) =>
41
+ p.name.toLowerCase().includes(practiceSearch.toLowerCase())
42
+ );
43
+
44
+ const togglePractice = (id: string) => {
45
+ setSelectedPractices((prev) =>
46
+ prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id]
47
+ );
48
+ };
49
+
50
+ const selectedPracticeNames = practices
51
+ .filter((p) => selectedPractices.includes(p.id))
52
+ .map((p) => p.name);
53
+
54
+ const practiceDropdownRef = useRef<HTMLDivElement>(null);
55
+
56
+ useEffect(() => {
57
+ const handleClickOutside = (e: MouseEvent) => {
58
+ if (practiceDropdownRef.current && !practiceDropdownRef.current.contains(e.target as Node)) {
59
+ setIsPracticeDropdownOpen(false);
60
+ setPracticeSearch('');
61
+ }
62
+ };
63
+ if (isPracticeDropdownOpen) {
64
+ document.addEventListener('mousedown', handleClickOutside);
65
+ }
66
+ return () => document.removeEventListener('mousedown', handleClickOutside);
67
+ }, [isPracticeDropdownOpen]);
68
 
69
  useEffect(() => {
70
  if (settingsData) {
 
159
 
160
  const handleFinalise = async () => {
161
  try {
162
+ await finaliseMutation.mutateAsync({
163
+ extract_last_3_months: extractLast3Months,
164
+ practice_ids: practiceSpecific ? selectedPractices : [],
165
+ });
166
  toast({ title: 'Statement sent to classification', variant: 'success' });
167
  router.push(`/statements/${statementId}/classify`);
168
  } catch (error) {
 
272
  </label>
273
  </div>
274
 
275
+ {/* Practice Specific Toggle */}
276
+ <div className="border-t border-slate-100 pt-3">
277
+ <div className="flex items-center justify-between">
278
+ <div>
279
+ <span className="text-sm font-semibold text-slate-800">Practice Specific</span>
280
+ <p className="text-xs text-gray-500 mt-0.5">
281
+ Restrict classification to selected practices only.
282
+ </p>
283
+ </div>
284
+ <button
285
+ type="button"
286
+ role="switch"
287
+ aria-checked={practiceSpecific}
288
+ onClick={() => {
289
+ setPracticeSpecific(!practiceSpecific);
290
+ if (practiceSpecific) {
291
+ setSelectedPractices([]);
292
+ setIsPracticeDropdownOpen(false);
293
+ setPracticeSearch('');
294
+ }
295
+ }}
296
+ className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-navy focus:ring-offset-2 ${
297
+ practiceSpecific ? 'bg-navy' : 'bg-gray-200'
298
+ }`}
299
+ >
300
+ <span
301
+ className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-lg ring-0 transition-transform duration-200 ease-in-out ${
302
+ practiceSpecific ? 'translate-x-5' : 'translate-x-0'
303
+ }`}
304
+ />
305
+ </button>
306
+ </div>
307
+
308
+ {/* Practices Dropdown */}
309
+ {practiceSpecific && (
310
+ <div className="mt-3 animate-in fade-in slide-in-from-top-1 duration-200" ref={practiceDropdownRef}>
311
+ <p className="text-xs font-medium text-slate-600 mb-1.5">Select practices:</p>
312
+ <div className="relative">
313
+ <button
314
+ type="button"
315
+ onClick={() => setIsPracticeDropdownOpen(!isPracticeDropdownOpen)}
316
+ className="flex h-9 w-full items-center justify-between rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-subtle focus:outline-none focus:ring-2 focus:ring-primary"
317
+ >
318
+ <span className={selectedPracticeNames.length ? 'text-slate-800' : 'text-gray-400'}>
319
+ {selectedPracticeNames.length
320
+ ? selectedPracticeNames.join(', ')
321
+ : 'Choose practices...'}
322
+ </span>
323
+ <ChevronDown className={`h-4 w-4 opacity-50 transition-transform ${isPracticeDropdownOpen ? 'rotate-180' : ''}`} />
324
+ </button>
325
+ {isPracticeDropdownOpen && (
326
+ <div className="absolute z-50 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-elevated animate-in fade-in slide-in-from-top-1 duration-150">
327
+ <div className="p-1.5">
328
+ <input
329
+ type="text"
330
+ placeholder="Search practices..."
331
+ value={practiceSearch}
332
+ onChange={(e) => setPracticeSearch(e.target.value)}
333
+ className="w-full rounded-md border border-gray-200 bg-slate-50 px-3 py-1.5 text-sm outline-none focus:ring-2 focus:ring-navy placeholder:text-gray-400"
334
+ autoFocus
335
+ />
336
+ </div>
337
+ <div className="max-h-40 overflow-y-auto p-1">
338
+ {practicesLoading ? (
339
+ <p className="px-3 py-2 text-xs text-gray-400">Loading...</p>
340
+ ) : filteredPractices.length === 0 ? (
341
+ <p className="px-3 py-2 text-xs text-gray-400">No practices found.</p>
342
+ ) : (
343
+ filteredPractices.map((practice) => (
344
+ <label
345
+ key={practice.id}
346
+ className="flex items-center gap-2.5 cursor-pointer select-none rounded-sm px-2 py-1.5 hover:bg-gray-100"
347
+ >
348
+ <input
349
+ type="checkbox"
350
+ checked={selectedPractices.includes(practice.id)}
351
+ onChange={() => togglePractice(practice.id)}
352
+ className="w-4 h-4 rounded border-gray-300 text-navy focus:ring-navy"
353
+ />
354
+ <span className="text-sm text-slate-700">{practice.name}</span>
355
+ </label>
356
+ ))
357
+ )}
358
+ </div>
359
+ </div>
360
+ )}
361
+ </div>
362
+ </div>
363
+ )}
364
+ </div>
365
+
366
  <p className="text-gray-600 text-xs leading-relaxed border-t border-slate-100 pt-3">
367
  Your {metricsData?.totalTransactions ?? visibleTransactions.length} corrected transactions will be locked and sent to the classification pipeline. You won't be able to edit the extraction table after this.
368
  </p>
befree-frontend/hooks/useStatementAPI.ts CHANGED
@@ -114,6 +114,15 @@ export const useSettings = (enabled = true) => {
114
  });
115
  };
116
 
 
 
 
 
 
 
 
 
 
117
  export const useReviewMetrics = (statementId: string | null, enabled = true) => {
118
  return useQuery({
119
  queryKey: statementId ? statementKeys.reviewMetrics(statementId) : ['null'],
@@ -348,7 +357,7 @@ export const useClassifyStatement = (statementId: string) => {
348
  export const useFinaliseStatement = (statementId: string) => {
349
  const queryClient = useQueryClient();
350
  return useMutation({
351
- mutationFn: (payload?: { extract_last_3_months: boolean }) =>
352
  apiClient.finaliseStatement(statementId, payload),
353
  onSuccess: () => {
354
  queryClient.invalidateQueries({ queryKey: statementKeys.detail(statementId) });
 
114
  });
115
  };
116
 
117
+ export const usePractices = (enabled = true) => {
118
+ return useQuery<{ practices: { id: string; name: string }[] }>({
119
+ queryKey: ['practices'],
120
+ queryFn: () => apiClient.getPractices(),
121
+ enabled,
122
+ staleTime: Infinity,
123
+ });
124
+ };
125
+
126
  export const useReviewMetrics = (statementId: string | null, enabled = true) => {
127
  return useQuery({
128
  queryKey: statementId ? statementKeys.reviewMetrics(statementId) : ['null'],
 
357
  export const useFinaliseStatement = (statementId: string) => {
358
  const queryClient = useQueryClient();
359
  return useMutation({
360
+ mutationFn: (payload?: { extract_last_3_months: boolean; practice_ids?: string[] }) =>
361
  apiClient.finaliseStatement(statementId, payload),
362
  onSuccess: () => {
363
  queryClient.invalidateQueries({ queryKey: statementKeys.detail(statementId) });
befree-frontend/services/api-client.ts CHANGED
@@ -280,7 +280,7 @@ export const apiClient = {
280
  classifyStatement: (statementId: string) =>
281
  api.post(`${BASE}/statements/${statementId}/classify`).then((r) => r.data),
282
 
283
- finaliseStatement: (statementId: string, payload?: { extract_last_3_months: boolean }) =>
284
  api.post(`${BASE}/statements/${statementId}/finalise`, payload).then((r) => r.data),
285
 
286
  getClassifyStatus: (statementId: string) =>
@@ -434,4 +434,8 @@ export const apiClient = {
434
 
435
  deleteRuleRequest: (id: string) =>
436
  api.delete(`${BASE}/rule-requests/${id}`).then((r) => r.data),
 
 
 
 
437
  };
 
280
  classifyStatement: (statementId: string) =>
281
  api.post(`${BASE}/statements/${statementId}/classify`).then((r) => r.data),
282
 
283
+ finaliseStatement: (statementId: string, payload?: { extract_last_3_months: boolean; practice_ids?: string[] }) =>
284
  api.post(`${BASE}/statements/${statementId}/finalise`, payload).then((r) => r.data),
285
 
286
  getClassifyStatus: (statementId: string) =>
 
434
 
435
  deleteRuleRequest: (id: string) =>
436
  api.delete(`${BASE}/rule-requests/${id}`).then((r) => r.data),
437
+
438
+ // ── Practices ──────────────────────────────────────────────────────────
439
+ getPractices: () =>
440
+ api.get('/api/practices').then((r) => r.data as { practices: { id: string; name: string }[] }),
441
  };
models/admin_models.py CHANGED
@@ -3,6 +3,7 @@ from pydantic import BaseModel
3
 
4
  class FinalisePayload(BaseModel):
5
  extract_last_3_months: Optional[bool] = None # None means "use saved settings value"
 
6
 
7
 
8
  class OverwatchEmailRequest(BaseModel):
 
3
 
4
  class FinalisePayload(BaseModel):
5
  extract_last_3_months: Optional[bool] = None # None means "use saved settings value"
6
+ practice_ids: Optional[List[str]] = None # Practice IDs for group overrides
7
 
8
 
9
  class OverwatchEmailRequest(BaseModel):
routers/practices.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from auth.database import SessionLocal
3
+ from auth.rule_models import Practice
4
+
5
+ router = APIRouter(tags=["practices"])
6
+
7
+
8
+ @router.get("/api/practices")
9
+ async def get_practices():
10
+ """Return all active practices for the dropdown seed."""
11
+ db = SessionLocal()
12
+ try:
13
+ practices = (
14
+ db.query(Practice)
15
+ .filter(Practice.is_active == True)
16
+ .order_by(Practice.name.asc())
17
+ .all()
18
+ )
19
+ return {"practices": [{"id": p.id, "name": p.name} for p in practices]}
20
+ finally:
21
+ db.close()