#!/usr/bin/perl

=begin -------------------------------------------------------------------------
calculates records overdue for authorisation > 2 working days after report date
=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 report date
################################################################################

BEGIN {
    use FindBin qw($Bin); # warn $Bin;
    use lib (
        "$Bin/../../../lib",
        '/home/raj/perl5/lib/perl5',
    );
}

use Data::Dumper;
use Date::Calc qw(Delta_Days);
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 @rows = sprintf "%-8s %s %s\n", qw(LabNo Days Diagnosis);

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

RESULT:
while (my $ref = $result->hash) { # warn Dumper $ref; next;
	# calculate working days since report date:
    my $from  = DateTime::Format::MySQL->parse_datetime($ref->{reported})->ymd;
	my $to    = $tools->time_now->ymd;
	my $delta = LIMS::Local::Utils::delta_business_days($from, $to);

	# skip if less than 3 days since report:
    next RESULT if $delta <= $duration;
	
    # put labno in brackets if CMP:
    $ref->{labno} = sprintf '[%s]',
        $ref->{labno} if $ref->{screened_as} eq 'Outreach';

    my $row = sprintf "%-8s %s %s",
        $ref->{labno}, 
        $delta,
        $ref->{diagnosis};
    push @rows, $row;
} 

my %mail = (		
	config  => $config,
    subject => "Reports > $duration days unauthorised",
    message => join "\n", @rows,
); # warn Dumper \%mail;

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