<% html_title l(:label_business_report) %> <% money = @report.money %> <% hours = @report.hours %> <% ratios = @report.ratios %> <% max_money = [money[:estimates][:total], money[:invoices][:total], money[:paid][:total], money[:payments][:total]].max.to_f %> <% max_hours = hours.values.max.to_f %> <% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %> <% fmt_hours = ->(h) { format('%.1f', h.to_f) } %> <% pct = ->(v) { v.nil? ? '–' : "#{v}%" } %> <%# Line charts: a label and a tooltip title per point, from the chart's granularity %> <% chart = @report.chart %> <% months_abbr = ::I18n.t('date.abbr_month_names') %> <% days_abbr = ::I18n.t('date.abbr_day_names') %> <% one_year = @report.from.year == @report.to.year %> <% point_label = lambda do |date| case chart[:granularity] when :day then "#{days_abbr[date.wday]} #{date.day}" when :week then "#{months_abbr[date.month]} #{date.day}" else one_year ? months_abbr[date.month] : "#{months_abbr[date.month]} #{date.year}" end end %> <% point_title = lambda do |first, last| case chart[:granularity] when :day then format_date(first) when :week then "#{format_date(first)} – #{format_date(last)}" else "#{::I18n.t('date.month_names')[first.month]} #{first.year}" end end %> <% previous_ends = chart[:previous_points].each_with_index.map { |p, i| Date.parse(p) + (Date.parse(chart[:ends][i]) - Date.parse(chart[:points][i])) } %> <% chart_points = { labels: chart[:points].map { |p| point_label.call(Date.parse(p)) }, titles: chart[:points].each_with_index.map { |p, i| point_title.call(Date.parse(p), Date.parse(chart[:ends][i])) }, previous_titles: chart[:previous_points].each_with_index.map { |p, i| point_title.call(Date.parse(p), previous_ends[i]) }, last_year: l(:label_report_last_year) } %> <% chart_series = lambda do |keys| keys.map do |key, label, color| { label: label, color: color, current: chart[:current][key], previous: chart[:previous][key] } end end %> <% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'], [:invoices, l(:label_report_invoices_written), '#e8a33d'], [:paid, l(:label_report_invoices_paid), '#c0504d'], [:payments, l(:label_report_payments_received), '#5aa05a']]) %> <% taxes = @report.taxes %> <% max_tax = taxes.values.map { |t| t[:total] }.max.to_f %> <% tax_series = chart_series.call([[:tax_invoiced, l(:label_report_tax_invoiced), '#e8a33d'], [:tax_collected, l(:label_report_tax_collected), '#c0504d']]) %> <% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'], [:issue_hours, l(:label_report_issue_hours), '#9b7fc0'], [:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'], [:spent_hours, l(:label_report_spent_hours), '#5aa05a']]) %>

<%= l(:label_business_report) %>

<%= form_tag qbo_reports_path, method: :get, id: 'qbo-report-form' do %>
<%= l(:label_report_period) %> <%= select_tag 'period', options_for_select(RedmineQboBilling::BusinessReport::PERIODS.map { |p| [l("label_report_period_#{p}"), p] }, @report.period), id: 'qbo-report-period' %> <%= date_field_tag 'from', @report.from.iso8601, id: 'qbo-report-from' %> – <%= date_field_tag 'to', @report.to.iso8601, id: 'qbo-report-to' %> <%= submit_tag l(:button_apply), name: nil %> <%# Projects for the issues and spent time; the blank value sends project_ids when none are picked (every project) %>
<%= hidden_field_tag 'project_ids[]', '', id: nil %> <%= select_tag 'project_ids[]', project_tree_options_for_select(@projects, selected: @projects.select { |p| @project_ids.include?(p.id) }), multiple: true, size: [[@projects.size, 3].max, 8].min, id: 'qbo-report-project-ids' %> <%= l(:text_report_projects) %> <% if @saved_project_ids.any? %> <%= l(:text_report_saved_projects, projects: @projects.select { |p| @saved_project_ids.include?(p.id) }.map(&:name).join(', ')) %> <% end %>
<% end %>

<%= format_date(@report.from) %> – <%= format_date(@report.to) %> <% if @report.projects_filtered? %> · <%= l(:label_project_plural) %>: <%= @projects.select { |p| @project_ids.include?(p.id) }.map(&:name).join(', ') %> <% end %>

<% if @report.projects_filtered? %>

<%= l(:text_report_projects_filtered) %>

<% end %> <% if Array(@syncing).any? %> <% sync_labels = { 'Estimate' => l(:label_estimates), 'Invoice' => l(:label_invoices), 'Payment' => l(:label_payments) } %>
<%= l(:text_report_syncing) %>
<%= javascript_tag do %> // Refresh while QuickBooks is syncing, so the figures fill in setTimeout(function () { window.location.reload(); }, 30000); <% end %> <% end %> <% if @report.unsynced_count > 0 %>

<%= l(:text_report_needs_sync, count: @report.unsynced_count) %>

<% end %>

<%= l(:label_report_money) %>

<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)], [:paid, l(:label_report_invoices_paid)], [:payments, l(:label_report_payments_received)]].each do |key, label| %> <% end %>
<%= label %> (<%= money[key][:count] %>)
<%= number_to_currency(money[key][:total]) %>

<%= l(:label_report_invoiced_of_estimated) %>: <%= pct.call(ratios[:invoiced_of_estimated]) %>
<%= l(:label_report_collected_of_invoiced) %>: <%= pct.call(ratios[:collected_of_invoiced]) %>
<%= l(:label_report_open_balance) %>: <%= number_to_currency(money[:invoices][:balance]) %>

<%= l(:text_report_without_tax) %>

<%= l(:label_report_hours) %>

<% [[:estimate_hours, l(:label_report_estimate_hours)], [:issue_hours, l(:label_report_issue_hours)], [:invoice_hours, l(:label_report_invoice_hours)], [:spent_hours, l(:label_report_spent_hours)]].each do |key, label| %> <% end %>
<%= label %>
<%= fmt_hours.call(hours[key]) %>
<% cpi_badge = lambda do |cpi| level = RedmineQboBilling::BusinessReport.cpi_level(cpi) content_tag(:span, cpi.nil? ? '–' : format('%.2f', cpi), class: "qbo-cpi qbo-cpi-#{level || 'none'}") end %>

<%= l(:label_report_cpi) %> <%= cpi_badge.call(@report.cpi) %> <%= l(:text_report_cpi) %>

<%= l(:label_report_spent_of_estimated) %>: <%= pct.call(ratios[:spent_of_estimated]) %>

<%= l(:label_report_by_month) %>

<% @report.months.each do |row| %> <% end %>
<%= l(:label_month) %> <%= l(:label_report_estimates_written) %> <%= l(:label_report_invoices_written) %> <%= l(:label_report_invoices_paid) %> <%= l(:label_report_payments_received) %> <%= l(:label_report_estimate_hours) %> <%= l(:label_report_issue_hours) %> <%= l(:label_report_invoice_hours) %> <%= l(:label_report_spent_hours) %> <%= l(:label_report_cpi_short) %>
<%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %> <%= number_to_currency(row[:estimates]) %> <%= number_to_currency(row[:invoices]) %> <%= number_to_currency(row[:paid]) %> <%= number_to_currency(row[:payments]) %> <%= fmt_hours.call(row[:estimate_hours]) %> <%= fmt_hours.call(row[:issue_hours]) %> <%= fmt_hours.call(row[:invoice_hours]) %> <%= fmt_hours.call(row[:spent_hours]) %> <%= cpi_badge.call(RedmineQboBilling::BusinessReport.cpi(row[:invoice_hours], row[:spent_hours])) %>
<%= l(:label_total) %> <%= number_to_currency(money[:estimates][:total]) %> <%= number_to_currency(money[:invoices][:total]) %> <%= number_to_currency(money[:paid][:total]) %> <%= number_to_currency(money[:payments][:total]) %> <%= fmt_hours.call(hours[:estimate_hours]) %> <%= fmt_hours.call(hours[:issue_hours]) %> <%= fmt_hours.call(hours[:invoice_hours]) %> <%= fmt_hours.call(hours[:spent_hours]) %> <%= cpi_badge.call(@report.cpi) %>

<%= l(:label_report_taxes) %>

<% [[:tax_invoiced, l(:label_report_tax_invoiced)], [:tax_collected, l(:label_report_tax_collected)]].each do |key, label| %> <% end %>
<%= label %> (<%= l(:label_report_taxed_invoices, count: taxes[key][:count]) %>)
<%= number_to_currency(taxes[key][:total]) %>

<%= l(:text_report_taxes) %>

<% @report.months.each do |row| %> <% end %>
<%= l(:label_month) %> <%= l(:label_report_tax_invoiced) %> <%= l(:label_report_tax_collected) %>
<%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %> <%= number_to_currency(row[:tax_invoiced]) %> <%= number_to_currency(row[:tax_collected]) %>
<%= l(:label_total) %> <%= number_to_currency(taxes[:tax_invoiced][:total]) %> <%= number_to_currency(taxes[:tax_collected][:total]) %>

<%= l(:text_report_notes) %>

<%= javascript_tag do %> $(function() { var $period = $('#qbo-report-period'), $dates = $('#qbo-report-from, #qbo-report-to'); // Picking a preset fills its dates on Apply; changing a date switches to Custom $dates.on('change', function() { $period.val('custom'); }); $period.on('change', function() { if ($period.val() !== 'custom') { $('#qbo-report-form').submit(); } }); }); // Line charts (Chart.js 4): the same figures and colors as the bars, a point per day, // week or month. "Compare with last year" adds last year's lines, dashed and faded, without reloading. (function() { var points = <%= raw chart_points.to_json %>; // The currency layout the tables use, e.g. "$%n" var currencyFormat = <%= raw number_to_currency(0, precision: 0).to_s.sub('0', '%n').to_json %>; var charts = []; function money(v, decimals) { var n = Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }); return currencyFormat.replace('%n', n); } function hours(v) { return Number(v || 0).toFixed(1); } function faded(hex) { var n = parseInt(hex.slice(1), 16); return 'rgba(' + (n >> 16 & 255) + ',' + (n >> 8 & 255) + ',' + (n & 255) + ',0.45)'; } // Grid lines and text from the page's colours, so a dark mode (e.g. redmine_dark_mode) can set // --qbo-chart-grid and --qbo-chart-text; Chart.js' own colours otherwise function chartColors() { var style = getComputedStyle(document.documentElement); return { grid: style.getPropertyValue('--qbo-chart-grid').trim() || 'rgba(0,0,0,0.1)', text: style.getPropertyValue('--qbo-chart-text').trim() || '#666' }; } function applyColors(chart) { var c = chartColors(); ['x', 'y'].forEach(function(axis) { var scale = chart.options.scales[axis]; scale.grid.color = c.grid; scale.border.color = c.grid; scale.ticks.color = c.text; }); chart.options.plugins.legend.labels.color = c.text; } function draw(Chart, canvas, compare) { var series = JSON.parse(canvas.getAttribute('data-series')); var isMoney = canvas.getAttribute('data-kind') === 'money'; var colors = chartColors(); var datasets = []; series.forEach(function(s) { datasets.push({ label: s.label, data: s.current, borderColor: s.color, backgroundColor: s.color, fill: false, cubicInterpolationMode: 'monotone', pointRadius: 3, pointHoverRadius: 5, spanGaps: false, order: 1 }); }); series.forEach(function(s) { datasets.push({ label: s.label + ' (' + points.last_year + ')', data: s.previous, previous: true, borderColor: faded(s.color), backgroundColor: faded(s.color), borderDash: [6, 4], borderWidth: 2, fill: false, cubicInterpolationMode: 'monotone', pointRadius: 2, pointHoverRadius: 4, hidden: !compare, order: 2 }); }); return new Chart(canvas, { type: 'line', data: { labels: points.labels, datasets: datasets }, options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { // One entry per figure (clicking it hides this year's and last year's line), plus a single // dashed "last year" entry while comparing (clicking it turns comparing off) legend: { position: 'bottom', labels: { boxWidth: 12, color: colors.text, generateLabels: function(chart) { var items = Chart.defaults.plugins.legend.labels.generateLabels(chart).filter(function(item) { return !chart.data.datasets[item.datasetIndex].previous; }); if (chart.data.datasets.some(function(ds) { return ds.previous && !ds.hidden; })) { items.push({ text: points.last_year, fillStyle: 'rgba(0,0,0,0)', strokeStyle: '#999', lineWidth: 2, lineDash: [4, 3], hidden: false, datasetIndex: -1 }); } return items; } }, onClick: function(e, item, legend) { var chart = legend.chart; if (item.datasetIndex === -1) { $('#qbo-report-compare').prop('checked', false).trigger('change'); return; } var visible = !chart.isDatasetVisible(item.datasetIndex); chart.setDatasetVisibility(item.datasetIndex, visible); // last year's line follows (shown only while comparing) chart.getDatasetMeta(item.datasetIndex + series.length).hidden = visible ? null : true; chart.update(); } }, tooltip: { callbacks: { title: function(items) { if (!items.length) { return ''; } var i = items[0].dataIndex, lines = [points.titles[i]]; if (items.some(function(it) { return it.dataset.previous; })) { lines.push(points.last_year + ': ' + points.previous_titles[i]); } return lines; }, label: function(item) { return item.dataset.label + ': ' + (isMoney ? money(item.raw, 2) : hours(item.raw)); } } } }, scales: { x: { grid: { color: colors.grid }, border: { color: colors.grid }, ticks: { color: colors.text } }, y: { beginAtZero: true, grid: { color: colors.grid }, border: { color: colors.grid }, ticks: { color: colors.text, precision: isMoney ? 0 : 1, callback: function(v) { return isMoney ? money(v, 0) : v; } } } } } }); } // Chart.js from the module: its default export or a named one. Chart.js 2 has no register() and is skipped. function chartClass(mod) { var found = [mod && mod.default, mod && mod.Chart, mod && mod.default && mod.default.Chart]; for (var i = 0; i < found.length; i++) { if (typeof found[i] === 'function' && typeof found[i].register === 'function') { return found[i]; } } return null; } function setCompare(on) { charts.forEach(function(chart) { var n = chart.data.datasets.length / 2; for (var j = 0; j < n; j++) { chart.data.datasets[j + n].hidden = !on; // a figure hidden from the legend keeps last year's line hidden too chart.getDatasetMeta(j + n).hidden = chart.isDatasetVisible(j) ? null : true; } chart.update(); }); // Keep the choice in the address, so reloading or changing the period keeps it if (window.history && history.replaceState) { var url = new URL(window.location.href); if (on) { url.searchParams.set('compare', '1'); } else { url.searchParams.delete('compare'); } history.replaceState(null, '', url); } } $(function() { var $compare = $('#qbo-report-compare'); // Chart.js 4 ships with this plugin (assets/javascripts), so the charts don't depend on how Redmine or // other plugins provide it (redmine_indicator puts Chart.js 2 on every page) import(<%= raw asset_path('plugin_assets/redmine_qbo/chart-4.5.1.min.js').to_json %>).then(function(mod) { var Chart = chartClass(mod); if (!Chart) { console.warn('Business report: Chart.js did not load', Object.keys(mod || {})); $('.qbo-report-chart').hide(); return; } $('.qbo-report-chart canvas').each(function() { charts.push(draw(Chart, this, $compare.is(':checked'))); }); window.qboReportCharts = charts; }).catch(function(error) { console.warn('Business report: Chart.js did not load', error); $('.qbo-report-chart').hide(); }); $compare.on('change', function() { setCompare(this.checked); }); // Switching between light and dark (redmine_dark_mode) recolours the charts document.addEventListener('redmine:color-scheme', function() { charts.forEach(function(chart) { applyColors(chart); chart.update('none'); }); }); }); })(); <% end %>