- my @items = qsearch({
- 'table' => "h_$table",
- 'addl_from' => $table_join{$table},
- 'hashref' => { 'history_date' => { op=>'>=', value=>$newer_than }, },
- 'extra_sql' => ' AND custnum = '. $cust_main->custnum,
- });
- %foundsvcs = (%foundsvcs, map { $_->svcnum => 1 } @items)
- if $table =~ /^svc/;
- push @history, @items;
+ if ($tables{$table} eq 'Contact') {
+
+ my $contact_addl_from = "
+ INNER JOIN (select contactnum, min(history_date) as min_history_date, max(history_date) as max_history_date, max(historynum) as max_historynum FROM h_cust_contact WHERE custnum = ".$cust_main->custnum." AND history_date >= $newer_than GROUP BY contactnum) a ON h_cust_contact.contactnum = a.contactnum
+ ";
+
+ ## get list with add and remove dates of contacts for customer
+ my @h_cust_contacts = qsearch({
+ 'table' => "h_cust_contact",
+ 'select' => "a.contactnum, a.min_history_date, a.max_history_date, history_action AS max_history_action",
+ 'addl_from' => $contact_addl_from,
+ 'extra_sql' => " WHERE historynum = a.max_historynum",
+ });
+
+ foreach my $c (@h_cust_contacts) {
+ my $max_date_sql;
+ $max_date_sql = " AND history_date <= ".$c->{Hash}->{max_history_date} if $c->{Hash}->{max_history_action} eq 'delete';
+
+ ## get history of contact while attached to customer
+ my @contact_history = qsearch({
+ 'table' => "h_$table",
+ 'hashref' => {
+ 'history_date' => { op=>'>=', value=>($c->{Hash}->{min_history_date} - 1) },
+ 'contactnum' => $c->{Hash}->{contactnum},
+ },
+ 'extra_sql' => $max_date_sql,
+ });
+ push @history, @contact_history;
+ }
+ }
+ else {
+ my @items = qsearch({
+ 'table' => "h_$table",
+ 'addl_from' => $table_join{$table},
+ 'hashref' => { 'history_date' => { op=>'>=', value=>$newer_than }, },
+ 'extra_sql' => $extra_sql,
+ });
+ %foundsvcs = (%foundsvcs, map { $_->svcnum => 1 } @items)
+ if $table =~ /^svc/;
+ push @history, @items;
+ }