+#!/usr/bin/perl
+use strict;
+use warnings;
+use DateTime;
+use OpenSRF::AppSession;
+use OpenILS::Utils::CStoreEditor;
+use OpenILS::Utils::Cronscript;
+binmode(STDOUT, ":utf8");
+my %defaults = (
+ 'osrf-config=s' => '/openils/conf/opensrf_core.xml',
+ 'start-date=s' => DateTime->now->strftime('%F'),
+ 'end-date=s' => '',
+ 'event-defs=s' => '',
+ 'verbose' => 0
+);
-my $header = <<CSV;
-"Media Type","Language","Notice Type","Notification Level","Patron Number","Patron Title","Patron First Names","Patron Surname","Telephone Number","Email Address","Library Code","Site Code","Site Name","Item Barcode","Due Date","Item Title","Transaction ID"
-CSV
+sub help {
+ print <<HELP;
+
+Collect CSV notification output and deliver to 3rd party
+
+# collection notifications for today for the selected defs
+$0 --event-def 104,105,106
+
+# collect a week of notifications
+$0 --event-def 104,105,106 --start-date 2012-01-01 --end-date 2012-01-07
+
+HELP
+ exit;
+}
+
+my $o = OpenILS::Utils::Cronscript->new(\%defaults);
+my $opts = $o->MyGetOptions();
+
+# TODO: skip cronscript's help
+help() if $opts->{help};
+
+my $verbose = $opts->{'verbose'};
+my $start_date = $opts->{'start-date'} || '';
+my $end_date = $opts->{'end-date'} || '';
+
+my @event_defs = split(/,/, $opts->{'event-defs'});
+
+if ($verbose) {
+ print "processing event_defs = @event_defs\n";
+ print "start_date = $start_date\n";
+ print "end_date = $end_date\n";
+}
+
+my %date_filter;
+$date_filter{run_time} = {'>=' => $start_date} if $start_date;
+$date_filter{run_time} = {'<' => $end_date} if $end_date;
+
+$o->bootstrap;
+
+my $ses = OpenSRF::AppSession->create('open-ils.cstore');
+my $req = $ses->request(
+ 'open-ils.cstore.json_query', {
+ select => {ateo => ['data']},
+ from => {
+ ateo => {
+ atev => {
+ filter => {
+ state => 'complete',
+ %date_filter
+ },
+ join => {
+ atevdef => {
+ filter => {id => \@event_defs}
+ }
+ }
+ }
+ }
+ }
+ }
+);
+
+# header
+print '"Media Type","Language","Notice Type","Notification Level",';
+print '"Patron Number","Patron Title","Patron First Names","Patron Surname",';
+print '"Telephone Number","Email Address","Library Code","Site Code",';
+print '"Site Name","Item Barcode","Due Date","Item Title","Transaction ID"';
+print "\n";
+
+# dump the CSV chunk from each event output
+while (my $resp = $req->recv(timeout => 12000)) {
+ my $content = $resp->content or next;
+ print $content->{data};
+}