checkAndCreateReminders method

Future<void> checkAndCreateReminders(
  1. String orgId
)

Implementation

Future<void> checkAndCreateReminders(String orgId) async {
  final assignments = await getAssignmentsForOrg(orgId);
  final now = DateTime.now().toUtc();

  for (final a in assignments) {
    if (a.dueDate == null) continue;
    final due = a.dueDate!;
    final diff = due.difference(now);

    String? threshold;
    String? type;
    String? title;
    String? body;

    if (diff.isNegative) {
      threshold = 'overdue';
      type = 'assignment_overdue';
      title = 'Assignment overdue';
      body = '${a.domainName ?? "A curriculum"} is past due';
    } else if (diff.inDays <= 1) {
      threshold = '1d';
      type = 'due_date_approaching';
      title = 'Due tomorrow';
      body = '${a.domainName ?? "A curriculum"} is due soon';
    } else if (diff.inDays <= 3) {
      threshold = '3d';
      type = 'due_date_approaching';
      title = 'Due in ${diff.inDays} days';
      body = '${a.domainName ?? "A curriculum"} is due soon';
    }

    if (threshold == null) continue;

    // Resolve recipients
    List<String> recipientIds = [];
    if (a.userId != null) {
      recipientIds = [a.userId!];
    } else if (a.teamId != null) {
      final members = await getTeamMembers(a.teamId!);
      recipientIds = members.map((m) => m.userId).toList();
    }
    if (recipientIds.isEmpty) continue;

    // Check dedup: does a notification already exist for this
    // assignment + threshold + any of these recipients?
    final existing = await _client
        .from('org_notifications')
        .select('id')
        .eq('org_id', orgId)
        .eq('type', type!)
        .contains('metadata', {'assignment_id': a.id, 'threshold': threshold})
        .inFilter('user_id', recipientIds)
        .limit(1);

    if ((existing as List<dynamic>).isNotEmpty) continue;

    await _client.rpc(
      'notify_org_event',
      params: {
        'p_org_id': orgId,
        'p_type': type,
        'p_title': title,
        'p_body': body,
        'p_metadata': {
          'assignment_id': a.id,
          'domain_id': a.domainId,
          'domain_name': a.domainName,
          'threshold': threshold,
        },
        'p_recipient_ids': recipientIds,
      },
    );
  }
}