package WebService::NetSuite::SuiteTalk::Role::AccountingPeriod;

use Modern::Perl '2011';    ## no critic (Modules::ProhibitUseQuotedVersion)

our $VERSION = '0.002';     # TRIAL VERSION
use utf8;
use DateTime::Format::XSD;
use DateTime::Span;
use List::Util 'first';
use Moo::Role;
use MooX::HandlesVia;
use MooX::Types::MooseLike::Base qw(ArrayRef HashRef InstanceOf Ref Value);
use Tree::DAG_Node;

requires 'connection';

has _accounting_period_records => ( is => 'lazy', isa => ArrayRef [HashRef] );

sub _build__accounting_period_records {
    my $self = shift;
    my ( $answer_ref, $trace )
        = $self->connection->search(
        searchRecord => { XSI_TYPE => 'listAcct:AccountingPeriodSearch' }, );

    ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
    my $result_ref = $answer_ref->{parameters}{searchResult};
    if ( 'HASH' ne ref $result_ref or not $result_ref->{status}{isSuccess} ) {
        for ( $trace->errors ) { $_->throw }
    }

    return $result_ref->{recordList}{record};
}

has _accounting_periods => (
    is          => 'lazy',
    isa         => HashRef [ HashRef [Ref] ],
    handles_via => 'Hash',
    handles     => {
        get_accounting_period => 'get',
        accounting_periods    => 'values',
    },
);

sub _build__accounting_periods {
    my $self = shift;

    my %accounting_periods;
    for my $record_ref ( @{ $self->_accounting_period_records } ) {
        my %period = %{$record_ref};
        my %span = map { $_ => _xsd_dateparse( $period{"${_}Date"} ) }
            qw(start end);

        # NetSuite uses xsd:dateTime but just uses dates.
        # We get around that by setting the end time to the next day minus
        # one nanosecond.
        $span{end}
            = $span{end}->add( days => 1 )->subtract( nanoseconds => 1 );

        $accounting_periods{ $period{internalId} } = {
            record => $record_ref,
            span   => DateTime::Span->from_datetimes(%span),
        };
    }
    return \%accounting_periods;
}

sub _xsd_dateparse {
    return DateTime::Format::XSD->parse_datetime(shift)
        ->truncate( to => 'day' );
}

has _accounting_period_trees => (
    is          => 'lazy',
    isa         => ArrayRef [ InstanceOf ['Tree::DAG_Node'] ],
    handles_via => 'Array',
    handles => { accounting_period_trees => 'elements' },
);

sub _build__accounting_period_trees {
    my $self = shift;

    my @roots;
    my @nodes = map { $self->_period_to_node($_) } $self->accounting_periods;
    for my $node (@nodes) {
        ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
        if ( not $node->attributes->{record}{parent} ) {
            push @roots => $node;
            next;
        }

        my $parent = first {
            $node->attributes->{record}{parent}{internalId}
                == $_->attributes->{record}{internalId};
        }
        @nodes;
        $parent->add_daughter($node);
    }
    return \@roots;
}

sub _period_to_node {
    my ( $self, $period_ref ) = @_;
    return if not ref 'HASH' eq $period_ref;

    my $node = Tree::DAG_Node->new();

    ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
    while ( my ( $attribute, $value ) = each %{$period_ref} ) {
        $node->attributes->{$attribute} = $value;
    }
    if ( exists $period_ref->{record}{periodName} ) {
        $node->name( $period_ref->{record}{periodName} );
    }

    return $node;
}

sub date_posting_period_ref {
    my $self = shift;
    my $dt   = DateTime::Format::XSD->parse_datetime(shift);

    # get the accounting period that contains our date with the most ancestors
    ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
    my @nodes = sort { ( $a->ancestors or 0 ) <=> ( $b->ancestors or 0 ) }
        grep { $_->attributes->{span}->contains($dt) }
        map  { $_->self_and_descendants } $self->accounting_period_trees
        or return;

    my %period_record = %{ $nodes[-1]->attributes->{record} };
    return {
        XSI_TYPE   => 'platformCore:RecordRef',
        type       => 'accountingPeriod',
        name       => $period_record{periodName},
        internalId => $period_record{internalId},
    };
}

sub posting_period_parameter {
    my $self = shift;
    my $xsd_datetime = shift or return;
    my $period_ref = $self->date_posting_period_ref($xsd_datetime) or return;
    return ( postingPeriod => $period_ref );
}

1;

# ABSTRACT: Role providing NetSuite accounting periods

__END__

=pod

=encoding UTF-8

=for :stopwords Mark Gardner ZipRecruiter cpan testmatrix url annocpan anno bugtracker rt
cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 NAME

WebService::NetSuite::SuiteTalk::Role::AccountingPeriod - Role providing NetSuite accounting periods

=head1 VERSION

version 0.002

=head1 SYNOPSIS

    use Moo;
    use Scalar::Util 'blessed';
    with 'WebService::NetSuite::SuiteTalk::Role::AccountingPeriod';

    has connection => (
        is       => 'ro',
        isa      => sub {
            die unless blessed $_[0]
                and $_[0]->isa('WebService::NetSuite::SuiteTalk');
        },
    );

    sub periods {
        my $self = shift;

        my @accounting_periods = $self->accounting_periods;
        my $first_period       = $self->get_accounting_period(1);

        my $period_record = $first_period->{record};
        my $period_span   = $first_period->{span};

        return;
    }

=head1 DESCRIPTION

This is a role for discovering the accounting periods available in a NetSuite
account.  It's meant to be applied to classes that use
C<WebService::NetSuite::SuiteTalk>.

Any error received when retrieving the list of accounting periods will throw
an exception.

=head1 METHODS

=head2 accounting_periods

Returns a reference to a hash where each key is the internal ID of a NetSuite
accounting period and its value is a hash reference with two keys:

=over

=item record

A hash reference containing the fields for the specific accounting period.

=item span

A L<DateTime::Span|DateTime::Span> object for the accounting period.

=back

=head2 accounting_period_trees

Returns a list of the accounting periods for the current NetSuite connection.
Each element is an instance of a L<Tree::DAG_Node|Tree::DAG_Node> whose
individual nodes describe the nested relationship between accounting periods.

=head2 get_accounting_period

Given an internal ID of a NetSuite accounting period, this will return a hash
reference with the two keys mentioned above under C<accounting_periods>.

=head2 date_posting_period_ref

Given a L<DateTime|DateTime> object, this will return a hash reference to
a NetSuite C<platformCore:RecordRef> of type C<accountingPeriod> for the
currently connected NetSuite account.

=head2 posting_period_parameter

Given a L<DateTime|DateTime> object, this will return a two-item list (i.e.,
a key-value pair) with the first itme being C<postingPeriod> and the second
item the results of a C<date_posting_period_ref> call on that
L<DateTime|DateTime>.

=head1 REQUIRED METHODS

=over

=item connection

This must be a method that returns a
C<WebService::NetSuite::SuiteTalk> object.

=back

=head1 SUPPORT

=head2 Perldoc

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

  perldoc WebService::NetSuite::SuiteTalk

=head2 Websites

The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.

=over 4

=item *

MetaCPAN

A modern, open-source CPAN search engine, useful to view POD in HTML format.

L<http://metacpan.org/release/WebService-NetSuite-SuiteTalk>

=item *

Search CPAN

The default CPAN search engine, useful to view POD in HTML format.

L<http://search.cpan.org/dist/WebService-NetSuite-SuiteTalk>

=item *

AnnoCPAN

The AnnoCPAN is a website that allows community annotations of Perl module documentation.

L<http://annocpan.org/dist/WebService-NetSuite-SuiteTalk>

=item *

CPAN Ratings

The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.

L<http://cpanratings.perl.org/d/WebService-NetSuite-SuiteTalk>

=item *

CPAN Forum

The CPAN Forum is a web forum for discussing Perl modules.

L<http://cpanforum.com/dist/WebService-NetSuite-SuiteTalk>

=item *

CPANTS

The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

L<http://cpants.cpanauthors.org/dist/WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers

The CPAN Testers is a network of smokers who run automated tests on uploaded CPAN distributions.

L<http://www.cpantesters.org/distro/W/WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers Matrix

The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.

L<http://matrix.cpantesters.org/?dist=WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers Dependencies

The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.

L<http://deps.cpantesters.org/?module=WebService::NetSuite::SuiteTalk>

=back

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the web
interface at
L<https://github.com/mjgardner/webservice-netsuite-suitetalk/issues>.
You will be automatically notified of any progress on the
request by the system.

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<https://github.com/mjgardner/webservice-netsuite-suitetalk>

  git clone git://github.com/mjgardner/webservice-netsuite-suitetalk.git

=head1 AUTHOR

Mark Gardner <mjgardner@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by ZipRecruiter.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
