示例#1
0
    def release_and_notify(self, week):
        # Update all reports for a given week and set preview = False, _and_
        # create notifications for all related users.

        # Capture which reports are previews before we release them. We'll base
        # the notifications on this list to make sure we're not notifying about
        # any reports that aren't previews.
        reports_to_release = Report.get_previews(week)

        # This is the "release" part.
        num_reports_released = Report.release_previews(week)

        # Now we have to load a bunch of data from the related teams,
        # classrooms, and users in order to create notifications.
        if len(reports_to_release) != num_reports_released:
            logging.error(
                "Report.get_previews() ({}) and Report.release_previews() "
                "({}) didn't hit the same number of rows.".format(
                    len(reports_to_release), num_reports_released))

        team_ids = {r.team_id for r in reports_to_release}
        classroom_ids = {
            r.classroom_id
            for r in reports_to_release if r.classroom_id
        }

        # Load all related teams and classrooms as a batch.
        teams = Team.get_by_id(team_ids)
        classrooms = Classroom.get_by_id(classroom_ids)

        t_index = {t.uid: t for t in teams}
        c_index = {c.uid: c for c in classrooms}
        p_index = {p.uid: p for p in Program.get()}
        notes = []
        for r in reports_to_release:
            team = t_index.get(r.team_id)
            program = p_index.get(team.program_id)
            classroom = c_index.get(r.classroom_id, None)
            result = self.notify_for_single_report(program, team, classroom)
            # result might be a list or None
            if result:
                notes += result

        Notification.put_multi(notes)

        return num_reports_released