package WebService::NetSuite::SuiteTalk;

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

our $VERSION = '0.003';     # TRIAL VERSION
use utf8;
use List::Util 1.33;
use Moo;
use MooX::Types::MooseLike::Base qw(CodeRef HashRef);
use POSIX 'floor';
with 'WebService::NetSuite::SuiteTalk::Role::Connection';

has _calls => ( is => 'ro', isa => HashRef [CodeRef], default => sub { {} } );

sub _call {
    my ( $self, $operation_name, $parameters_ref, @call_options ) = @_;
    $self->_soap_action($operation_name);

    # cache compiled client code
    if ( not exists $self->_calls->{$operation_name} ) {
        $self->_calls->{$operation_name}
            = $self->wsdl->compileClient( $operation_name,
            transport => $self->transport );
    }

    # make the call and either return or throw an exception
    my @results;
    push @results => [
        $self->_calls->{$operation_name}->(
            passport   => $self->passport,
            parameters => $parameters_ref,
            @call_options,
        ),
    ];
    my ( $answer_ref, $trace ) = @{ $results[-1] };
    if ( not $answer_ref ) {
        for ( $trace->errors ) { $_->throw }
    }

    ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
    if ( my $faults_ref = $answer_ref->{Fault} ) {
        my $fault_name
            = $answer_ref->{ $faults_ref->{_NAME} }{error}{class}[2];
        if ((   List::Util::any { $fault_name eq $_ }
                qw(ExceededRecordCountFault ExceededRequestSizeFault)
            )
            and $operation_name =~ / List $/xms
            and exists $parameters_ref->{record}
            and 'ARRAY' eq ref $parameters_ref->{record}
            and @{ $parameters_ref->{record} } > 1
            )
        {
            push @results => map { $self->_call( @{$_} ) }
                _halve_array( @{ $parameters_ref->{record} } );
        }
    }

    return ( @results > 1 ? @results : @{ $results[0] } );
}

sub BUILD {
    my $instance = shift;
    for my $method ( map { $_->name } $instance->wsdl->operations ) {
        ## no critic (ProhibitNoStrict,ProhibitNoWarnings)
        no strict 'refs';
        no warnings 'redefine';
        *{$method} = sub {
            my $self = shift;
            return $self->_call(
                $method => ( 'HASH' eq ref $_[0] ? $_[0] : {@_} ) );
        };
    }
    return;
}

## no critic (Subroutines::RequireArgUnpacking)
sub _halve_array {
    my $item_split_idx = floor( $#_ / 2 );
    return ( [ @_[ 0 .. $item_split_idx ] ],
        [ @_[ ( $item_split_idx + 1 ) .. $#_ ] ] );
}

1;

# ABSTRACT: NetSuite SOAP interface that caches compiled calls in memory

__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 - NetSuite SOAP interface that caches compiled calls in memory

=head1 VERSION

version 0.003

=head1 SYNOPSIS

    use WebService::NetSuite::SuiteTalk;
    my $suitetalk = WebService::NetSuite::SuiteTalk->new(
        account_id    => '12345678',
        email_address => 'netsuite_customer@example.com',
        password      => 'sekrit',
        xsi_auto      => 1,
    );
    my $answer_ref = $suitetalk->changePassword(
        changePassword => {
            currentPassword => 'sekrit',
            newPassword     => 'tirkes',
            newPassword2    => 'tirkes',
            justThisAccount => 'true',
        },
    );

=head1 DESCRIPTION

This class provides an in-memory lazy cache for compiled SOAP calls using
L<NetSuite SuiteTalk|http://www.netsuite.com/portal/platform/developer/suitetalk.shtml>
web services. The first call to any SOAP method uses
L<XML::Compile::WSDL11|XML::Compile::WSDL11> to compile and execute that method
against the specified NetSuite SuiteTalk service; subsequent calls can vary the
parameters but will use the same compiled code.

=head1 METHODS

Available method names are dynamically loaded from the SuiteTalk WSDL file's
operations, and can be passed either a hash or reference to a hash with the
necessary parameters. In scalar context they return a reference to a hash
containing the results of the SOAP call; in list context they return the
results hashref and an L<XML::Compile::SOAP::Trace|XML::Compile::SOAP::Trace>
object suitable for debugging and exception handling.

If there is no result then an exception will be thrown.

=head2 Special note about list methods

NetSuite's list methods (e.g., C<addList>, C<deleteList>, C<getList>,
C<initializeList>, C<updateList>, C<upsertList>, and their asynchronous
counterparts C<asyncAddList>, C<asyncDeleteList>, C<asyncGetList>,
C<asyncInitializeList>, C<asyncUpdateList>, C<asyncUpsertList>) may all run
into the various governance measures implemented to prevent web serviced from
adversely affecting other users or the user experience. This module tries
to mitigate this by detecting when the C<ExceededRecordCountFault> or
C<ExceededRequestSizeFault> errors are triggered, and when detected splitting
the record list in half and sending it as separate requests, repeating if
necessary. Thus the results of list methods are returned as an array of
answers and traces, rather than a simple paired answer and trace. This is
reflected in the examples below.

As of this writing the following operations are published in the NetSuite
SuiteTalk API 2014.2 schema.  Consult NetSuite's Help Center for full
documentation on input and output parameters for each operation.

=head2 add

Example:

    use Moo;
    with 'WebServices::NetSuite::SuiteTalk::Role::Country';
    my $answer_ref = $suitetalk->add( record => {
        XSI_TYPE    => 'listRel:Customer',
        isPerson    => 1,
        firstName   => 'Joseph',
        middleName  => 'Random',
        lastName    => 'Netsuite',
        companyName => 'Acme',
        email       => 'joe@example.com',
        addressbookList => [
            {   defaultBilling => 1,
                addr1   => '123 Main Street',
                city    => 'Anytown',
                state   => 'CA',
                zip     => '99999',
                country => code2country('us'),
            },
        ],
    } );

=head2 addList

Example:

    use Moo;
    with 'WebServices::NetSuite::SuiteTalk::Role::Country';
    my $answer_ref = ( $suitetalk->addList( record => [
        {
            XSI_TYPE    => 'listRel:Customer',
            isPerson    => 1,
            firstName   => 'Joseph',
            middleName  => 'Random',
            lastName    => 'Netsuite',
            companyName => 'Acme',
            email       => 'joe@example.com',
            addressbookList => [
                {   defaultBilling => 1,
                    addr1   => '123 Main Street',
                    city    => 'Anytown',
                    state   => 'CA',
                    zip     => '99999',
                    country => code2country('us'),
                },
            ],
        },
        {
            XSI_TYPE    => 'listRel:Customer',
            isPerson    => 1,
            firstName   => 'Jennifer',
            middleName  => 'Random',
            lastName    => 'Netsuite',
            companyName => 'Acme',
            email       => 'jen@example.com',
            addressbookList => [
                {   defaultBilling => 1,
                    addr1   => '123 Main Street',
                    city    => 'Anytown',
                    state   => 'CA',
                    zip     => '99999',
                    country => code2country('us'),
                },
            ],
        },
    ] ) )[0][0];

=head2 asyncAddList

=head2 asyncDeleteList

=head2 asyncGetList

=head2 asyncInitializeList

=head2 asyncSearch

=head2 asyncUpdateList

=head2 asyncUpsertList

=head2 attach

=head2 changeEmail

=head2 changePassword

Example:

    my $answer_ref = $suitetalk->changePassword(
        changePassword => {
            currentPassword => 'sekrit',
            newPassword     => 'tirkes',
            newPassword2    => 'tirkes',
            justThisAccount => 'true',
        },
    );

=head2 checkAsyncStatus

=head2 delete

=head2 deleteList

=head2 detach

=head2 get

Example:

    my $answer_ref = $suitetalk->get( baseRef => {
        XSI_TYPE   => 'platformCore:RecordRef',
        type       => 'nonInventorySaleItem',
        externalId => '12345',
    } );

=head2 getAll

=head2 getAsyncResult

=head2 getBudgetExchangeRate

=head2 getConsolidatedExchangeRate

=head2 getCurrencyRate

=head2 getCustomizationId

=head2 getDataCenterUrls

Example:

    my $answer_ref = $suitetalk->getDataCenterUrls(account => '1234567');

=head2 getDeleted

=head2 getItemAvailability

=head2 getList

=head2 getPostingTransactionSummary

=head2 getSavedSearch

=head2 getSelectValue

Example:

    my $answer_ref = $suitetalk->getSelectValue(
        pageIndex        => 1,
        fieldDescription => { recordType => 'customer', field => 'leadSource' },
    );

=head2 getServerTime

=head2 initialize

Example:

    my $answer_ref = $suitetalk->initialize( initializeRecord => {
        type      => 'creditMemo',
        reference => { internalId => '12345', type => 'invoice' },
    } );

=head2 initializeList

=head2 login

=head2 logout

=head2 mapSso

=head2 search

Example:

    my $answer_ref = $suitetalk->search( searchRecord => {
        XSI_TYPE => 'platformCommon:TransactionSearchBasic',
        type     => {
            operator    => 'anyOf',
            searchValue => ['invoice'],
        },
    } );

=head2 searchMore

=head2 searchMoreWithId

=head2 searchNext

=head2 ssoLogin

=head2 update

Example:

    my $answer_ref = $suitetalk->update( record => {
        XSI_TYPE   => 'tranCust:CreditMemo',
        internalId => '12345'
        applyList  =>  {
            replaceAll => 0,
            apply => {
                apply => 1,
                total => '1.00',
                doc   => '12346',
                line  => 0,
            },
        },
    } );

=head2 updateInviteeStatus

=head2 updateInviteeStatusList

=head2 updateList

=head2 upsert

Example:

    use Moo;
    with 'WebServices::NetSuite::SuiteTalk::Role::Country';
    my $answer_ref = $suitetalk->upsert( record => {
        XSI_TYPE    => 'listRel:Customer',
        isPerson    => 1,
        firstName   => 'Joseph',
        middleName  => 'Random',
        lastName    => 'Netsuite',
        companyName => 'Acme',
        email       => 'joe@example.com',
        addressbookList => [
            {   defaultBilling => 1,
                addr1   => '123 Main Street',
                city    => 'Anytown',
                state   => 'CA',
                zip     => '99999',
                country => code2country('us'),
            },
        ],
    } );

=head2 upsertList

Example:

    use Moo;
    with 'WebServices::NetSuite::SuiteTalk::Role::Country';
    my $answer_ref = ( $suitetalk->upsertList( record => [
        {
            XSI_TYPE    => 'listRel:Customer',
            isPerson    => 1,
            firstName   => 'Joseph',
            middleName  => 'Random',
            lastName    => 'Netsuite',
            companyName => 'Acme',
            email       => 'joe@example.com',
            addressbookList => [
                {   defaultBilling => 1,
                    addr1   => '123 Main Street',
                    city    => 'Anytown',
                    state   => 'CA',
                    zip     => '99999',
                    country => code2country('us'),
                },
            ],
        },
        {
            XSI_TYPE    => 'listRel:Customer',
            isPerson    => 1,
            firstName   => 'Jennifer',
            middleName  => 'Random',
            lastName    => 'Netsuite',
            companyName => 'Acme',
            email       => 'jen@example.com',
            addressbookList => [
                {   defaultBilling => 1,
                    addr1   => '123 Main Street',
                    city    => 'Anytown',
                    state   => 'CA',
                    zip     => '99999',
                    country => code2country('us'),
                },
            ],
        },
    ] ) )[0][0];

=for Pod::Coverage BUILD

=head1 OTHER METHODS AND ATTRIBUTES

Because this class consumes the
C<WebService::NetSuite::SuiteTalk::Role::Connection> role, it also has that
role's attributes and methods. For example, you can use the C<user_agent>
attribute to access the L<LWP::UserAgent|LWP::UserAgent> used to retrieve and
call the SuiteTalk service, or the C<wsdl> method to access the underlying
L<XML::Compile::WSDL11|XML::Compile::WSDL11> object.

=head1 TESTING

The unit tests included with this distribution need to authenticate to a
NetSuite account with SuiteTalk Web Services enabled. To enable web services,
use the NetSuite web user interface and select the "Setup" menu, followed by
"Company", followed by "Enable Features", then select the "SuiteCloud" tab.
Make sure the "Web Services" checkbox is marked and select the "Save" button.

In addition, you need to set the following environment variables in order to
run the unit tests:

=over

=item C<PERL_TEST_NETSUITE_ACCOUNT>

=item C<PERL_TEST_NETSUITE_EMAIL>

=item C<PERL_TEST_NETSUITE_PASSWORD>

=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
