+ if ($form->{reqdate_unset_or_old}) {
+ $query .= qq| AND ((o.reqdate IS NULL) OR (o.reqdate < date_trunc('month', current_date)))|;
+ }
+
+ if (($form->{order_probability_value} || '') ne '') {
+ my $op = $form->{order_probability_value} eq 'le' ? '<=' : '>=';
+ $query .= qq| AND (o.order_probability ${op} ?)|;
+ push @values, trim($form->{order_probability_value});
+ }
+
+ if ($form->{expected_billing_date_from}) {
+ $query .= qq| AND (o.expected_billing_date >= ?)|;
+ push @values, conv_date($form->{expected_billing_date_from});
+ }
+
+ if ($form->{expected_billing_date_to}) {
+ $query .= qq| AND (o.expected_billing_date <= ?)|;
+ push @values, conv_date($form->{expected_billing_date_to});
+ }
+
+ if ($form->{intnotes}) {
+ $query .= qq| AND o.intnotes ILIKE ?|;
+ push(@values, like($form->{intnotes}));
+ }
+
+ if ($form->{phone_notes}) {
+ $query .= qq| AND (phone_notes.subject ILIKE ? OR phone_notes.body ILIKE ?)|;
+ push(@values, like($form->{phone_notes}), like($form->{phone_notes}));
+ }
+
+ if ($form->{parts_partnumber}) {
+ $query .= <<SQL;
+ AND EXISTS (
+ SELECT orderitems.trans_id
+ FROM orderitems
+ LEFT JOIN parts ON (orderitems.parts_id = parts.id)
+ WHERE (orderitems.trans_id = o.id)
+ AND (parts.partnumber ILIKE ?)
+ LIMIT 1
+ )
+SQL
+ push @values, like($form->{parts_partnumber});
+ }
+
+ if ($form->{parts_description}) {
+ $query .= <<SQL;
+ AND EXISTS (
+ SELECT orderitems.trans_id
+ FROM orderitems
+ WHERE (orderitems.trans_id = o.id)
+ AND (orderitems.description ILIKE ?)
+ LIMIT 1
+ )
+SQL
+ push @values, like($form->{parts_description});
+ }
+
+ if ($form->{all}) {
+ my @tokens = parse_line('\s+', 0, $form->{all});
+ # ordnumber quonumber customer.name vendor.name transaction_description
+ $query .= qq| AND (
+ o.ordnumber ILIKE ? OR
+ o.quonumber ILIKE ? OR
+ ct.name ILIKE ? OR
+ o.transaction_description ILIKE ?
+ )| for @tokens;
+ push @values, (like($_))x4 for @tokens;
+ }
+
+ my ($cvar_where, @cvar_values) = CVar->build_filter_query('module' => 'CT',
+ 'trans_id_field' => 'ct.id',
+ 'filter' => $form,
+ );
+ if ($cvar_where) {
+ $query .= qq| AND ($cvar_where)|;
+ push @values, @cvar_values;
+ }
+