package Business::BatchPayment::KeyBank;

use 5.006;
use strict;
use warnings;
our $VERSION = '0.01';

=head1 NAME

Business::BatchPayment::KeyBank - Key Bank check lockbox format

=head1 VERSION

Version 0.01

=head1 USAGE

See L<Business::BatchPayment> for general usage notes.  This is a
one-way, non-transport processor; you must supply the file to be 
received.

=head2 SYNOPSIS

use Business::BatchPayment;

my $processor = Business::BatchPayment->create( KeyBank =>
  input => 'mybatch.csv');

my @items = $processor->receive;

=head2 PROCESSOR ATTRIBUTES

None.

=cut

use DateTime;
use Text::CSV;
use Digest::MD5 qw( md5_hex );

use Moose;
with 'Business::BatchPayment::Processor';

sub incoming { 1 }
sub format_item { '' }

has '_csv' => (
  is => 'ro',
  default => sub { Text::CSV->new() },
);

sub parse_batch_id {
  my ($self, $content) = @_;
  # we just need it to be unique...
  return md5_hex($content);
}

sub parse_item {
  my ($self, $row) = @_;
  $self->_csv->parse($row);
  if ( !$self->_csv->status ) {
    die $self->_csv->error_diag . "\n";
  }
  my @f = $self->_csv->fields;
  foreach (@f) {
    s/^\s+//;
    s/\s+$//;
  }
  # INVOICEID, ACCOUNT_NUMBER, POSTDATE, AMOUNT, CHECK_NUMBER
  # date in YYYYMMDD format
  $f[2] =~ /^(\d{4})(\d{2})(\d{2})$/ or die "bad process date '$f[2]'\n";
  my $dt = eval { DateTime->new( year => $1, month => $2, day => $3 ) }
    or die "bad process date '$f[2]'\n";

  my $amount = $f[3] / 100;
  Business::BatchPayment->create(Item =>
    action          => 'payment',
    payment_type    => 'ECHECK',
    invoice_number  => $f[0],
    customer_id     => $f[1],
    payment_date    => $dt,
    amount          => $amount,
    check_number    => $f[3],
    order_number    => $f[3],  #?
    approved        => 1,
  );
}

__PACKAGE__->meta->make_immutable;

=head1 AUTHOR

Mark Wells, <mark@freeside.biz>

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Business::BatchPayment::KeyBank

Commercial support is available from Freeside Internet Services, Inc.

L<http://www.freeside.biz>

=head1 LICENSE AND COPYRIGHT

Copyright 2012 Mark Wells.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.


=cut

1;
