@davoodmehraban89 / Aram-2 Mirror · read-only / commits / 0dbee85
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 10:30 UTC

Implement Phase 13 Accountant Pilot Feedback & Real Data Validation

Create pilot feedback and learning module in backend/app/services/feedback.py. Implement entities PilotFeedback (category: MAPPING_CORRECTION, PROCESSING_ISSUE, USER_SUGGESTION) and PilotValidationLog. Support auto-learning mapping corrections into COAMappingRule and recurring unknown account detection (get_recurring_unknown_accounts). Add API endpoints: POST /api/v1/pilot/feedback, GET /api/v1/pilot/feedback, GET /api/v1/pilot/validation-logs, and GET /api/v1/pilot/recurring-unknowns. Update docs/PILOT_TESTING_GUIDE.md with feedback recording workflows and checklist. Add 15 automated unit tests in test_pilot_feedback_validation.py (135/135 total tests passing). Preserve core accounting calculations, snapshot integrity, audit trail, and raw source file immutability. Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>

google-labs-jules[bot] committed Aug 23, 2026 at 17:58 UTC 0dbee855b414e36ec3741bf818729385776bd70f
8 files changed +652 -9
backend/app/api/endpoints.py
+66 -1
@@ -12,6 +12,11 @@ from backend.app.api.auth import (
12 create_access_token,
13 )
14 from backend.app.services.audit import log_audit_event
15 +from backend.app.services.feedback import (
16 + record_pilot_feedback,
17 + log_pilot_validation_summary,
18 + get_recurring_unknown_accounts,
19 +)
20 from backend.app.accounting.service import generate_financial_statements
21 from backend.app.accounting.snapshot import (
22 create_statement_snapshot,
@@ -31,7 +36,67 @@ def health_check():
36 return {"status": "ok", "service": "financial-reporting-platform"}
37
38
34 -# --- COA Mapping Engine Endpoints (Phase 12) ---
39 +# --- Pilot Feedback & Validation Endpoints (Phase 13) ---
40 +
41 +@router.post("/pilot/feedback", response_model=schemas.PilotFeedbackRead)
42 +def submit_pilot_feedback(
43 + year_id: int = Query(..., description="Fiscal Year ID"),
44 + feedback_data: schemas.PilotFeedbackCreate = Body(...),
45 + db: Session = Depends(get_db),
46 + user: Dict[str, Any] = Depends(get_current_user),
47 +):
48 + """Submits accountant pilot feedback or mapping correction."""
49 + fb = record_pilot_feedback(
50 + db,
51 + year_id=year_id,
52 + user_id=user.get("user_id"),
53 + category=feedback_data.category,
54 + comments=feedback_data.comments,
55 + account_code=feedback_data.account_code,
56 + original_value=feedback_data.original_value,
57 + corrected_value=feedback_data.corrected_value,
58 + )
59 + log_audit_event(
60 + db,
61 + user_id=user.get("user_id"),
62 + user_action=f"Submitted pilot feedback for account '{feedback_data.account_code}'.",
63 + entity_affected="PilotFeedback",
64 + action_type="CREATE",
65 + )
66 + return fb
67 +
68 +
69 +@router.get("/pilot/feedback", response_model=List[schemas.PilotFeedbackRead])
70 +def list_pilot_feedback(
71 + year_id: int = Query(..., description="Fiscal Year ID"),
72 + db: Session = Depends(get_db),
73 + user: Dict[str, Any] = Depends(require_role([models.UserRole.ADMIN, models.UserRole.AUDITOR])),
74 +):
75 + """Lists pilot feedback entries for a fiscal year."""
76 + return db.query(models.PilotFeedback).filter(models.PilotFeedback.year_id == year_id).all()
77 +
78 +
79 +@router.get("/pilot/validation-logs", response_model=List[schemas.PilotValidationLogRead])
80 +def list_pilot_validation_logs(
81 + year_id: int = Query(..., description="Fiscal Year ID"),
82 + db: Session = Depends(get_db),
83 + user: Dict[str, Any] = Depends(require_role([models.UserRole.ADMIN, models.UserRole.AUDITOR])),
84 +):
85 + """Lists pilot validation summary logs for a fiscal year."""
86 + return db.query(models.PilotValidationLog).filter(models.PilotValidationLog.year_id == year_id).all()
87 +
88 +
89 +@router.get("/pilot/recurring-unknowns")
90 +def list_recurring_unknown_accounts(
91 + year_id: int = Query(..., description="Fiscal Year ID"),
92 + db: Session = Depends(get_db),
93 + user: Dict[str, Any] = Depends(get_current_user),
94 +):
95 + """Lists recurring unknown or unmapped accounts detected from pilot feedback."""
96 + return get_recurring_unknown_accounts(db, year_id)
97 +
98 +
99 +# --- COA Mapping Engine Endpoints ---
100
101 @router.get("/coa/unmapped", response_model=List[Dict[str, Any]])
102 def get_unmapped_accounts(
backend/app/models/__init__.py
+6
@@ -9,8 +9,11 @@ from backend.app.models.entities import (
9 UserRole,
10 WorkflowStatus,
11 AccountHierarchyLevel,
12 + FeedbackCategory,
13 User,
14 AuditLog,
15 + PilotFeedback,
16 + PilotValidationLog,
17 SourceDocument,
18 AccountVersion,
19 MappingRule,
@@ -36,8 +39,11 @@ __all__ = [
39 "UserRole",
40 "WorkflowStatus",
41 "AccountHierarchyLevel",
42 + "FeedbackCategory",
43 "User",
44 "AuditLog",
45 + "PilotFeedback",
46 + "PilotValidationLog",
47 "SourceDocument",
48 "AccountVersion",
49 "MappingRule",
backend/app/models/entities.py
+44 -8
@@ -60,12 +60,18 @@ class WorkflowStatus(str, enum.Enum):
60
61
62 class AccountHierarchyLevel(str, enum.Enum):
63 - GENERAL_LEDGER = "GENERAL_LEDGER" # کل
64 - SUBSIDIARY_LEDGER = "SUBSIDIARY_LEDGER" # معین
65 - DETAIL_1 = "DETAIL_1" # تفصيل ۱
66 - DETAIL_2 = "DETAIL_2" # تفصيل ۲
67 - DETAIL_3 = "DETAIL_3" # تفصيل ۳
68 - DETAIL_4 = "DETAIL_4" # تفصيل ۴
63 + GENERAL_LEDGER = "GENERAL_LEDGER"
64 + SUBSIDIARY_LEDGER = "SUBSIDIARY_LEDGER"
65 + DETAIL_1 = "DETAIL_1"
66 + DETAIL_2 = "DETAIL_2"
67 + DETAIL_3 = "DETAIL_3"
68 + DETAIL_4 = "DETAIL_4"
69 +
70 +
71 +class FeedbackCategory(str, enum.Enum):
72 + MAPPING_CORRECTION = "MAPPING_CORRECTION"
73 + PROCESSING_ISSUE = "PROCESSING_ISSUE"
74 + USER_SUGGESTION = "USER_SUGGESTION"
75
76
77 class User(Base, TimestampMixin):
@@ -91,6 +97,34 @@ class AuditLog(Base, TimestampMixin):
97 user = relationship("User", back_populates="audit_logs")
98
99
100 +class PilotFeedback(Base, TimestampMixin):
101 + __tablename__ = "pilot_feedbacks"
102 +
103 + year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
104 + user_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
105 + category = Column(SQLEnum(FeedbackCategory), nullable=False, default=FeedbackCategory.MAPPING_CORRECTION)
106 + account_code = Column(String(100), nullable=True)
107 + original_value = Column(String(255), nullable=True)
108 + corrected_value = Column(String(255), nullable=True)
109 + comments = Column(Text, nullable=False)
110 +
111 + fiscal_year = relationship("FiscalYear", back_populates="pilot_feedbacks")
112 +
113 +
114 +class PilotValidationLog(Base, TimestampMixin):
115 + __tablename__ = "pilot_validation_logs"
116 +
117 + year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
118 + uploaded_filename = Column(String(255), nullable=False)
119 + file_hash = Column(String(64), nullable=False)
120 + record_count = Column(Integer, default=0, nullable=False)
121 + mapping_decisions = Column(JSON, nullable=True)
122 + user_corrections_count = Column(Integer, default=0, nullable=False)
123 + processing_result = Column(String(100), nullable=False)
124 +
125 + fiscal_year = relationship("FiscalYear", back_populates="pilot_validation_logs")
126 +
127 +
128 class Company(Base, TimestampMixin):
129 __tablename__ = "companies"
130
@@ -122,6 +156,8 @@ class FiscalYear(Base, TimestampMixin):
156 validation_logs = relationship("ValidationErrorLog", back_populates="fiscal_year", cascade="all, delete-orphan")
157 statement_snapshots = relationship("StatementSnapshot", back_populates="fiscal_year", cascade="all, delete-orphan")
158 coa_mapping_rules = relationship("COAMappingRule", back_populates="fiscal_year", cascade="all, delete-orphan")
159 + pilot_feedbacks = relationship("PilotFeedback", back_populates="fiscal_year", cascade="all, delete-orphan")
160 + pilot_validation_logs = relationship("PilotValidationLog", back_populates="fiscal_year", cascade="all, delete-orphan")
161
162
163 class SourceDocument(Base, TimestampMixin):
@@ -184,8 +220,8 @@ class COAMappingRule(Base, TimestampMixin):
220 year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
221 account_code = Column(String(100), nullable=False, index=True)
222 account_name = Column(String(255), nullable=False)
187 - target_statement = Column(SQLEnum(StatementType), nullable=False) # BS, IS, CF, EQ
188 - statement_section = Column(String(100), nullable=False) # Current Assets, Revenues, etc.
223 + target_statement = Column(SQLEnum(StatementType), nullable=False)
224 + statement_section = Column(String(100), nullable=False)
225 group_name = Column(String(255), nullable=False)
226 is_approved = Column(Boolean, default=False, nullable=False)
227
backend/app/schemas/__init__.py
+6
@@ -1,4 +1,7 @@
1 from backend.app.schemas.entities import (
2 + PilotFeedbackCreate,
3 + PilotFeedbackRead,
4 + PilotValidationLogRead,
5 COAMappingRuleBase,
6 COAMappingRuleRead,
7 UserCreate,
@@ -19,6 +22,9 @@ from backend.app.schemas.entities import (
22 )
23
24 __all__ = [
25 + "PilotFeedbackCreate",
26 + "PilotFeedbackRead",
27 + "PilotValidationLogRead",
28 "COAMappingRuleBase",
29 "COAMappingRuleRead",
30 "UserCreate",
backend/app/schemas/entities.py
+30
@@ -9,6 +9,7 @@ from backend.app.models.entities import (
9 UserRole,
10 WorkflowStatus,
11 AccountHierarchyLevel,
12 + FeedbackCategory,
13 )
14
15
@@ -16,6 +17,35 @@ class BaseORMModel(BaseModel):
17 model_config = ConfigDict(from_attributes=True)
18
19
20 +class PilotFeedbackCreate(BaseModel):
21 + category: FeedbackCategory = FeedbackCategory.MAPPING_CORRECTION
22 + account_code: Optional[str] = None
23 + original_value: Optional[str] = None
24 + corrected_value: Optional[str] = None
25 + comments: str
26 +
27 +
28 +class PilotFeedbackRead(PilotFeedbackCreate, BaseORMModel):
29 + id: int
30 + year_id: int
31 + user_id: Optional[int] = None
32 + created_at: datetime
33 + updated_at: datetime
34 +
35 +
36 +class PilotValidationLogRead(BaseORMModel):
37 + id: int
38 + year_id: int
39 + uploaded_filename: str
40 + file_hash: str
41 + record_count: int
42 + mapping_decisions: Optional[Dict[str, Any]] = None
43 + user_corrections_count: int
44 + processing_result: str
45 + created_at: datetime
46 + updated_at: datetime
47 +
48 +
49 class COAMappingRuleBase(BaseModel):
50 account_code: str
51 account_name: str
backend/app/services/feedback.py new
+92
@@ -0,0 +1,92 @@
1 +from typing import List, Optional, Dict, Any
2 +from sqlalchemy.orm import Session
3 +
4 +from backend.app.models.entities import (
5 + PilotFeedback,
6 + PilotValidationLog,
7 + COAMappingRule,
8 + FeedbackCategory,
9 +)
10 +from backend.app.services.protection import check_fiscal_year_mutable
11 +
12 +
13 +def record_pilot_feedback(
14 + db: Session,
15 + year_id: int,
16 + user_id: Optional[int],
17 + category: FeedbackCategory,
18 + comments: str,
19 + account_code: Optional[str] = None,
20 + original_value: Optional[str] = None,
21 + corrected_value: Optional[str] = None,
22 +) -> PilotFeedback:
23 + """Records user feedback, mapping corrections, or processing issues."""
24 + check_fiscal_year_mutable(db, year_id)
25 +
26 + feedback = PilotFeedback(
27 + year_id=year_id,
28 + user_id=user_id,
29 + category=category,
30 + account_code=account_code,
31 + original_value=original_value,
32 + corrected_value=corrected_value,
33 + comments=comments,
34 + )
35 + db.add(feedback)
36 +
37 + # If feedback is a mapping correction, auto-update or learn into COAMappingRule
38 + if category == FeedbackCategory.MAPPING_CORRECTION and account_code and corrected_value:
39 + rule = (
40 + db.query(COAMappingRule)
41 + .filter(COAMappingRule.year_id == year_id, COAMappingRule.account_code == account_code)
42 + .first()
43 + )
44 + if rule:
45 + rule.group_name = corrected_value
46 + rule.is_approved = True
47 +
48 + db.commit()
49 + db.refresh(feedback)
50 + return feedback
51 +
52 +
53 +def log_pilot_validation_summary(
54 + db: Session,
55 + year_id: int,
56 + uploaded_filename: str,
57 + file_hash: str,
58 + record_count: int,
59 + mapping_decisions: Dict[str, Any],
60 + user_corrections_count: int = 0,
61 + processing_result: str = "SUCCESS",
62 +) -> PilotValidationLog:
63 + """Logs uploaded file information, processing results, mapping decisions, and user corrections count."""
64 + v_log = PilotValidationLog(
65 + year_id=year_id,
66 + uploaded_filename=uploaded_filename,
67 + file_hash=file_hash,
68 + record_count=record_count,
69 + mapping_decisions=mapping_decisions,
70 + user_corrections_count=user_corrections_count,
71 + processing_result=processing_result,
72 + )
73 + db.add(v_log)
74 + db.commit()
75 + db.refresh(v_log)
76 + return v_log
77 +
78 +
79 +def get_recurring_unknown_accounts(db: Session, year_id: int) -> List[Dict[str, Any]]:
80 + """Detects recurring unknown or unmapped accounts across feedback entries for a fiscal year."""
81 + feedbacks = (
82 + db.query(PilotFeedback)
83 + .filter(PilotFeedback.year_id == year_id, PilotFeedback.account_code.isnot(None))
84 + .all()
85 + )
86 +
87 + counts: Dict[str, int] = {}
88 + for f in feedbacks:
89 + code = f.account_code
90 + counts[code] = counts.get(code, 0) + 1
91 +
92 + return [{"account_code": code, "feedback_count": count} for code, count in counts.items() if count >= 1]
backend/tests/test_pilot_feedback_validation.py new
+342
@@ -0,0 +1,342 @@
1 +import pytest
2 +from backend.app.models import (
3 + Company,
4 + FiscalYear,
5 + FiscalYearStatus,
6 + PilotFeedback,
7 + PilotValidationLog,
8 + COAMappingRule,
9 + FeedbackCategory,
10 + StatementType,
11 + User,
12 + UserRole,
13 +)
14 +from backend.app.services.feedback import (
15 + record_pilot_feedback,
16 + log_pilot_validation_summary,
17 + get_recurring_unknown_accounts,
18 +)
19 +from backend.app.services.protection import LockedFiscalYearError
20 +
21 +
22 +def test_record_pilot_feedback_capture(db_session):
23 + comp = Company(code="FB_1", name="Feedback Corp 1")
24 + db_session.add(comp)
25 + db_session.commit()
26 +
27 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
28 + db_session.add(fy)
29 + db_session.commit()
30 +
31 + user = User(username="accountant1", hashed_password="hash", role=UserRole.AUDITOR)
32 + db_session.add(user)
33 + db_session.commit()
34 +
35 + fb = record_pilot_feedback(
36 + db_session,
37 + year_id=fy.id,
38 + user_id=user.id,
39 + category=FeedbackCategory.USER_SUGGESTION,
40 + comments="Great UI performance on reports.",
41 + )
42 +
43 + assert fb.id is not None
44 + assert fb.category == FeedbackCategory.USER_SUGGESTION
45 + assert fb.comments == "Great UI performance on reports."
46 +
47 +
48 +def test_mapping_correction_feedback_auto_learns_mapping_rule(db_session):
49 + comp = Company(code="FB_2", name="Feedback Corp 2")
50 + db_session.add(comp)
51 + db_session.commit()
52 +
53 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
54 + db_session.add(fy)
55 + db_session.commit()
56 +
57 + rule = COAMappingRule(
58 + year_id=fy.id,
59 + account_code="110101",
60 + account_name="Cash",
61 + target_statement=StatementType.BS,
62 + statement_section="Current Assets",
63 + group_name="Old Cash Group",
64 + is_approved=False,
65 + )
66 + db_session.add(rule)
67 + db_session.commit()
68 +
69 + fb = record_pilot_feedback(
70 + db_session,
71 + year_id=fy.id,
72 + user_id=None,
73 + category=FeedbackCategory.MAPPING_CORRECTION,
74 + account_code="110101",
75 + original_value="Old Cash Group",
76 + corrected_value="Cash and Cash Equivalents",
77 + comments="Corrected group classification",
78 + )
79 +
80 + db_session.refresh(rule)
81 + assert rule.group_name == "Cash and Cash Equivalents"
82 + assert rule.is_approved is True
83 +
84 +
85 +def test_pilot_validation_summary_logging(db_session):
86 + comp = Company(code="FB_3", name="Feedback Corp 3")
87 + db_session.add(comp)
88 + db_session.commit()
89 +
90 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
91 + db_session.add(fy)
92 + db_session.commit()
93 +
94 + v_log = log_pilot_validation_summary(
95 + db_session,
96 + year_id=fy.id,
97 + uploaded_filename="trial_balance_1402.xlsx",
98 + file_hash="hash_summary_1402",
99 + record_count=150,
100 + mapping_decisions={"auto_mapped": 140, "unmapped": 10},
101 + user_corrections_count=3,
102 + processing_result="SUCCESS",
103 + )
104 +
105 + assert v_log.id is not None
106 + assert v_log.record_count == 150
107 + assert v_log.user_corrections_count == 3
108 + assert v_log.mapping_decisions["auto_mapped"] == 140
109 +
110 +
111 +def test_recurring_unknown_account_detection(db_session):
112 + comp = Company(code="FB_4", name="Feedback Corp 4")
113 + db_session.add(comp)
114 + db_session.commit()
115 +
116 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
117 + db_session.add(fy)
118 + db_session.commit()
119 +
120 + record_pilot_feedback(
121 + db_session,
122 + year_id=fy.id,
123 + user_id=None,
124 + category=FeedbackCategory.PROCESSING_ISSUE,
125 + account_code="990101",
126 + comments="Unknown account code",
127 + )
128 + record_pilot_feedback(
129 + db_session,
130 + year_id=fy.id,
131 + user_id=None,
132 + category=FeedbackCategory.MAPPING_CORRECTION,
133 + account_code="990101",
134 + comments="Second issue report for 990101",
135 + )
136 +
137 + recurring = get_recurring_unknown_accounts(db_session, fy.id)
138 + assert len(recurring) == 1
139 + assert recurring[0]["account_code"] == "990101"
140 + assert recurring[0]["feedback_count"] == 2
141 +
142 +
143 +def test_locked_year_feedback_rejection(db_session):
144 + comp = Company(code="FB_5", name="Feedback Corp 5")
145 + db_session.add(comp)
146 + db_session.commit()
147 +
148 + fy_locked = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.LOCKED)
149 + db_session.add(fy_locked)
150 + db_session.commit()
151 +
152 + with pytest.raises(LockedFiscalYearError):
153 + record_pilot_feedback(
154 + db_session,
155 + year_id=fy_locked.id,
156 + user_id=None,
157 + category=FeedbackCategory.USER_SUGGESTION,
158 + comments="Feedback on locked year",
159 + )
160 +
161 +
162 +def test_api_submit_pilot_feedback(client, db_session):
163 + comp = Company(code="API_FB1", name="API Feedback Corp")
164 + db_session.add(comp)
165 + db_session.commit()
166 +
167 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
168 + db_session.add(fy)
169 + db_session.commit()
170 +
171 + payload = {
172 + "category": "MAPPING_CORRECTION",
173 + "account_code": "1101",
174 + "original_value": "Wrong Group",
175 + "corrected_value": "Cash Equivalents",
176 + "comments": "Fixed mapping via UI",
177 + }
178 +
179 + res = client.post(f"/api/v1/pilot/feedback?year_id={fy.id}", json=payload)
180 + assert res.status_code == 200
181 + assert res.json()["account_code"] == "1101"
182 +
183 +
184 +def test_api_list_pilot_feedback(client, db_session):
185 + comp = Company(code="API_FB2", name="API Feedback Corp 2")
186 + db_session.add(comp)
187 + db_session.commit()
188 +
189 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
190 + db_session.add(fy)
191 + db_session.commit()
192 +
193 + record_pilot_feedback(db_session, fy.id, None, FeedbackCategory.USER_SUGGESTION, "Test comment")
194 +
195 + res = client.get(f"/api/v1/pilot/feedback?year_id={fy.id}")
196 + assert res.status_code == 200
197 + assert len(res.json()) >= 1
198 +
199 +
200 +def test_api_list_validation_logs(client, db_session):
201 + comp = Company(code="API_FB3", name="API Feedback Corp 3")
202 + db_session.add(comp)
203 + db_session.commit()
204 +
205 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
206 + db_session.add(fy)
207 + db_session.commit()
208 +
209 + log_pilot_validation_summary(
210 + db_session,
211 + year_id=fy.id,
212 + uploaded_filename="test.csv",
213 + file_hash="hash_test",
214 + record_count=10,
215 + mapping_decisions={},
216 + )
217 +
218 + res = client.get(f"/api/v1/pilot/validation-logs?year_id={fy.id}")
219 + assert res.status_code == 200
220 + assert len(res.json()) == 1
221 +
222 +
223 +def test_api_list_recurring_unknowns(client, db_session):
224 + comp = Company(code="API_FB4", name="API Feedback Corp 4")
225 + db_session.add(comp)
226 + db_session.commit()
227 +
228 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
229 + db_session.add(fy)
230 + db_session.commit()
231 +
232 + record_pilot_feedback(db_session, fy.id, None, FeedbackCategory.PROCESSING_ISSUE, "Issue", account_code="8801")
233 +
234 + res = client.get(f"/api/v1/pilot/recurring-unknowns?year_id={fy.id}")
235 + assert res.status_code == 200
236 + assert len(res.json()) == 1
237 + assert res.json()[0]["account_code"] == "8801"
238 +
239 +
240 +def test_processing_issue_feedback_recording(db_session):
241 + comp = Company(code="FB_PROC", name="Proc Issue Corp")
242 + db_session.add(comp)
243 + db_session.commit()
244 +
245 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
246 + db_session.add(fy)
247 + db_session.commit()
248 +
249 + fb = record_pilot_feedback(
250 + db_session,
251 + year_id=fy.id,
252 + user_id=None,
253 + category=FeedbackCategory.PROCESSING_ISSUE,
254 + comments="Column shift detected on row 12",
255 + )
256 + assert fb.category == FeedbackCategory.PROCESSING_ISSUE
257 +
258 +
259 +def test_feedback_isolation_between_companies(db_session):
260 + comp1 = Company(code="ISO_FB1", name="Iso FB Corp 1")
261 + comp2 = Company(code="ISO_FB2", name="Iso FB Corp 2")
262 + db_session.add_all([comp1, comp2])
263 + db_session.commit()
264 +
265 + fy1 = FiscalYear(company_id=comp1.id, year=1402, status=FiscalYearStatus.DRAFT)
266 + fy2 = FiscalYear(company_id=comp2.id, year=1402, status=FiscalYearStatus.DRAFT)
267 + db_session.add_all([fy1, fy2])
268 + db_session.commit()
269 +
270 + record_pilot_feedback(db_session, fy1.id, None, FeedbackCategory.USER_SUGGESTION, "Comp1 feedback")
271 +
272 + fb_c2 = db_session.query(PilotFeedback).filter_by(year_id=fy2.id).all()
273 + assert len(fb_c2) == 0
274 +
275 +
276 +def test_feedback_isolation_between_fiscal_years(db_session):
277 + comp = Company(code="ISO_FY_FB", name="Iso FY FB Corp")
278 + db_session.add(comp)
279 + db_session.commit()
280 +
281 + fy1402 = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
282 + fy1403 = FiscalYear(company_id=comp.id, year=1403, status=FiscalYearStatus.DRAFT)
283 + db_session.add_all([fy1402, fy1403])
284 + db_session.commit()
285 +
286 + record_pilot_feedback(db_session, fy1402.id, None, FeedbackCategory.USER_SUGGESTION, "1402 feedback")
287 +
288 + fb_1403 = db_session.query(PilotFeedback).filter_by(year_id=fy1403.id).all()
289 + assert len(fb_1403) == 0
290 +
291 +
292 +def test_validation_log_persistence_with_corrections(db_session):
293 + comp = Company(code="VLOG_PERS", name="VLog Corp")
294 + db_session.add(comp)
295 + db_session.commit()
296 +
297 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
298 + db_session.add(fy)
299 + db_session.commit()
300 +
301 + vlog = log_pilot_validation_summary(
302 + db_session,
303 + year_id=fy.id,
304 + uploaded_filename="ledger_full.csv",
305 + file_hash="hash_full",
306 + record_count=500,
307 + mapping_decisions={"auto": 480, "manual": 20},
308 + user_corrections_count=5,
309 + processing_result="COMPLETED_WITH_CORRECTIONS",
310 + )
311 +
312 + assert vlog.processing_result == "COMPLETED_WITH_CORRECTIONS"
313 + assert vlog.user_corrections_count == 5
314 +
315 +
316 +def test_recurring_unknown_empty_when_no_feedbacks(db_session):
317 + comp = Company(code="EMPTY_UNK", name="Empty Unknown Corp")
318 + db_session.add(comp)
319 + db_session.commit()
320 +
321 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
322 + db_session.add(fy)
323 + db_session.commit()
324 +
325 + recurring = get_recurring_unknown_accounts(db_session, fy.id)
326 + assert len(recurring) == 0
327 +
328 +
329 +def test_feedback_audit_log_integration(client, db_session):
330 + comp = Company(code="FB_AUDIT", name="FB Audit Corp")
331 + db_session.add(comp)
332 + db_session.commit()
333 +
334 + fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
335 + db_session.add(fy)
336 + db_session.commit()
337 +
338 + payload = {"category": "USER_SUGGESTION", "comments": "Audit logging test"}
339 + client.post(f"/api/v1/pilot/feedback?year_id={fy.id}", json=payload)
340 +
341 + logs = client.get("/api/v1/audit-logs").json()
342 + assert any("PilotFeedback" in l["entity_affected"] for l in logs)
docs/PILOT_TESTING_GUIDE.md new
+66
@@ -0,0 +1,66 @@
1 +# راهنمای تست پایلوت حسابداران و اعتبارسنجی داده‌های واقعی (Accountant Pilot Testing Guide)
2 +
3 +این سند چک‌لیست تست پایلوت، نمونه گردش کار اجرایی، ثبت بازخوردها و خروجی‌های مورد انتظار نرم‌افزار آرام را برای حسابداران و حسابرسان تشریح می‌کند.
4 +
5 +---
6 +
7 +## ۱. چک‌لیست تست حسابداران (Accountant Test Checklist)
8 +
9 +| شماره | عنوان تست | شرح عملیات | خروجی مورد انتظار |
10 +| :---: | :--- | :--- | :--- |
11 +| ۱ | ورود به سیستم | ورود با نام کاربری و کلمه عبور اختصاص داده شده | دریافت توکن احراز هویت و نمایش نقش کاربر (`ADMIN` / `AUDITOR`) |
12 +| ۲ | ثبت فایل دفتر مالی | بارگذاری فایل CSV/XLSX دفتر کل یا معین | محاسبه هش SHA256، جلوگیری از ثبت تکراری و ثبت `SourceDocument` |
13 +| ۳ | نرمال‌سازی داده‌ها | تبدیل سطرهای خام فایل به رکوردهای استاندارد | تشکیل رکوردهای مالی نرمال‌شده و ثبت لاگ خطاهای احتمالی |
14 +| ۴ | کشف حساب‌های نگاشت‌نشده | شناسایی کد حساب‌هایی که نگاشت تاییدشده ندارند | ارائه پیشنهاد هوشمندانه نگاشت بر اساس استانداردهای حسابداری |
15 +| ۵ | اصلاح و ثبت نگاشت | اصلاح گروه یا بخش صورت مالی حساب توسط حسابدار | به‌روزرسانی قوانین نگاشت و اعمال هوشمند اصلاحات در سیستم |
16 +| ۶ | ثبت بازخورد و گزارش اشکال | ارسال بازخورد، اصلاح نگاشت یا گزارش اشکال | ذخیره در جدول `PilotFeedback` و یادگیری سیستم از اصلاحات |
17 +| ۷ | محاسبه صورت‌های مالی | اجرای محاسبات تراز آزمایشی، ترازنامه و سود و زیان | محاسبه دقیق مانده‌ها و بررسی برابری مجموع بدهکار و بستانکار |
18 +| ۸ | تولید اسنپ‌شات بررسی | ایجاد نسخه جدید اسنپ‌شات انجمادیافته جهت بررسی | تخصیص شماره نسخه (نسخه ۱، ۲ و ...) و ثبت وضعیت `DRAFT` |
19 +| ۹ | تایید نهایی گردش کار | تغییر وضعیت اسنپ‌شات و دوره مالی به `APPROVED` | قفل شدن تغییرات و آماده‌سازی جهت گزارش‌گیری نهایی |
20 +| ۱۰ | خروجی‌گرفتن گزارش‌ها | دریافت فایل CSV یا ساختار چاپی PDF | تولید فایل خروجی با فرمت استاندارد ریال و خطوط مالی |
21 +
22 +---
23 +
24 +## ۲. سرویس بازخورد و یادگیری نگاشت (Pilot Feedback & Learning Module)
25 +
26 +- **انواع بازخوردها (`FeedbackCategory`)**:
27 + - `MAPPING_CORRECTION`: اصلاح نگاشت کد حساب توسط حسابدار (به صورت خودکار نگاشت جدید را در `COAMappingRule` به‌روزرسانی کرده و تایید می‌نماید).
28 + - `PROCESSING_ISSUE`: گزارش جابه‌جایی ستون یا اشکال ساختاری در پردازش فایل.
29 + - `USER_SUGGESTION`: پیشنهادات کاربر برای بهبود تجربه کاربری.
30 +- **کشف حساب‌های نگاشت‌نشده تکرارشونده**: متد `get_recurring_unknown_accounts()` حساب‌هایی که مکرراً گزارش شده‌اند را شناسایی کرده تا در قالب پیشنهاد به کاربر نمایش داده شود.
31 +- **خلاصه اعتبارسنجی پایلوت (`PilotValidationLog`)**: خلاصه فایل‌های بارگذاری‌شده، تعداد رکوردهای پردازش‌شده، تصمیمات نگاشت و تعداد اصلاحات کاربر را ذخیره می‌کند.
32 +
33 +---
34 +
35 +## ۳. نمونه گردش کار اجرایی (Sample Workflow Execution)
36 +
37 +```text
38 +[۱. بارگذاری فایل CSV/XLSX]
39 + │
40 + ▼
41 +[۲. اعتبارسنجی و محاسبه SHA256] ──► (اگر فایل تکراری باشد: خطای DuplicateSourceError)
42 + │
43 + ▼
44 +[۳. نرمال‌سازی سطرهای مالی]
45 + │
46 + ▼
47 +[۴. کشف حساب‌های جدید نگاشت‌نشده] ──► (ارائه پیشنهاد هوشمند به حسابدار)
48 + │
49 + ▼
50 +[۵. ثبت بازخورد / اصلاح حسابدار] ──► (ذخیره در PilotFeedback و به‌روزرسانی COAMappingRule)
51 + │
52 + ▼
53 +[۶. اجرای محاسبات و تولید اسنپ‌شات]
54 + │
55 + ▼
56 +[۷. تایید نهایی (APPROVED) و خروجی CSV/PDF]
57 +```
58 +
59 +---
60 +
61 +## ۴. خروجی‌های مورد انتظار سیستم (Expected Outputs)
62 +
63 +1. **تراز آزمایشی (Trial Balance)**: مجموع بدهکار و بستانکار کاملاً برابر بوده و پرچم `is_balanced: true` فعال باشد.
64 +2. **ترازنامه (Balance Sheet)**: مجموع دارایی‌ها برابر با مجموع بدهی‌ها و حقوق مالکانه باشد.
65 +3. **لاگ‌های حسابرسی (Audit Logs)**: تمام اقدامات کاربر همراه با نام کاربر، زمان و نوع عملیات به طور کامل ثبت شود.
66 +4. **عدم تغییر منابع خام**: فایل‌های اصلی تحت پوشش فولدر `data/` تحت هیچ شرایطی تغییر یا دستکاری نشوند.