#!/usr/bin/perl -w

BEGIN {
    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        exit 1;
    }
}


use Opals::Context;

use strict;
my $dbh = Opals::Context->dbh();;
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}
$| = 1;
my $sth=$dbh->prepare("select barcode from opl_itemStats where import=1 group by barcode having count(barcode)>1");
$sth->execute();
while(my($bc)=$sth->fetchrow_array){
    my($id,$rid)=$dbh->selectrow_array("select id,rid from opl_itemStats where barcode=? order by id limit 1",undef,$bc);
    $dbh->do("delete from opl_itemStats where import=1 && id>? && barcode=?", undef,$id,$bc);
    $dbh->do("delete r.* from opl_recordStats r left outer join opl_itemStats i using(statId) where r.rid=? && i.statId is null",undef,$rid);
     
}
exit 0;
################################################################################


#sub {
#}
############################################################
