Files
encoach_backend_v4/custom_addons/encoach_lms_api/controllers/payments.py
Yamen Ahmad 6ec68160c8 feat: institutional + support + training admin sections (backend + frontend)
Ship three fully-wired admin areas end-to-end with APIs, seeds, tests and docs.

Backend (new `encoach_lms_api` addon + existing addons):
- Institutional: academic years/terms, departments, admission registers & admissions,
  courses/batches, lessons, fees (terms + student fees + invoicing with income-account
  auto-wiring), gradebook (assignments/grades), library, facilities (encoach.asset),
  student leave, result templates + marksheets (incl. delete-with-cascade).
- Support: `encoach.ticket` model + CRUD/assignee routes; payment records derived
  from `op.student.fees.details` and `account.move`; platform settings backed by
  `encoach.code` and `ir.config_parameter` (packages + grading config).
- Training: `encoach.vocab.item` + `encoach.grammar.rule` (plus progress models)
  with CRUD, pagination, search/level filters, and upsert-style progress endpoints.
  Odoo 19 compatibility: `_sql_constraints` replaced with `@api.constrains`;
  `ValidationError`/`UserError` mapped to HTTP 400.

Frontend:
- Rewire institutional admin pages (Academic Year Manager, Admissions, Courses,
  Lessons, Fees, Gradebook, Library, Facilities, Student Leave, Marksheets,
  Taxonomy, Resources) to real APIs with React Query invalidation and dialogs.
- New typed services: `payments.service.ts`, `platformSettings.service.ts`,
  `training.service.ts`. Updated `fees/gradebook/lms/courseware/taxonomy/
  resources/student-progress/generation` services + related types.
- Rewrite `VocabularyPage`, `GrammarPage`, `PaymentRecordPage`, `SettingsPage`,
  `TicketsPage` to consume live data with search/filter/progress/CRUD flows.
- New shared components: `TaxonomyCascade`, `MaterialViewer`, `teacher/TeacherLibrary`.
- Favicons/branding assets and misc. UX polish across teacher/student pages.

Tooling & QA:
- Seeders: `seed_demo.py`, `seed_demo_data.py`, `seed_institutional.py` (idempotent,
  covers institutional + support + training fixtures incl. income-account wiring).
- API write-flow test suites: `test_write_flows.py` (institutional),
  `test_support_flows.py` (support), `test_training_flows.py` (training),
  `test_ai_full.py`. All suites pass end-to-end.
- Docs: add `docs/PROJECT_SUMMARY.md` with per-section scope, artifacts and QA.
- `.gitignore`: ignore `pgdata_bak_*/`, `frontend/.vite/`, `frontend/dist/`,
  `frontend/node_modules/`.

Made-with: Cursor
2026-04-19 03:13:23 +04:00

126 lines
5.2 KiB
Python

"""Payment Record endpoints — surfaces real accounting/fees data to the
`/admin/payment-record` page (previously mocked).
"""
import logging
from odoo import http
from odoo.http import request
from odoo.addons.encoach_api.controllers.base import (
jwt_required, _json_response, _error_response,
)
_logger = logging.getLogger(__name__)
def _ser_fee_as_payment(rec):
"""Serialize an op.student.fees.details row as a 'payment record'."""
inv = rec.invoice_id if hasattr(rec, 'invoice_id') else False
return {
'id': rec.id,
'ref': f'FEE-{rec.id:04d}',
'student_id': rec.student_id.id if rec.student_id else None,
'student_name': rec.student_id.name if rec.student_id else '',
'course_id': rec.course_id.id if rec.course_id else None,
'course_name': rec.course_id.name if rec.course_id else '',
'product_name': rec.product_id.name if rec.product_id else '',
'amount': float(rec.amount or 0.0),
'after_discount_amount': float(getattr(rec, 'after_discount_amount', rec.amount) or 0.0),
'currency': rec.currency_id.name if hasattr(rec, 'currency_id') and rec.currency_id else 'USD',
'state': rec.state or 'draft',
'paid': rec.state in ('paid', 'post'),
'date': str(rec.date) if rec.date else '',
'type': 'Student Fees',
'invoice_id': inv.id if inv else None,
'invoice_number': inv.name if inv and inv.name and inv.name != '/' else '',
'payment_state': inv.payment_state if inv and hasattr(inv, 'payment_state') else '',
}
def _ser_invoice(inv):
return {
'id': inv.id,
'ref': inv.name or f'INV-{inv.id}',
'partner_name': inv.partner_id.name if inv.partner_id else '',
'amount': float(inv.amount_total or 0.0),
'currency': inv.currency_id.name if inv.currency_id else 'USD',
'state': inv.state or 'draft',
'payment_state': getattr(inv, 'payment_state', '') or '',
'paid': getattr(inv, 'payment_state', '') == 'paid',
'date': str(inv.invoice_date) if inv.invoice_date else str(inv.date) if inv.date else '',
'type': 'Invoice',
}
class PaymentRecordsController(http.Controller):
@http.route('/api/payment-records', type='http', auth='public',
methods=['GET'], csrf=False)
@jwt_required
def list_payments(self, **kw):
"""Return a unified list of payment records sourced from student fees
(and optionally accounting invoices). Supports filters: status, paid,
student_id."""
try:
FeesModel = request.env['op.student.fees.details'].sudo()
domain = []
status = kw.get('status')
if status and status != 'all':
domain.append(('state', '=', status))
if kw.get('student_id'):
try:
domain.append(('student_id', '=', int(kw['student_id'])))
except (TypeError, ValueError):
pass
recs = FeesModel.search(domain, limit=200)
items = [_ser_fee_as_payment(r) for r in recs]
paid_filter = kw.get('paid')
if paid_filter in ('true', 'false'):
want = paid_filter == 'true'
items = [i for i in items if i['paid'] == want]
return _json_response({
'data': items,
'items': items,
'total': len(items),
'totals': {
'count': len(items),
'paid': sum(1 for i in items if i['paid']),
'unpaid': sum(1 for i in items if not i['paid']),
'amount': sum(i['amount'] for i in items),
},
})
except Exception as e:
_logger.exception('list_payments')
return _error_response(str(e), 500)
@http.route('/api/payment-records/invoices', type='http', auth='public',
methods=['GET'], csrf=False)
@jwt_required
def list_invoices(self, **kw):
"""Raw accounting invoices (account.move with out_invoice)."""
try:
Move = request.env['account.move'].sudo()
domain = [('move_type', '=', 'out_invoice')]
try:
size = min(int(kw.get('size') or 50), 200)
except (TypeError, ValueError):
size = 50
recs = Move.search(domain, limit=size, order='id desc')
items = [_ser_invoice(m) for m in recs]
return _json_response({
'data': items, 'items': items, 'total': len(items),
})
except Exception as e:
_logger.exception('list_invoices')
return _error_response(str(e), 500)
@http.route('/api/paymob-orders', type='http', auth='public',
methods=['GET'], csrf=False)
@jwt_required
def list_paymob_orders(self, **kw):
"""Paymob integration is not yet wired — return empty list.
This endpoint exists so the UI renders cleanly instead of calling a
404-returning route."""
return _json_response({
'data': [], 'items': [], 'total': 0,
'message': 'Paymob integration not configured.',
})