#!/usr/bin/perl

=begin -------------------------------------------------------------------------
unscreened requests > 2 working days after registration
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

my $JUST_TESTING = 0; # email to ra.jones only

################################################################################
my @recipients = qw( douglas bagguley raj );
my $duration = 2; # how many working days since registration date
################################################################################

use lib '/home/raj/perl5/lib/perl5';
use Data::Dumper;

use FindBin qw($Bin); # warn $Bin;
use lib "$Bin/../../../lib";
use LIMS::Local::ScriptHelpers;

# get tools from LIMS::Local::ScriptHelpers:
my $tools = LIMS::Local::ScriptHelpers->new();
$tools->test_only($JUST_TESTING);

my $sql_lib = $tools->sql_lib();
my $config  = $tools->config(); 
my $dbix    = $tools->dbix();

my $query = $sql_lib->retr('unscreened_requests');
my $result = $dbix->query($query);

my @rows;
while (my $vals = $result->hash) { # warn Dumper \@vals;
	# calculate working days since registration (delta):
    my $from  = DateTime::Format::MySQL->parse_date($vals->{registered})->ymd;
	my $to    = $tools->time_now->ymd;
	
	my $delta = $vals->{delta}
		= LIMS::Local::Utils::delta_business_days($from, $to);	
	next unless $delta > $duration; # warn $delta;
	
    my $row = join ' :: ',
		@{$vals}{ qw(labno registered specimen location delta) };
    push @rows, $row;
} # warn Dumper \@rows;

exit unless @rows;

my %mail = (		
	config  => $config,
    subject => "Requests > $duration days unscreened",
    message => join "\n", @rows,
); # warn Dumper [\%mail, \@recipients]; exit;

$tools->send_mail(\%mail, \@recipients);
