#!/usr/bin/env perl

use strict;
use warnings;

my $JUST_TESTING = 0; # dumps xl file only
# export CENTRE=uclh; perl script/crons/monthly/lab_test_audit.pl # manual run

### recipients #################################################################
my @recipients = qw(raj wai.keong);                                            #
################################################################################

BEGIN {
	use lib '/home/raj/perl5/lib/perl5'; # *must* come before FindBin($Bin)
 	use FindBin qw($Bin); # warn $Bin; exit;
 	use lib $Bin . '/../../../lib';
 	# override default db test:
 	$ENV{ROSEDB_DEVINIT} = "$Bin/../../../config/rosedb_devinit_prod.pl";
}

use IO::All;
use Data::Printer;
use LIMS::Local::LIMS; # for LIMS::Model
use LIMS::Local::ScriptHelpers;

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

my $config = $tools->config(); 
my $today  = $tools->time_now;

my $filename = 'lab_test_audit_data.xls';

# provides access to LIMS::Model:
my $lims = LIMS::Local::LIMS->new({tools => $tools});

# 1st of month 2 months ago:
my $d1 = $today->clone->subtract( months => 2 );
# end of month, 2 months ago (ie yesterday minus 1 month):
my $d2 = $today->clone->subtract( months => 1 )->subtract( days => 1 );

my $subject = sprintf 'Lab test audit data [%s to %s]', $d1->dmy, $d2->dmy; # p $subject;

# args for Model::Roles::Query::_set_search_constraints():
my %args = (
    'date_from' => $d1, # '01/01/2014' # dates OK also
    'date_to'   => $d2, # '31/10/2014'
); # p %args; exit;

my $xl = $lims->model('Audit')->lab_test_turnaround_export(\%args);

if ($JUST_TESTING) {
    io($filename)->print($xl);  exit;
}

my %mail = (
	config  => $config,
	subject => $subject, 	
	filename   => $filename,
	attachment => $xl,
);
$tools->send_mail(\%mail, \@recipients);
