route.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { getServerSession } from 'next-auth';
  3. import { authOptions } from '@/lib/auth';
  4. import { db } from '@/lib/db';
  5. import { sections, classes, periods, eq, and } from '@/lib/db/schema';
  6. export async function GET() {
  7. try {
  8. const session = await getServerSession(authOptions);
  9. if (!session?.user || session.user.role !== 'admin') {
  10. return NextResponse.json(
  11. { error: 'No autorizado' },
  12. { status: 401 }
  13. );
  14. }
  15. const allSections = await db
  16. .select({
  17. id: sections.id,
  18. name: sections.name,
  19. classId: sections.classId,
  20. className: classes.name,
  21. classCode: classes.code,
  22. periodId: sections.periodId,
  23. periodName: periods.name,
  24. maxStudents: sections.maxStudents,
  25. isActive: sections.isActive,
  26. createdAt: sections.createdAt,
  27. })
  28. .from(sections)
  29. .leftJoin(classes, eq(sections.classId, classes.id))
  30. .leftJoin(periods, eq(sections.periodId, periods.id))
  31. .orderBy(classes.code, sections.name);
  32. return NextResponse.json(allSections);
  33. } catch (error) {
  34. console.error('Error fetching sections:', error);
  35. return NextResponse.json(
  36. { error: 'Error interno del servidor' },
  37. { status: 500 }
  38. );
  39. }
  40. }
  41. export async function POST(request: NextRequest) {
  42. try {
  43. const session = await getServerSession(authOptions);
  44. if (!session?.user || session.user.role !== 'admin') {
  45. return NextResponse.json(
  46. { error: 'No autorizado' },
  47. { status: 401 }
  48. );
  49. }
  50. const { name, classId, periodId, maxStudents } = await request.json();
  51. // Validaciones
  52. if (!name || !classId || !periodId || !maxStudents) {
  53. return NextResponse.json(
  54. { error: 'Todos los campos son requeridos' },
  55. { status: 400 }
  56. );
  57. }
  58. if (typeof maxStudents !== 'number' || maxStudents < 1) {
  59. return NextResponse.json(
  60. { error: 'El número máximo de estudiantes debe ser mayor a 0' },
  61. { status: 400 }
  62. );
  63. }
  64. // Verificar si la clase existe
  65. const existingClass = await db
  66. .select()
  67. .from(classes)
  68. .where(eq(classes.id, classId))
  69. .limit(1);
  70. if (existingClass.length === 0) {
  71. return NextResponse.json(
  72. { error: 'La clase seleccionada no existe' },
  73. { status: 400 }
  74. );
  75. }
  76. // Verificar si el período existe
  77. const existingPeriod = await db
  78. .select()
  79. .from(periods)
  80. .where(eq(periods.id, periodId))
  81. .limit(1);
  82. if (existingPeriod.length === 0) {
  83. return NextResponse.json(
  84. { error: 'El período seleccionado no existe' },
  85. { status: 400 }
  86. );
  87. }
  88. // Verificar si ya existe una sección con el mismo nombre para la misma clase y período
  89. const existingSection = await db
  90. .select()
  91. .from(sections)
  92. .where(and(
  93. eq(sections.name, name),
  94. eq(sections.classId, classId),
  95. eq(sections.periodId, periodId)
  96. ))
  97. .limit(1);
  98. if (existingSection.length > 0) {
  99. return NextResponse.json(
  100. { error: 'Ya existe una sección con este nombre para la misma clase y período' },
  101. { status: 400 }
  102. );
  103. }
  104. // Crear sección
  105. const [newSection] = await db
  106. .insert(sections)
  107. .values({
  108. name,
  109. classId,
  110. periodId,
  111. maxStudents,
  112. isActive: true,
  113. })
  114. .returning({
  115. id: sections.id,
  116. name: sections.name,
  117. classId: sections.classId,
  118. periodId: sections.periodId,
  119. maxStudents: sections.maxStudents,
  120. isActive: sections.isActive,
  121. createdAt: sections.createdAt,
  122. });
  123. return NextResponse.json(newSection, { status: 201 });
  124. } catch (error) {
  125. console.error('Error creating section:', error);
  126. return NextResponse.json(
  127. { error: 'Error interno del servidor' },
  128. { status: 500 }
  129. );
  130. }
  131. }