Commit 2ab0efe1 by Percy Quispe Huarcaya

feat: agregar sync plan de pago

parent d979718e
...@@ -49,6 +49,7 @@ All endpoints prefixed with `/api/v1`. ...@@ -49,6 +49,7 @@ All endpoints prefixed with `/api/v1`.
- `POST /api/v1/sync/students/trigger` / `GET /api/v1/sync/students/status` — students pipeline: run now / last run time, rows synced (created/updated/deleted breakdown), last error if any. - `POST /api/v1/sync/students/trigger` / `GET /api/v1/sync/students/status` — students pipeline: run now / last run time, rows synced (created/updated/deleted breakdown), last error if any.
- `POST /api/v1/sync/students_incremental/trigger` / `GET /api/v1/sync/students_incremental/status` — carga incremental de estudiantes: `postgres.LoadDataStudent` (= `StudentQuery` + `pp.to_update OR ma.to_update`) relee solo las personas/matrículas marcadas y, al terminar, `postgres.StudentMarker` resetea `persona.pe_persona.to_update` y `matricula.ma_matricula.to_update` a `false`. No reconcilia borrados. - `POST /api/v1/sync/students_incremental/trigger` / `GET /api/v1/sync/students_incremental/status` — carga incremental de estudiantes: `postgres.LoadDataStudent` (= `StudentQuery` + `pp.to_update OR ma.to_update`) relee solo las personas/matrículas marcadas y, al terminar, `postgres.StudentMarker` resetea `persona.pe_persona.to_update` y `matricula.ma_matricula.to_update` a `false`. No reconcilia borrados.
- `POST /api/v1/sync/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — payment_plans pipeline (same shape). - `POST /api/v1/sync/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — payment_plans pipeline (same shape).
- `POST /api/v1/sync/payment_plans_incremental/trigger` / `GET /api/v1/sync/payment_plans_incremental/status` — carga incremental de planes de pago: `postgres.LoadDataPaymentPlan` (= `PaymentPlanQuery` unido a `caja.ca_plan_de_pago_intranet` por `plan_de_pago_id` y filtrado por su `to_update`) relee solo los planes marcados y, al terminar, `postgres.PaymentPlanMarker` resetea `caja.ca_plan_de_pago_intranet.to_update` a `false` y estampa `sync_last_update = now()`. No reconcilia borrados.
- `POST /api/v1/sync/parents/trigger` / `GET /api/v1/sync/parents/status` — parents pipeline (same shape). - `POST /api/v1/sync/parents/trigger` / `GET /api/v1/sync/parents/status` — parents pipeline (same shape).
- `POST /api/v1/sync/users/trigger` / `GET /api/v1/sync/users/status` — users pipeline (same shape). - `POST /api/v1/sync/users/trigger` / `GET /api/v1/sync/users/status` — users pipeline (same shape).
- `POST /api/v1/sync/balotarios/trigger` / `GET /api/v1/sync/balotarios/status` — pipeline de balotarios (misma forma). La primera corrida tarda ~2 min, así que usar `curl -m 290`. - `POST /api/v1/sync/balotarios/trigger` / `GET /api/v1/sync/balotarios/status` — pipeline de balotarios (misma forma). La primera corrida tarda ~2 min, así que usar `curl -m 290`.
...@@ -59,7 +60,7 @@ All endpoints prefixed with `/api/v1`. ...@@ -59,7 +60,7 @@ All endpoints prefixed with `/api/v1`.
Students: `internal/infrastructure/database/postgres.StudentQuery`, a raw SQL query (not a function) joining `matricula.ma_estudiante`/`persona.pe_persona`/`matricula.ma_matricula`/`caja.ca_plan_de_pago`, grouped per student, `payment_plans`/`payment_plans_current_year` built via `JSON_AGG(...) FILTER (...)` split on `periodo_academico_id = 14`. Read directly by `postgres.StudentReader` (`pgx` row scan, no JSON envelope) — one Mongo doc per row, requires numeric `enrollment_id`. `student_enrollment_photo_url` sale de un `LEFT JOIN LATERAL` sobre `matricula.ma_requisito` (requisito 2961, "Foto tamaño carné"): la URL pública de Drive más reciente entre todas las matrículas del alumno, `null` si no tiene. Suma ~5 s al ciclo porque `ma_requisito` está inflada y no tiene índice por `requisito_documento_id`. Students: `internal/infrastructure/database/postgres.StudentQuery`, a raw SQL query (not a function) joining `matricula.ma_estudiante`/`persona.pe_persona`/`matricula.ma_matricula`/`caja.ca_plan_de_pago`, grouped per student, `payment_plans`/`payment_plans_current_year` built via `JSON_AGG(...) FILTER (...)` split on `periodo_academico_id = 14`. Read directly by `postgres.StudentReader` (`pgx` row scan, no JSON envelope) — one Mongo doc per row, requires numeric `enrollment_id`. `student_enrollment_photo_url` sale de un `LEFT JOIN LATERAL` sobre `matricula.ma_requisito` (requisito 2961, "Foto tamaño carné"): la URL pública de Drive más reciente entre todas las matrículas del alumno, `null` si no tiene. Suma ~5 s al ciclo porque `ma_requisito` está inflada y no tiene índice por `requisito_documento_id`.
Payment plans: `internal/infrastructure/database/postgres.PaymentPlanQuery`, one document per plan of payment. Read by `postgres.StudentReader (anida los planes de pago)`. Payment plans: `internal/infrastructure/database/postgres.PaymentPlanQuery`, one document per plan of payment. Read by `postgres.StudentReader (anida los planes de pago)`. La carga incremental usa `postgres.LoadDataPaymentPlan` (= `PaymentPlanQuery` + `INNER JOIN caja.ca_plan_de_pago_intranet` por `plan_de_pago_id` y filtro `coalesce(to_update, false)`): esa tabla (`plan_de_pago_id`, `to_update`, `sync_last_update`) es la que marca qué planes re-sincronizar, y `postgres.PaymentPlanMarker` la resetea (`to_update = false`, `sync_last_update = now()`) al terminar.
Parents: `internal/infrastructure/database/postgres.ParentQuery`, joins `persona.pe_persona` with an aggregated subquery on `matricula.ma_estudiante_apoderado` (one row per parent/guardian, `students` embedded via `JSON_AGG(json_build_object('student_id', ...))`). Read by `postgres.ParentReader` into `entities.Parent` — collection `parents`, archive `deleted_parents`, `IDField` = `parent_id`, `StateID` = 3. Parents: `internal/infrastructure/database/postgres.ParentQuery`, joins `persona.pe_persona` with an aggregated subquery on `matricula.ma_estudiante_apoderado` (one row per parent/guardian, `students` embedded via `JSON_AGG(json_build_object('student_id', ...))`). Read by `postgres.ParentReader` into `entities.Parent` — collection `parents`, archive `deleted_parents`, `IDField` = `parent_id`, `StateID` = 3.
......
package entities package entities
import "time" import (
"fmt"
"time"
)
type PaymentPlan struct { type PaymentPlan struct {
PaymentPlanID int `bson:"payment_plan_id"` PaymentPlanID int `bson:"payment_plan_id"`
...@@ -30,3 +33,7 @@ func (p *PaymentPlan) SetRowHash(h string) { ...@@ -30,3 +33,7 @@ func (p *PaymentPlan) SetRowHash(h string) {
func (p *PaymentPlan) SetCreatedAt(t time.Time) { func (p *PaymentPlan) SetCreatedAt(t time.Time) {
p.CreatedAt = t p.CreatedAt = t
} }
func (p *PaymentPlan) RefLogLines(verb, estado string) []string {
return []string{fmt.Sprintf("%s plan de pago %s en Mongo con payment_plan_id: %d y enrollment_id: %d", verb, estado, p.PaymentPlanID, p.EnrollmentID)}
}
...@@ -87,6 +87,16 @@ var Pipelines = []PipelineDef{ ...@@ -87,6 +87,16 @@ var Pipelines = []PipelineDef{
DefaultInterval: 90 * time.Minute, DefaultInterval: 90 * time.Minute,
}, },
{ {
Name: "payment_plans_incremental",
PGQuery: postgres.LoadDataPaymentPlan,
MongoCollection: "payment_plans",
MongoDeletedCollection: "deleted_payment_plans",
IDField: "payment_plan_id",
StateID: 16,
Incremental: true,
DefaultInterval: 90 * time.Minute,
},
{
Name: "attendance", Name: "attendance",
PGQuery: postgres.AttendanceQuery, PGQuery: postgres.AttendanceQuery,
MongoCollection: "c_attendance", MongoCollection: "c_attendance",
......
...@@ -55,7 +55,7 @@ CREATE TABLE IF NOT EXISTS sync_state ( ...@@ -55,7 +55,7 @@ CREATE TABLE IF NOT EXISTS sync_state (
); );
INSERT INTO sync_state (id, last_synced_at) INSERT INTO sync_state (id, last_synced_at)
VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z'), (6, '1970-01-01T00:00:00Z'), (7, '1970-01-01T00:00:00Z'), (8, '1970-01-01T00:00:00Z'), (9, '1970-01-01T00:00:00Z'), (11, '1970-01-01T00:00:00Z'), (12, '1970-01-01T00:00:00Z'), (15, '1970-01-01T00:00:00Z') VALUES (1, '1970-01-01T00:00:00Z'), (2, '1970-01-01T00:00:00Z'), (3, '1970-01-01T00:00:00Z'), (4, '1970-01-01T00:00:00Z'), (5, '1970-01-01T00:00:00Z'), (6, '1970-01-01T00:00:00Z'), (7, '1970-01-01T00:00:00Z'), (8, '1970-01-01T00:00:00Z'), (9, '1970-01-01T00:00:00Z'), (11, '1970-01-01T00:00:00Z'), (12, '1970-01-01T00:00:00Z'), (15, '1970-01-01T00:00:00Z'), (16, '1970-01-01T00:00:00Z')
ON CONFLICT (id) DO NOTHING; ON CONFLICT (id) DO NOTHING;
` `
......
package postgres
import (
"context"
"fmt"
"log"
"sort"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
type PaymentPlanMarker struct {
pool *Pool
}
func NewPaymentPlanMarker(pool *Pool) repositories.ProcessedMarker {
return &PaymentPlanMarker{pool: pool}
}
const resetPaymentPlanToUpdateSQL = `
UPDATE caja.ca_plan_de_pago_intranet
SET to_update = false, sync_last_update = now()
WHERE plan_de_pago_id = ANY($1)
AND coalesce(to_update, false)`
func (m *PaymentPlanMarker) MarkProcessed(ctx context.Context, rows []entities.SyncRow) error {
ids := paymentPlanIDs(rows)
if len(ids) == 0 {
return nil
}
if _, err := m.pool.Pool.Exec(ctx, resetPaymentPlanToUpdateSQL, ids); err != nil {
return fmt.Errorf("reset payment_plan to_update: %w", err)
}
for _, row := range rows {
plan, ok := row.Doc.(*entities.PaymentPlan)
if !ok {
continue
}
log.Printf("[payment_plans_incremental] Paso 3: actualizar caja.ca_plan_de_pago_intranet to_update=false con payment_plan_id: %d y enrollment_id: %d", plan.PaymentPlanID, plan.EnrollmentID)
}
return nil
}
func paymentPlanIDs(rows []entities.SyncRow) []int {
seen := make(map[int]struct{}, len(rows))
ids := make([]int, 0, len(rows))
for _, row := range rows {
plan, ok := row.Doc.(*entities.PaymentPlan)
if !ok {
continue
}
if _, exists := seen[plan.PaymentPlanID]; exists {
continue
}
seen[plan.PaymentPlanID] = struct{}{}
ids = append(ids, plan.PaymentPlanID)
}
sort.Ints(ids)
return ids
}
...@@ -41,6 +41,7 @@ WITH tb_lista_plan_pago AS (select c.plan_de_pago_id ...@@ -41,6 +41,7 @@ WITH tb_lista_plan_pago AS (select c.plan_de_pago_id
c.plan_de_pago_subtotal as payment_plan_total, c.plan_de_pago_subtotal as payment_plan_total,
CASE WHEN c.plan_de_pago_deuda THEN 1 ELSE 0 END as payment_plan_debt CASE WHEN c.plan_de_pago_deuda THEN 1 ELSE 0 END as payment_plan_debt
FROM caja.ca_plan_de_pago c FROM caja.ca_plan_de_pago c
INNER JOIN caja.ca_plan_de_pago_intranet cpdi ON cpdi.plan_de_pago_id = c.plan_de_pago_id
INNER JOIN matricula.ma_matricula ma ON c.matricula_id = ma.matricula_id INNER JOIN matricula.ma_matricula ma ON c.matricula_id = ma.matricula_id
INNER JOIN academico.ac_apertura ac on ma.apertura_id = ac.apertura_id INNER JOIN academico.ac_apertura ac on ma.apertura_id = ac.apertura_id
WHERE c.plan_de_pago_anulado = false WHERE c.plan_de_pago_anulado = false
...@@ -48,7 +49,7 @@ WITH tb_lista_plan_pago AS (select c.plan_de_pago_id ...@@ -48,7 +49,7 @@ WITH tb_lista_plan_pago AS (select c.plan_de_pago_id
and ma.matricula_anulada = false and ma.matricula_anulada = false
and ac.ciclo_id = 28 and ac.ciclo_id = 28
and ac.periodo_academico_id = 14 and ac.periodo_academico_id = 14
and coalesce(c.to_update, false) and coalesce(cpdi.to_update, false)
) )
SELECT * SELECT *
FROM tb_lista_plan_pago FROM tb_lista_plan_pago
......
...@@ -18,7 +18,7 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou ...@@ -18,7 +18,7 @@ func readerFor(name string, pool *postgres.Pool, query string) (repositories.Sou
switch name { switch name {
case "students", "students_incremental": case "students", "students_incremental":
return postgres.NewStudentReader(pool, query), nil return postgres.NewStudentReader(pool, query), nil
case "payment_plans": case "payment_plans", "payment_plans_incremental":
return postgres.NewPaymentPlanReader(pool, query), nil return postgres.NewPaymentPlanReader(pool, query), nil
case "parents": case "parents":
return postgres.NewParentReader(pool, query), nil return postgres.NewParentReader(pool, query), nil
...@@ -79,6 +79,8 @@ func markerFor(name string, pool *postgres.Pool) repositories.ProcessedMarker { ...@@ -79,6 +79,8 @@ func markerFor(name string, pool *postgres.Pool) repositories.ProcessedMarker {
return postgres.NewBalotarioMarker(pool) return postgres.NewBalotarioMarker(pool)
case "students_incremental": case "students_incremental":
return postgres.NewStudentMarker(pool) return postgres.NewStudentMarker(pool)
case "payment_plans_incremental":
return postgres.NewPaymentPlanMarker(pool)
default: default:
return nil return nil
} }
......
-- Triggers y carga inicial para la sincronización incremental de planes de pago.
--
-- caja.ca_plan_de_pago_intranet es la tabla de marcado: una fila por plan de pago con
-- to_update (pendiente de re-sincronizar) y sync_last_update (cuándo lo procesó el
-- synchronizer). El pipeline payment_plans_incremental lee los planes con to_update=true
-- (LoadDataPaymentPlan) y, al terminar, el PaymentPlanMarker resetea to_update=false y
-- estampa sync_last_update=now().
--
-- Este archivo hace tres cosas:
-- 1. Función que marca en ca_plan_de_pago_intranet el plan afectado.
-- 2. Triggers AFTER INSERT / AFTER UPDATE sobre caja.ca_plan_de_pago.
-- 3. Carga inicial (backfill) que marca todos los planes hoy vigentes.
--
-- Ejecutar contra cada ambiente. Es idempotente (DROP TRIGGER IF EXISTS + CREATE OR REPLACE).
-- No usar CONCURRENTLY acá, así que puede ir dentro de una transacción si se desea.
-- 1) Función de marcado ------------------------------------------------------------
-- Upsert por plan_de_pago_id (PK de la tabla intranet). Solo escribe si el flag aún no
-- está en true, para no generar WAL/dead tuples de más cuando ya estaba marcado.
CREATE OR REPLACE FUNCTION caja.fn_marcar_plan_de_pago_to_update()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
INSERT INTO caja.ca_plan_de_pago_intranet (plan_de_pago_id, to_update)
VALUES (NEW.plan_de_pago_id, TRUE)
ON CONFLICT (plan_de_pago_id) DO UPDATE
SET to_update = TRUE
WHERE caja.ca_plan_de_pago_intranet.to_update IS NOT TRUE;
RETURN NULL;
END;
$function$;
-- 2) Triggers sobre caja.ca_plan_de_pago ------------------------------------------
-- INSERT: todo plan nuevo debe sincronizarse.
DROP TRIGGER IF EXISTS trg_ca_plan_de_pago_after_insert ON caja.ca_plan_de_pago;
CREATE TRIGGER trg_ca_plan_de_pago_after_insert
AFTER INSERT ON caja.ca_plan_de_pago
FOR EACH ROW
EXECUTE PROCEDURE caja.fn_marcar_plan_de_pago_to_update();
-- UPDATE: solo cuando cambia algo real de la fila (OLD.* IS DISTINCT FROM NEW.*),
-- para no re-marcar en updates no-op. ca_plan_de_pago no tiene to_update/sync_last_update
-- propios, por eso no hace falta la guarda extra que usan persona/matricula.
DROP TRIGGER IF EXISTS trg_ca_plan_de_pago_after_update ON caja.ca_plan_de_pago;
CREATE TRIGGER trg_ca_plan_de_pago_after_update
AFTER UPDATE ON caja.ca_plan_de_pago
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE PROCEDURE caja.fn_marcar_plan_de_pago_to_update();
-- 3) Carga inicial (backfill) ------------------------------------------------------
-- Marca los planes que hoy cumplen el mismo filtro que LoadDataPaymentPlan (no anulados,
-- matrícula vigente, ciclo 28 / período 14), para que la primera corrida incremental los
-- recoja y luego los resetee. No toca los que ya están en to_update=true.
INSERT INTO caja.ca_plan_de_pago_intranet (plan_de_pago_id, to_update)
SELECT c.plan_de_pago_id, TRUE
FROM caja.ca_plan_de_pago c
INNER JOIN matricula.ma_matricula ma ON c.matricula_id = ma.matricula_id
INNER JOIN academico.ac_apertura ac ON ma.apertura_id = ac.apertura_id
WHERE c.plan_de_pago_anulado = false
AND ma.matricula_retirado = false
AND ma.matricula_anulada = false
AND ac.ciclo_id = 28
AND ac.periodo_academico_id = 14
ON CONFLICT (plan_de_pago_id) DO UPDATE
SET to_update = TRUE
WHERE caja.ca_plan_de_pago_intranet.to_update IS NOT TRUE;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment