Commit d979718e by Percy Quispe Huarcaya

feat: agregar sync estudiantes

parent 08415506
......@@ -47,6 +47,7 @@ All endpoints prefixed with `/api/v1`.
- `GET /api/v1/health` — checks Postgres and Mongo connectivity.
- `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/payment_plans/trigger` / `GET /api/v1/sync/payment_plans/status` — payment_plans 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).
......
......@@ -104,6 +104,7 @@ SCHEDULERS_ENABLED=false
# Habilitación de schedulers por módulo (true/false). El global SCHEDULERS_ENABLED apaga todos.
SYNC_STUDENTS_ENABLED=true
SYNC_STUDENTS_INCREMENTAL_ENABLED=true
SYNC_PAYMENT_PLANS_ENABLED=true
SYNC_PARENTS_ENABLED=true
SYNC_USERS_ENABLED=true
......
package entities
import "time"
import (
"fmt"
"time"
)
type BalotarioCurso struct {
BalotarioID int `bson:"balotario_id" json:"balotario_id"`
......@@ -60,3 +63,12 @@ func (r *Balotario) Refs() []BalotarioRef {
}
return refs
}
func (r *Balotario) RefLogLines(verb, estado string) []string {
refs := r.Refs()
lines := make([]string, 0, len(refs))
for _, ref := range refs {
lines = append(lines, fmt.Sprintf("%s matrícula %s en Mongo con matricula_id: %d y balotario_id: %d", verb, estado, ref.MatriculaID, ref.BalotarioID))
}
return lines
}
package entities
import "time"
import (
"fmt"
"time"
)
type Student struct {
StudentID int `bson:"student_id"`
......@@ -30,6 +33,7 @@ type Student struct {
SignedCSEComplementaryInfo bool `bson:"firmo_cse"`
SignedDataProtection bool `bson:"firmo_proteccion_datos"`
SignedInternalRegulations bool `bson:"firmo_reglamento"`
PersonaID int `bson:"-" json:"-"`
CreatedAt time.Time `bson:"created_at"`
UpdatedAt time.Time `bson:"updated_at"`
RowHash string `bson:"row_hash,omitempty" json:"-"`
......@@ -46,3 +50,7 @@ func (s *Student) SetRowHash(h string) {
func (s *Student) SetCreatedAt(t time.Time) {
s.CreatedAt = t
}
func (s *Student) RefLogLines(verb, estado string) []string {
return []string{fmt.Sprintf("%s estudiante %s en Mongo con student_id: %d y enrollment_id: %d", verb, estado, s.StudentID, s.EnrollmentID)}
}
......@@ -28,3 +28,9 @@ type RowHashSetter interface {
type CreatedAtSetter interface {
SetCreatedAt(t time.Time)
}
// IncrementalRefLog lo implementan las entidades de las tuberías incrementales para describir
// en el log qué registros del origen quedaron reflejados en Mongo.
type IncrementalRefLog interface {
RefLogLines(verb, estado string) []string
}
......@@ -77,6 +77,16 @@ var Pipelines = []PipelineDef{
DefaultInterval: 90 * time.Minute,
},
{
Name: "students_incremental",
PGQuery: postgres.LoadDataStudent,
MongoCollection: "students",
MongoDeletedCollection: "deleted_students",
IDField: "student_id",
StateID: 15,
Incremental: true,
DefaultInterval: 90 * time.Minute,
},
{
Name: "attendance",
PGQuery: postgres.AttendanceQuery,
MongoCollection: "c_attendance",
......
......@@ -55,7 +55,7 @@ CREATE TABLE IF NOT EXISTS sync_state (
);
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')
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')
ON CONFLICT (id) DO NOTHING;
`
......
package postgres
import (
"context"
"fmt"
"log"
"sort"
"intranet-synchronizer/internal/domain/entities"
"intranet-synchronizer/internal/domain/repositories"
)
type StudentMarker struct {
pool *Pool
}
func NewStudentMarker(pool *Pool) repositories.ProcessedMarker {
return &StudentMarker{pool: pool}
}
const resetPersonaToUpdateSQL = `
UPDATE persona.pe_persona
SET to_update = false, sync_last_update = now()
WHERE coalesce(to_update, false)
AND persona_id = ANY($1)`
const resetMatriculaToUpdateSQL = `
UPDATE matricula.ma_matricula
SET to_update = false, sync_last_update = now()
WHERE coalesce(to_update, false)
AND matricula_id = ANY($1)`
func (m *StudentMarker) MarkProcessed(ctx context.Context, rows []entities.SyncRow) error {
personaIDs, enrollmentIDs := studentRefs(rows)
if len(personaIDs) == 0 && len(enrollmentIDs) == 0 {
return nil
}
if _, err := m.pool.Pool.Exec(ctx, resetPersonaToUpdateSQL, personaIDs); err != nil {
return fmt.Errorf("reset persona to_update: %w", err)
}
if _, err := m.pool.Pool.Exec(ctx, resetMatriculaToUpdateSQL, enrollmentIDs); err != nil {
return fmt.Errorf("reset matricula to_update: %w", err)
}
for _, row := range rows {
student, ok := row.Doc.(*entities.Student)
if !ok {
continue
}
log.Printf("[students_incremental] Paso 3: actualizar persona.pe_persona to_update=false con persona_id: %d y matricula.ma_matricula to_update=false con enrollment_id: %d", student.PersonaID, student.EnrollmentID)
}
return nil
}
func studentRefs(rows []entities.SyncRow) (personaIDs, enrollmentIDs []int) {
seenPersonas := make(map[int]struct{})
seenEnrollments := make(map[int]struct{})
for _, row := range rows {
student, ok := row.Doc.(*entities.Student)
if !ok {
continue
}
if student.PersonaID != 0 {
if _, exists := seenPersonas[student.PersonaID]; !exists {
seenPersonas[student.PersonaID] = struct{}{}
personaIDs = append(personaIDs, student.PersonaID)
}
}
if student.EnrollmentID != 0 {
if _, exists := seenEnrollments[student.EnrollmentID]; !exists {
seenEnrollments[student.EnrollmentID] = struct{}{}
enrollmentIDs = append(enrollmentIDs, student.EnrollmentID)
}
}
}
sort.Ints(personaIDs)
sort.Ints(enrollmentIDs)
return personaIDs, enrollmentIDs
}
......@@ -30,7 +30,8 @@ SELECT e.estudiante_id as student_id,
COALESCE(ma.firmo_ficha_matricula_salud,false) as firmo_ficha_matricula_salud,
COALESCE(ma.firmo_cse,false) as firmo_cse,
COALESCE(ma.firmo_proteccion_datos,false) as firmo_proteccion_datos,
COALESCE(ma.firmo_reglamento,false) as firmo_reglamento
COALESCE(ma.firmo_reglamento,false) as firmo_reglamento,
e.persona_id as persona_id
FROM matricula.ma_estudiante e
INNER JOIN persona.pe_persona pp ON e.persona_id = pp.persona_id
INNER JOIN general.gn_catalogo_siiaa sexo on pp.sexo_id = sexo.catalogo_siiaa_id
......@@ -56,4 +57,4 @@ WHERE ac.periodo_academico_id = 14
and ma.matricula_anulada = false
`
const GetStudentToLoadData = `${StudentQuery} AND (coalesce(pp.to_update, false) or coalesce(ma.to_update, false))`
const LoadDataStudent = StudentQuery + ` AND (coalesce(pp.to_update, false) or coalesce(ma.to_update, false))`
......@@ -69,12 +69,13 @@ func FetchStudentBasics(ctx context.Context, pool *Pool, query string) (map[int]
signedCSEComplementaryInfo bool
signedDataProtection bool
signedInternalRegulations bool
personaID int
)
if err := rows.Scan(&studentID, &studentCode, &studentInternalCode, &paternalLastName, &maternalLastName,
&name, &dni, &birthday, &email, &genre, &branch, &level,
&grade, &shift, &classroomAttendanceID, &periodID, &cicleID, &enrollmentID, &enrollmentPhotoURL,
&enrollmentDate, &classroomBranchID,
&signedInsuranceWaiver, &signedEducationalServiceTerms, &signedEnrollmentHealthForm, &signedCSEComplementaryInfo, &signedDataProtection, &signedInternalRegulations); err != nil {
&signedInsuranceWaiver, &signedEducationalServiceTerms, &signedEnrollmentHealthForm, &signedCSEComplementaryInfo, &signedDataProtection, &signedInternalRegulations, &personaID); err != nil {
return nil, nil, fmt.Errorf("scan student row: %w", err)
}
......@@ -106,6 +107,7 @@ func FetchStudentBasics(ctx context.Context, pool *Pool, query string) (map[int]
SignedCSEComplementaryInfo: signedCSEComplementaryInfo,
SignedDataProtection: signedDataProtection,
SignedInternalRegulations: signedInternalRegulations,
PersonaID: personaID,
}
order = append(order, studentID)
}
......
......@@ -16,7 +16,7 @@ import (
func readerFor(name string, pool *postgres.Pool, query string) (repositories.SourceReader, error) {
switch name {
case "students":
case "students", "students_incremental":
return postgres.NewStudentReader(pool, query), nil
case "payment_plans":
return postgres.NewPaymentPlanReader(pool, query), nil
......@@ -77,6 +77,19 @@ func markerFor(name string, pool *postgres.Pool) repositories.ProcessedMarker {
switch name {
case "balotarios_incremental":
return postgres.NewBalotarioMarker(pool)
case "students_incremental":
return postgres.NewStudentMarker(pool)
default:
return nil
}
}
// cleanerFor devuelve el limpiador de arrays anidados de los módulos incrementales que lo
// necesitan (hoy solo balotarios, que reescribe periodos[]). Los demás no limpian nada.
func cleanerFor(name string, docRepo repositories.PeriodosCleaner) repositories.PeriodosCleaner {
switch name {
case "balotarios_incremental":
return docRepo
default:
return nil
}
......@@ -156,7 +169,7 @@ func Build(
var uc usecase.RunSyncPipelineUseCase
if p.Incremental {
uc = usecase.NewRunIncrementalSyncUseCase(p.Name, reader, docRepo, docRepo, state, markerFor(p.Name, pool), docRepo, time.Now)
uc = usecase.NewRunIncrementalSyncUseCase(p.Name, reader, docRepo, docRepo, state, markerFor(p.Name, pool), cleanerFor(p.Name, docRepo), time.Now)
} else {
uc = usecase.NewRunSyncPipelineUseCase(p.Name, reader, docRepo, docRepo, archiver, state, docRepo, changeLog, time.Now)
}
......
......@@ -69,7 +69,7 @@ func (s *runIncrementalSync) Run(ctx context.Context) error {
for i, row := range rows {
ids[i] = row.ID
}
log.Printf("[%s] Paso 1: obtener matrículas de Postgres con to_update=true -> %d matrícula(s): %v", s.name, len(ids), ids)
log.Printf("[%s] Paso 1: obtener registros de Postgres con to_update=true -> %d registro(s): %v", s.name, len(ids), ids)
var currentDocs map[int]map[string]interface{}
if s.fetcher != nil && len(ids) > 0 {
......@@ -123,7 +123,7 @@ func (s *runIncrementalSync) Run(ctx context.Context) error {
}
for _, row := range changed {
doc, ok := row.Doc.(*entities.Balotario)
logger, ok := row.Doc.(entities.IncrementalRefLog)
if !ok {
continue
}
......@@ -133,8 +133,8 @@ func (s *runIncrementalSync) Run(ctx context.Context) error {
verbo, estado = "actualizar", "existente"
}
for _, ref := range doc.Refs() {
log.Printf("[%s] Paso 2: %s matrícula %s en Mongo con matricula_id: %d y balotario_id: %d", s.name, verbo, estado, ref.MatriculaID, ref.BalotarioID)
for _, line := range logger.RefLogLines(verbo, estado) {
log.Printf("[%s] Paso 2: %s", s.name, line)
}
}
log.Printf("[%s] Paso 2: fin -> nuevas=%d existentes=%d", s.name, created, updated)
......
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