refreshMaterials method

Future<void> refreshMaterials({
  1. required int courseOfferingId,
  2. required String courseNumber,
})

Replaces the cached material list after a successful authenticated fetch.

Implementation

Future<void> refreshMaterials({
  required int courseOfferingId,
  required String courseNumber,
}) async {
  final dtos = await _authRepository.withAuth(() async {
    final courses = await _iSchoolPlusService.getCourseList();
    final course = courses.where(
      (course) => course.courseNumber == courseNumber,
    );
    if (course.isEmpty) return const <MaterialRefDto>[];
    return _iSchoolPlusService.getMaterials(course.first);
  }, sso: [.iSchoolPlusService]);

  final seen = <String>{};
  final valid = dtos
      .where(
        (dto) => switch (dto.href?.trim()) {
          final href? when href.isNotEmpty => seen.add(href),
          _ => false,
        },
      )
      .toList();
  await _database.transaction(() async {
    final existing = await (_database.select(
      _database.materials,
    )..where((row) => row.courseOffering.equals(courseOfferingId))).get();
    final classifications = {
      for (final material in existing)
        (material.iSchoolCourseId, material.href): material.streamable,
    };
    await (_database.delete(
      _database.materials,
    )..where((row) => row.courseOffering.equals(courseOfferingId))).go();
    for (final dto in valid) {
      await _database
          .into(_database.materials)
          .insert(
            MaterialsCompanion.insert(
              courseOffering: courseOfferingId,
              title: Value(dto.title?.trim()),
              href: Value(dto.href!.trim()),
              iSchoolCourseId: Value(dto.course.internalId),
              streamable: Value(
                classifications[(dto.course.internalId, dto.href!.trim())],
              ),
            ),
          );
    }
    await (_database.update(
      _database.courseOfferings,
    )..where((row) => row.id.equals(courseOfferingId))).write(
      CourseOfferingsCompanion(materialsFetchedAt: Value(DateTime.now())),
    );
  });
}