{"size": 1233, "ext": "js", "max_stars_repo_path": "src/extensions/dynamicassignment-batches/finished-replies/index.js", "max_stars_repo_name": "asalant/Spoke", "max_stars_repo_stars_event_min_datetime": "2020-01-22T19:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-22T19:15:32.000Z", "max_issues_repo_path": "src/extensions/dynamicassignment-batches/finished-replies/index.js", "max_issues_repo_name": "asalant/Spoke", "max_issues_repo_issues_event_min_datetime": "2020-04-26T18:29:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-26T19:20:43.000Z", "max_forks_repo_path": "src/extensions/dynamicassignment-batches/finished-replies/index.js", "max_forks_repo_name": "asalant/Spoke", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 3, "max_forks_count": null, "avg_line_length": 23.2641509434, "max_line_length": 67, "alphanum_fraction": 0.6358475264}
import { getContacts } from "../../../server/api/assignment";

export const name = "finished-replies";

export const displayName = () => "After finishing current replies";

export const requestNewBatchCount = async ({
  organization,
  campaign,
  assignment,
  texter,
  r,
  cacheableData,
  loaders
}) => {
  // START WITH SOME BASE-LINE THINGS EVERY POLICY SHOULD HAVE
  if (!campaign.use_dynamic_assignment || campaign.is_archived) {
    return 0;
  }
  if (assignment.max_contacts === 0 || !campaign.batch_size) {
    return 0;
  }
  const availableCount = await r.getCount(
    r
      .knex("campaign_contact")
      .where({
        campaign_id: campaign.id,
        is_opted_out: false,
        message_status: "needsMessage"
      })
      .whereNull("assignment_id")
  );
  // Make sure they don't have any needsResponse(s)
  if (availableCount) {
    const hasOpenReplies = await getContacts(
      assignment,
      {
        messageStatus: "needsResponse",
        validTimezone: true,
        isOptedOut: false
      },
      organization,
      campaign,
      true // forCount=true because we don't care about ordering
    ).first();
    if (hasOpenReplies) {
      return 0;
    }
  }

  return availableCount;
};
