Class: Report::BookOfBusiness::BookOfBusiness

Inherits:
Object
  • Object
show all
Defined in:
app/services/report/book_of_business/book_of_business.rb

Overview

Service object: book of business.

Defined Under Namespace

Classes: Result

Class Method Summary collapse

Class Method Details

.build_int_in_clause(column, values) ⇒ Object

SQL fragment helpers: every interpolated user-supplied value goes through
one of these. Integer() coerces ID lists so any non-numeric raises before
reaching SQL; connection.quote escapes all grammar quirks for strings.

Parameters:

  • column (Object)
  • values (Object)


27
28
29
30
31
32
33
34
# File 'app/services/report/book_of_business/book_of_business.rb', line 27

def self.build_int_in_clause(column, values)
  return '' if values.blank?

  ids = Array(values).map { |v| Integer(v) }
  return '' if ids.empty?

  " and #{column} in (#{ids.join(',')})"
end

.build_string_in_clause(column, values) ⇒ Object

Build string in clause.

Parameters:

  • column (Object)
  • values (Object)

Returns:

  • (Object)


40
41
42
43
44
45
# File 'app/services/report/book_of_business/book_of_business.rb', line 40

def self.build_string_in_clause(column, values)
  return '' if values.blank?

  quoted = Array(values).map { |v| ActiveRecord::Base.lease_connection.quote(v) }
  " and #{column} in (#{quoted.join(',')})"
end

.existing_business(start_date, end_date, options) ⇒ Array<Integer>

Returns customer IDs with repeat business in the period.

Parameters:

  • start_date (Date)

    period start

  • end_date (Date)

    period end

  • options (Hash)

    report filter options

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

Returns:

  • (Array<Integer>)

    customer IDs with repeat business in the period



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'app/services/report/book_of_business/book_of_business.rb', line 571

def self.existing_business(start_date, end_date, options)
  star_date_year_ago = start_date.years_ago(1)
  end_date_year_ago = start_date.days_ago(1)
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])
  sql_command = "select distinct a.customer_id
                from (
                    select distinct customer_id
                    from invoices
                    where gl_date between '#{start_date}' and '#{end_date}'
                    and invoice_type = 'SO'
                    and state not in ('draft','requested')
                    #{where_gp}
                    #{where_rep}
                ) a
                inner join (
                    select distinct customer_id
                    from invoices
                    where gl_date between '#{star_date_year_ago}' and '#{end_date_year_ago}'
                    and invoice_type = 'SO'
                    and state not in ('draft','requested')
                    #{where_gp}
                    #{where_rep}
                ) b on a.customer_id = b.customer_id"

  ActiveRecord::Base.lease_connection.execute(sql_command).to_a.map { |r| r.map { |_k, v| v }[0].to_i }
end

.get_cust(start_date, end_date, options, visualization, cust_cache: nil) ⇒ Array<Hash>

Runs the union of customer ID queries per state classification.

Parameters:

  • start_date (Date)

    start of the current period

  • end_date (Date)

    end of the current period

  • options (Hash)

    report filter options

  • visualization (Integer)

    1 for overview, 2 for customer breakdown

  • cust_cache (Hash, nil) (defaults to: nil)

    pre-computed customer classification cache

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (Array<Hash>)

    result rows with symbolized keys



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'app/services/report/book_of_business/book_of_business.rb', line 346

def self.get_cust(start_date, end_date, options, visualization, cust_cache: nil)
  orders_opps_number = get_customers_ids(start_date, end_date, options, 1, visualization, cust_cache: cust_cache)
  activities_open = get_customers_ids(start_date, end_date, options, 3, visualization, cust_cache: cust_cache)
  activities_no_open = get_customers_ids(start_date, end_date, options, 4, visualization, cust_cache: cust_cache)

  sql = <<-SQL.squish
    #{orders_opps_number}
    union all
    #{activities_open}
    union all
    #{activities_no_open}
  SQL

  ActiveRecord::Base.lease_connection.execute(sql).to_a.map(&:symbolize_keys)
end

.get_customers_ids(start_date, end_date, options, detail, visualization, cust_cache: nil) ⇒ String

Returns the SQL query.

Parameters:

  • start_date (Date)

    period start

  • end_date (Date)

    period end

  • detail (Integer)

    detail selector (1 = orders/opps, 3/4 = activities)

  • visualization (Integer)

    1 for overview, 2 for customer breakdown

  • cust_cache (Hash, nil) (defaults to: nil)

    pre-computed customer classification cache

  • options (Hash)

    report filter options

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (String)

    the SQL query



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'app/services/report/book_of_business/book_of_business.rb', line 675

def self.get_customers_ids(start_date, end_date, options, detail, visualization, cust_cache: nil)
  prev_start_date = start_date.years_ago(1)
  prev_end_date = end_date.years_ago(1)
  where_activity = ''
  from_table = ''
  case detail
  when 1
    from_table = ' from view_book_business_ord_opps '
  when 3
    from_table = ' from view_book_business_activities '
    where_activity = ' and activity = 1 '
  when 4
    from_table = ' from view_book_business_activities '
    where_activity = ' and activity = 0 '
  end
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])
  if options[:sources].empty?
    where_sources = ''
  else
    source_ids = options[:sources].flat_map { |r| Source.select_suboptions(r) }.uniq
    where_sources = build_int_in_clause('source_id', source_ids)
  end
  if options[:campaign_ids].empty?
    where_campaigns = ''
  else
    campaign_source_ids = Campaign.where(id: options[:campaign_ids]).pluck(:source_id)
    where_campaigns = build_int_in_clause('source_id', campaign_source_ids)
  end
  where_branch = build_int_in_clause('store_id', options[:company_ids])

  if visualization == 1
    "select distinct #{detail}::int as detail,report_grouping,customer_id,
                case when gl_date between '#{start_date}' and '#{end_date}' and state = 'lead' then 'lead_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'lead' then 'lead_prev'
                     when gl_date between '#{start_date}' and '#{end_date}' and state = 'prospect' then 'prct_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'prospect' then 'prct_prev'
                     when gl_date between '#{start_date}' and '#{end_date}' and state = 'customer' then 'ctmr_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'customer' then 'ctmr_prev'
                     when gl_date between '#{start_date}' and '#{end_date}' and state = 'closed' then 'clsd_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'closed' then 'clsd_prev' else null end as customer_state
                #{from_table}
                where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                #{where_activity}
                #{where_gp}
                #{where_rep}
                #{where_sources}
                #{where_campaigns}
                #{where_branch}"
  elsif visualization == 2
    new_cust = cached_customers(cust_cache, :new_customers, start_date, end_date, options)
    eb_cust = cached_customers(cust_cache, :existing_business, start_date, end_date, options)
    rb_cust = cached_customers(cust_cache, :reactivating_business, start_date, end_date, options)
    prev_new_cust = cached_customers(cust_cache, :new_customers, prev_start_date, prev_end_date, options)
    prev_eb_cust = cached_customers(cust_cache, :existing_business, prev_start_date, prev_end_date, options)
    prev_rb_cust = cached_customers(cust_cache, :reactivating_business, prev_start_date, prev_end_date, options)

    eb_cur = " when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{eb_cust.map { |r| r }.join(',')}) then 'eb_cur' " if detail == 1
    eb_cur = " when gl_date between '#{start_date}' and '#{end_date}' and customer_id not in (#{(new_cust + rb_cust).uniq.map { |r| r }.join(',')}) then 'eb_cur' " if [3, 4].include?(detail)
    eb_prev = " when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_eb_cust.map { |r| r }.join(',')}) then 'eb_prev' " if detail == 1
    eb_prev = " when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id not in (#{(prev_new_cust + prev_rb_cust).uniq.map { |r| r }.join(',')}) then 'eb_prev' " if [3, 4].include?(detail)

    "select distinct #{detail}::int as detail,report_grouping,customer_id,
                case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{new_cust.map { |r| r }.join(',')}) then 'nc_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_new_cust.map { |r| r }.join(',')}) then 'nc_prev'
                     #{eb_cur}
                     #{eb_prev}
                     when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{rb_cust.map { |r| r }.join(',')}) then 'rb_cur'
                     when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_rb_cust.map { |r| r }.join(',')}) then 'rb_prev' else null end as customer_state
                #{from_table}
                where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                and state = 'customer'
                #{where_activity}
                #{where_gp}
                #{where_rep}
                #{where_sources}
                #{where_campaigns}
                #{where_branch}"
  end
end

.get_data(start_date, end_date, is_total, options, visualization, cust_cache: nil) ⇒ Array<Hash>

Runs the union of order/opportunity and activity metric queries.

Parameters:

  • start_date (Date)

    start of the current period

  • end_date (Date)

    end of the current period

  • is_total (Boolean)

    true for the total row, false for per-grouping detail rows

  • options (Hash)

    report filter options

  • visualization (Integer)

    1 for overview, 2 for customer breakdown

  • cust_cache (Hash, nil) (defaults to: nil)

    pre-computed customer classification cache

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (Array<Hash>)

    result rows with symbolized keys



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'app/services/report/book_of_business/book_of_business.rb', line 313

def self.get_data(start_date, end_date, is_total, options, visualization, cust_cache: nil)
  orders_opps_number = string_query_opps_orders(start_date, end_date, 1, is_total, options, visualization, cust_cache: cust_cache)
  orders_opps_revenue = string_query_opps_orders(start_date, end_date, 2, is_total, options, visualization, cust_cache: cust_cache)
  activities_open = string_query_activities(start_date, end_date, 3, is_total, options, visualization, cust_cache: cust_cache)
  activities_no_open = string_query_activities(start_date, end_date, 4, is_total, options, visualization, cust_cache: cust_cache)
  order_by = is_total == true ? '' : 'order by 1,2'

  sql = <<-SQL.squish
    #{orders_opps_number}
    union all
    #{orders_opps_revenue}
    union all
    #{activities_open}
    union all
    #{activities_no_open}
    #{order_by}
  SQL

  ActiveRecord::Base.lease_connection.execute(sql).to_a.map(&:symbolize_keys)
end

.new_customers(start_date, end_date, options) ⇒ Array<Integer>

Returns customer IDs with first-ever business in the period.

Parameters:

  • start_date (Date)

    period start

  • end_date (Date)

    period end

  • options (Hash)

    report filter options

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

Returns:

  • (Array<Integer>)

    customer IDs with first-ever business in the period



537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'app/services/report/book_of_business/book_of_business.rb', line 537

def self.new_customers(start_date, end_date, options)
  star_date_day_ago = start_date.days_ago(1)
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])
  sql_command = "select distinct a.customer_id
                from (
                    select distinct customer_id
                    from invoices
                    where gl_date between '#{start_date}' and '#{end_date}'
                    and invoice_type = 'SO'
                    and state not in ('draft','requested')
                    #{where_gp}
                    #{where_rep}
                ) a
                left join (
                    select distinct customer_id
                    from invoices
                    where gl_date <= '#{star_date_day_ago}'
                    and invoice_type = 'SO'
                    and state not in ('draft','requested')
                    #{where_gp}
                    #{where_rep}
                ) b on a.customer_id = b.customer_id
                where b.customer_id is null"

  ActiveRecord::Base.lease_connection.execute(sql_command).to_a.map { |r| r.map { |_k, v| v }[0].to_i }
end

.reactivating_business(start_date, end_date, options) ⇒ Array<Integer>

Returns customer IDs reactivating in the period.

Parameters:

  • start_date (Date)

    period start

  • end_date (Date)

    period end

  • options (Hash)

    report filter options

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

Returns:

  • (Array<Integer>)

    customer IDs reactivating in the period



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'app/services/report/book_of_business/book_of_business.rb', line 605

def self.reactivating_business(start_date, end_date, options)
  star_date_year_ago = start_date.years_ago(1)
  end_date_year_ago = start_date.days_ago(1)
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])
  sql_command = "select distinct customer_id
    from invoices
    where gl_date between '#{start_date}' and '#{end_date}'
    and invoice_type = 'SO'
    and state not in ('draft','requested')
    #{where_gp}
    #{where_rep}
    and customer_id not in (
        select distinct a.customer_id
        from (
            select distinct customer_id
            from invoices
            where gl_date between '#{start_date}' and '#{end_date}'
            and invoice_type = 'SO'
            and state not in ('draft','requested')
            #{where_gp}
            #{where_rep}
        ) a
        left join (
            select distinct customer_id
            from invoices
            where gl_date <= '#{end_date_year_ago}'
            and invoice_type = 'SO'
            and state not in ('draft','requested')
            #{where_gp}
            #{where_rep}
        ) b on a.customer_id = b.customer_id
        where b.customer_id is null
        union all
        select distinct a.customer_id
        from (
            select distinct customer_id
            from invoices
            where gl_date between '#{start_date}' and '#{end_date}'
            and invoice_type = 'SO'
            and state not in ('draft','requested')
            #{where_gp}
            #{where_rep}
        ) a
        inner join (
            select distinct customer_id
            from invoices
            where gl_date between '#{star_date_year_ago}' and '#{end_date_year_ago}'
            and invoice_type = 'SO'
            and state not in ('draft','requested')
            #{where_gp}
            #{where_rep}
        ) b on a.customer_id = b.customer_id
    )"

  ActiveRecord::Base.lease_connection.execute(sql_command).to_a.map { |r| r.map { |_k, v| v }[0].to_i }
end

.result_report(options = {}) ⇒ Result

Builds the full book of business report (overview + customer breakdown).

Parameters:

  • options (Hash) (defaults to: {})

    report filter options

Options Hash (options):

  • period1_gteq (Date)

    start of the current period

  • period1_lteq (Date)

    end of the current period

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (Result)

    the assembled report data



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'app/services/report/book_of_business/book_of_business.rb', line 57

def self.result_report(options = {})
  start_date = options[:period1_gteq]
  end_date = options[:period1_lteq]
  prev_start_date = start_date.years_ago(1)
  prev_end_date = end_date.years_ago(1)

  # visualization = 1 ---> overview
  cust_overview = get_cust(start_date, end_date, options, 1)
  cust_detail = cust_overview.map { |r| r[:detail].to_i }.uniq.sort.to_a
  cust_states = cust_overview.pluck(:customer_state).compact.uniq.sort.to_a
  total_overview = get_data(start_date, end_date, true, options, 1).map { |r| r.keys.zip(r.values.map(&:to_f)).to_h }
  detail_overview = get_data(start_date, end_date, false, options, 1)
  rg = detail_overview.pluck(:report_grouping).compact.uniq.sort.to_a
  rowspan_by_rg = detail_overview.filter_map { |r| r[:report_grouping] }.sort.to_a.each_with_object(Hash.new(0)) do |v, k|
    k[v] += 1
  end

  total_cust_overview = []
  cust_detail.each do |i|
    cust_ids = {}
    cust_ids.merge!(detail: i)
    cust_states.each do |j|
      ids = []
      cust_overview.each do |k|
        ids << k[:customer_id] if k[:detail].to_i == i && k[:customer_state] == j
      end
      cust_ids.merge!("#{j}_ids": ids)
    end
    total_cust_overview << cust_ids
  end

  cust_detail.each do |d|
    total_cust_overview.each do |c|
      next unless c[:detail] == d

      total_overview.each do |r|
        next unless r[:detail].to_i == d

        r.merge!(lead_cur_ids: c[:lead_cur_ids],
                 lead_prev_ids: c[:lead_prev_ids],
                 prct_cur_ids: c[:prct_cur_ids],
                 prct_prev_ids: c[:prct_prev_ids],
                 ctmr_cur_ids: c[:ctmr_cur_ids],
                 ctmr_prev_ids: c[:ctmr_prev_ids],
                 clsd_cur_ids: c[:clsd_cur_ids],
                 clsd_prev_ids: c[:clsd_prev_ids])
      end
    end
  end

  detail_cust_overview = []
  cust_detail.each do |i|
    rg.each do |j|
      cust_ids = {}
      cust_ids.merge!(report_grouping: j, detail: i.to_s)
      cust_states.each do |k|
        ids = []
        cust_overview.each do |l|
          ids << l[:customer_id] if l[:detail].to_i == i && l[:report_grouping] == j && l[:customer_state] == k
        end
        cust_ids.merge!("#{k}_ids": ids)
      end
      detail_cust_overview << cust_ids
    end
  end

  cust_detail.each do |d|
    rg.each do |g|
      detail_cust_overview.each do |c|
        next unless c[:detail].to_i == d && c[:report_grouping] == g

        detail_overview.each do |r|
          next unless r[:detail].to_i == d && r[:report_grouping] == g

          r.merge!(lead_cur_ids: c[:lead_cur_ids],
                   lead_prev_ids: c[:lead_prev_ids],
                   prct_cur_ids: c[:prct_cur_ids],
                   prct_prev_ids: c[:prct_prev_ids],
                   ctmr_cur_ids: c[:ctmr_cur_ids],
                   ctmr_prev_ids: c[:ctmr_prev_ids],
                   clsd_cur_ids: c[:clsd_cur_ids],
                   clsd_prev_ids: c[:clsd_prev_ids])
        end
      end
    end
  end

  rowsnum = Hash.new(0)
  channel_array = []
  rg.each do |j|
    detail_overview.each do |i|
      channel_array << i if i[:report_grouping] == j
    end
    rowsnum.store(j, channel_array.min_by { |h| h[:detail] }[:detail].to_i)
    channel_array.clear
  end

  # Pre-compute customer classifications ONCE for visualization=2.
  # Previously these 6 queries were duplicated ~58 times per report run,
  # accounting for the majority of the report's load time.
  cust_cache = build_customer_cache(start_date, end_date, prev_start_date, prev_end_date, options)

  # visualization = 2 ---> customer breakdown
  cust_cbd = get_cust(start_date, end_date, options, 2, cust_cache: cust_cache)
  cust_states_cbd = cust_cbd.pluck(:customer_state).compact.uniq.sort.to_a
  total_cbd = get_data(start_date, end_date, true, options, 2, cust_cache: cust_cache).map { |r| r.keys.zip(r.values.map(&:to_f)).to_h }
  detail_cbd = get_data(start_date, end_date, false, options, 2, cust_cache: cust_cache)
  rg_cbd = detail_cbd.pluck(:report_grouping).compact.uniq.sort.to_a
  rowspan_by_rg_cbd = detail_cbd.filter_map { |r| r[:report_grouping] }.sort.to_a.each_with_object(Hash.new(0)) do |v, k|
    k[v] += 1
  end

  total_cust_cbd = []
  cust_detail.each do |i|
    cust_ids_cbd = {}
    cust_ids_cbd.merge!(detail: i)
    cust_states_cbd.each do |j|
      ids_cbd = []
      cust_cbd.each do |k|
        ids_cbd << k[:customer_id] if k[:detail].to_i == i && k[:customer_state] == j
      end
      cust_ids_cbd.merge!("#{j}_ids": ids_cbd)
    end
    total_cust_cbd << cust_ids_cbd
  end

  cust_detail.each do |d|
    total_cust_cbd.each do |c|
      next unless c[:detail] == d

      total_cbd.each do |r|
        next unless r[:detail].to_i == d

        r.merge!(nc_cur_ids: c[:nc_cur_ids],
                 nc_prev_ids: c[:nc_prev_ids],
                 eb_cur_ids: c[:eb_cur_ids],
                 eb_prev_ids: c[:eb_prev_ids],
                 rb_cur_ids: c[:rb_cur_ids],
                 rb_prev_ids: c[:rb_prev_ids])
      end
    end
  end

  detail_cust_cbd = []
  cust_detail.each do |i|
    rg_cbd.each do |j|
      cust_ids_cbd = {}
      cust_ids_cbd.merge!(report_grouping: j, detail: i.to_s)
      cust_states_cbd.each do |k|
        ids_cbd = []
        cust_cbd.each do |l|
          ids_cbd << l[:customer_id] if l[:detail].to_i == i && l[:report_grouping] == j && l[:customer_state] == k
        end
        cust_ids_cbd.merge!("#{k}_ids": ids_cbd)
      end
      detail_cust_cbd << cust_ids_cbd
    end
  end

  cust_detail.each do |d|
    rg_cbd.each do |g|
      detail_cust_cbd.each do |c|
        next unless c[:detail].to_i == d && c[:report_grouping] == g

        detail_cbd.each do |r|
          next unless r[:detail].to_i == d && r[:report_grouping] == g

          r.merge!(nc_cur_ids: c[:nc_cur_ids],
                   nc_prev_ids: c[:nc_prev_ids],
                   eb_cur_ids: c[:eb_cur_ids],
                   eb_prev_ids: c[:eb_prev_ids],
                   rb_cur_ids: c[:rb_cur_ids],
                   rb_prev_ids: c[:rb_prev_ids])
        end
      end
    end
  end

  rowsnum_cbd = Hash.new(0)
  channel_array_cbd = []
  rg_cbd.each do |j|
    detail_cbd.each do |i|
      channel_array_cbd << i if i[:report_grouping] == j
    end
    rowsnum_cbd.store(j, channel_array_cbd.min_by { |h| h[:detail] }[:detail].to_i)
    channel_array_cbd.clear
  end

  Result.new(success: true, total_overview: total_overview, detail_overview: detail_overview, rowspan_by_rg: rowspan_by_rg, rowsnum: rowsnum, total_cbd: total_cbd, detail_cbd: detail_cbd, rowspan_by_rg_cbd: rowspan_by_rg_cbd,
rowsnum_cbd: rowsnum_cbd)
end

.string_query_activities(start_date, end_date, detail, is_total, options, visualization, cust_cache: nil) ⇒ String

Returns the SQL query.

Parameters:

  • start_date (Date)

    period start

  • end_date (Date)

    period end

  • detail (Integer)

    activity detail selector

  • is_total (Boolean)

    whether this is the totals row

  • visualization (Integer)

    1 for overview, 2 for customer breakdown

  • cust_cache (Hash, nil) (defaults to: nil)

    pre-computed customer classification cache

  • options (Hash)

    report filter options

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (String)

    the SQL query



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'app/services/report/book_of_business/book_of_business.rb', line 460

def self.string_query_activities(start_date, end_date, detail, is_total, options, visualization, cust_cache: nil)
  prev_start_date = start_date.years_ago(1)
  prev_end_date = end_date.years_ago(1)
  where_activity = ' and activity = 1 ' if detail == 3
  where_activity = ' and activity = 0 ' if detail == 4
  select = "select #{detail}::int as detail" if is_total == true
  select = "select report_grouping,#{detail}::int as detail" if is_total == false
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])

  if options[:sources].empty?
    where_sources = ''
  else
    source_ids = options[:sources].flat_map { |r| Source.select_suboptions(r) }.uniq
    where_sources = build_int_in_clause('source_id', source_ids)
  end
  if options[:campaign_ids].empty?
    where_campaigns = ''
  else
    campaign_source_ids = Campaign.where(id: options[:campaign_ids]).pluck(:source_id)
    where_campaigns = build_int_in_clause('source_id', campaign_source_ids)
  end
  where_branch = build_int_in_clause('store_id', options[:company_ids])
  group_by = '' if is_total == true
  group_by = 'group by report_grouping' if is_total == false

  if visualization == 1
    "#{select},
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and state = 'lead' then customer_id else null end)) as lead_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'lead' then customer_id else null end)) as lead_prev,
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and state = 'prospect' then customer_id else null end)) as prct_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'prospect' then customer_id else null end)) as prct_prev,
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and state = 'customer' then customer_id else null end)) as ctmr_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'customer' then customer_id else null end)) as ctmr_prev,
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and state = 'closed' then customer_id else null end)) as clsd_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'closed' then customer_id else null end)) as clsd_prev
                 from view_book_business_activities
                 where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                 #{where_activity}
                 #{where_gp}
                 #{where_rep}
                 #{where_sources}
                 #{where_campaigns}
                 #{where_branch}
                 #{group_by}"
  elsif visualization == 2
    new_cust = cached_customers(cust_cache, :new_customers, start_date, end_date, options)
    rb_cust = cached_customers(cust_cache, :reactivating_business, start_date, end_date, options)
    prev_new_cust = cached_customers(cust_cache, :new_customers, prev_start_date, prev_end_date, options)
    prev_rb_cust = cached_customers(cust_cache, :reactivating_business, prev_start_date, prev_end_date, options)

    "#{select},
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{new_cust.map { |r| r }.join(',')}) then customer_id else null end)) as nc_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_new_cust.map { |r| r }.join(',')}) then customer_id else null end)) as nc_prev,
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and customer_id not in (#{(new_cust + rb_cust).uniq.map { |r| r }.join(',')}) then customer_id else null end)) as eb_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id not in (#{(prev_new_cust + prev_rb_cust).uniq.map { |r| r }.join(',')}) then customer_id else null end)) as eb_prev,
                 count(distinct (case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{rb_cust.map { |r| r }.join(',')}) then customer_id else null end)) as rb_cur,
                 count(distinct (case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_rb_cust.map { |r| r }.join(',')}) then customer_id else null end)) as rb_prev
                 from view_book_business_activities
                 where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                 and state = 'customer'
                 #{where_activity}
                 #{where_gp}
                 #{where_rep}
                 #{where_sources}
                 #{where_campaigns}
                 #{where_branch}
                 #{group_by}"
  end
end

.string_query_opps_orders(start_date, end_date, detail, is_total, options, visualization, cust_cache: nil) ⇒ String?

Builds the order/opportunity metric SQL fragment.

Parameters:

  • start_date (Date)

    start of the current period

  • end_date (Date)

    end of the current period

  • detail (Integer)

    1 for counts, 2 for revenue amounts

  • is_total (Boolean)

    true for the total row, false for per-grouping detail rows

  • options (Hash)

    report filter options

  • visualization (Integer)

    1 for overview, 2 for customer breakdown

  • cust_cache (Hash, nil) (defaults to: nil)

    pre-computed customer classification cache

Options Hash (options):

  • report_groupings (Array<String>)

    report groupings to filter by

  • primary_sales_rep_ids (Array<Integer>)

    sales rep IDs to filter by

  • sources (Array<Integer>)

    source IDs to filter by (expanded via Source.select_suboptions)

  • campaign_ids (Array<Integer>)

    campaign IDs to filter by (mapped to their source IDs)

  • company_ids (Array<Integer>)

    store IDs to filter by

Returns:

  • (String, nil)

    the SQL fragment



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'app/services/report/book_of_business/book_of_business.rb', line 376

def self.string_query_opps_orders(start_date, end_date, detail, is_total, options, visualization, cust_cache: nil)
  prev_start_date = start_date.years_ago(1)
  prev_end_date = end_date.years_ago(1)
  column = '1' if detail == 1
  column = 'amount' if detail == 2
  select = "select #{detail}::int as detail" if is_total == true
  select = "select report_grouping,#{detail}::int as detail" if is_total == false
  where_gp = build_string_in_clause('report_grouping', options[:report_groupings])
  where_rep = build_int_in_clause('primary_sales_rep_id', options[:primary_sales_rep_ids])

  if options[:sources].empty?
    where_sources = ''
  else
    source_ids = options[:sources].flat_map { |r| Source.select_suboptions(r) }.uniq
    where_sources = build_int_in_clause('source_id', source_ids)
  end
  if options[:campaign_ids].empty?
    where_campaigns = ''
  else
    campaign_source_ids = Campaign.where(id: options[:campaign_ids]).pluck(:source_id)
    where_campaigns = build_int_in_clause('source_id', campaign_source_ids)
  end
  where_branch = build_int_in_clause('store_id', options[:company_ids])
  group_by = '' if is_total == true
  group_by = 'group by report_grouping' if is_total == false

  if visualization == 1
    "#{select},
                 sum(case when gl_date between '#{start_date}' and '#{end_date}' and state = 'lead' then #{column} else 0 end) as lead_cur,
                 sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'lead' then #{column} else 0 end) as lead_prev,
                 sum(case when gl_date between '#{start_date}' and '#{end_date}' and state = 'prospect' then #{column} else 0 end) as prct_cur,
                 sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'prospect' then #{column} else 0 end) as prct_prev,
                 sum(case when gl_date between '#{start_date}' and '#{end_date}' and state = 'customer' then #{column} else 0 end) as ctmr_cur,
                 sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'customer' then #{column} else 0 end) as ctmr_prev,
                 sum(case when gl_date between '#{start_date}' and '#{end_date}' and state = 'closed' then #{column} else 0 end) as clsd_cur,
                 sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and state = 'closed' then #{column} else 0 end) as clsd_prev
                 from view_book_business_ord_opps
                 where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                 #{where_gp}
                 #{where_rep}
                 #{where_sources}
                 #{where_campaigns}
                 #{where_branch}
                 #{group_by}"
  elsif visualization == 2
    new_cust = cached_customers(cust_cache, :new_customers, start_date, end_date, options)
    eb_cust = cached_customers(cust_cache, :existing_business, start_date, end_date, options)
    rb_cust = cached_customers(cust_cache, :reactivating_business, start_date, end_date, options)
    prev_new_cust = cached_customers(cust_cache, :new_customers, prev_start_date, prev_end_date, options)
    prev_eb_cust = cached_customers(cust_cache, :existing_business, prev_start_date, prev_end_date, options)
    prev_rb_cust = cached_customers(cust_cache, :reactivating_business, prev_start_date, prev_end_date, options)

    "#{select},
                   sum(case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{new_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as nc_cur,
                   sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_new_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as nc_prev,
                   sum(case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{eb_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as eb_cur,
                   sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_eb_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as eb_prev,
                   sum(case when gl_date between '#{start_date}' and '#{end_date}' and customer_id in (#{rb_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as rb_cur,
                   sum(case when gl_date between '#{prev_start_date}' and '#{prev_end_date}' and customer_id in (#{prev_rb_cust.map { |r| r }.join(',')}) then #{column} else 0 end) as rb_prev
                   from view_book_business_ord_opps
                   where (gl_date between '#{start_date}' and '#{end_date}' or gl_date between '#{prev_start_date}' and '#{prev_end_date}')
                   and state = 'customer'
                   #{where_gp}
                   #{where_rep}
                   #{where_sources}
                   #{where_campaigns}
                   #{where_branch}
                   #{group_by}"
  end
end