
#!/usr/bin/perl
use strict;
use Data::Show;

use lib '/home/sites/clm.dmadelivers.com/www/clmapp/lib';
use CLMApp::Schema;
my $dbix = CLMApp::Schema->connect("dbi:mysql:host=rds1.dmadelivers.com;db=dmaclm", 'dmaclm', '3lUz1OV2!',{unsafe=>1,RaiseError=>0,PrintError=>1});
$ENV{DBIC_TRACE} = 1;


&reconcile;


sub reconcile{


	my @cs = $dbix->resultset('Customer')->search({ 
		'me.statusid' => 1,
		'-or' => [ 
			{'me.invoicesystem' => {'>' => 0}},
			{'me.ordersystem' => {'>' => 0}},
		],
		'customersystem.customersystemid' => undef
	},{
		prefetch => [qw/customersystem/],					
		result_class=>'DBIx::Class::ResultClass::HashRefInflator',
	});



	# 901040071

	# show \@cs;

	
	my @oisystems = $dbix->resultset('OrderInvoiceSystem')->search({ 
		# deleted => 0,
	},{

		result_class=>'DBIx::Class::ResultClass::HashRefInflator',
	});


	# show \@oisystems;

	my $oisystems = {};
	foreach my $ois (@oisystems){

		$oisystems->{ $ois->{id} } = $ois;
	}


	# show $oisystems;

	my @csobjs;

	foreach my $cs (@cs){

		if($cs->{invoicesystem} > 0){
			my $csobj = {
				customerid => $cs->{customerid},
				systemtype => 1,
				systemid => $cs->{invoicesystem},
				systemfiles => $oisystems->{ $cs->{invoicesystem} }->{systemfiles},
				marketid => $cs->{marketid},
				accountingcode => $cs->{accountingcode},
				filecode => $cs->{filecode},
				active => 1
			};
			push(@csobjs, $csobj);
		}
		if($cs->{ordersystem} > 0){
			my $csobj = {
				customerid => $cs->{customerid},
				systemtype => 0,
				systemid => $cs->{ordersystem},
				systemfiles => $oisystems->{ $cs->{ordersystem} }->{systemfiles},
				marketid => $cs->{marketid},
				accountingcode => $cs->{accountingcode},
				filecode => $cs->{filecode},
				active => 1
			};

			push(@csobjs, $csobj);
		}


	}

	show \@csobjs;

	foreach my $cso (@csobjs){
		if($cso->{systemid}){
			$dbix->resultset('CustomerSystem')->create($cso);
		}

	}




}


sub deleteparty{

# problem: difference between delete and implementation error where there may be unassigned legacy values vs. delete

# SELECT * FROM CustomerSystem csys LEFT JOIN Customer cs ON cs.CustomerId=csys.CustomerId WHERE cs.StatusId=1 AND  csys.systemtype=1 AND cs.invoicesystem=0;

# SELECT * FROM CustomerSystem csys LEFT JOIN Customer cs ON cs.CustomerId=csys.CustomerId WHERE cs.StatusId=1 AND  csys.systemtype=0 AND cs.ordersystem=0;


}




1;