# /packages/intranet-leaflet/www/crm-ip-interactions-over-time.json.tcl
#
# Copyright (C) 2019 ]project-open[
#
# All rights reserved. Please check
# https://www.project-open.com/license/ for details.

# ----------------------------------------------------------------------
#
# ---------------------------------------------------------------------

ad_page_contract {
    Datasource for CRM actions over time chart
    <ul>
    <li>diagram_interval options include "all_time", "last_year", "last_quarter" and "last_month"
    <li>diagram_fact options include "number" and "volume"
    </ul>
} {
    { diagram_country_code "" }
    { diagram_interval "all_time" }
    { diagram_fact "cnt" }
    { diagram_min_start_date "2010-01-01" }
}

# ----------------------------------------------------
# Defaults & Permissions
# ----------------------------------------------------

set current_user_id [ad_conn user_id]
if {![im_permission $current_user_id view_companies_all] || ![im_permission $current_user_id view_finance]} { 
    set json "{\"success\": false, \"message\": \"Insufficient permissions - you need view_companies_all and view_finance.\" }"
    doc_return 400 "application/json" $json
    ad_script_abort
}

# ----------------------------------------------------
#
# ----------------------------------------------------

switch $diagram_interval {
    all_time { set diagram_start_date [db_string all_time "
	select greatest(min(start_date)::date, :diagram_min_start_date::date) from im_projects where parent_id is null
    "] }
    last_year { set diagram_start_date [db_string year "select now()::date - 365 - 31"] }
    last_two_years { set diagram_start_date [db_string year "select now()::date - 365*2 - 31"] }
    last_five_years { set diagram_start_date [db_string year "select now()::date - 365*5 - 31"] }
    last_quarter { set diagram_start_date [db_string year "select now()::date - 90 - 31"] }
    default {
	set json "{\"success\": false, \"message\": \"Invalid diagram_interval option: '$diagram_interval'.\" }"
	doc_return 400 "application/json" $json
	ad_script_abort
    }
}
# ad_return_complaint 1 $diagram_start_date
set diagram_end_date [db_string year "select now()::date"]

# ----------------------------------------------------
# <fact> by department
# ----------------------------------------------------

set country_sql ""
if {"" ne $diagram_country_code} { set country_sql "and oiac.country = :diagram_country_code" }

set interaction_sql "
	select	*
	from
		tmp_crm_online_interactions_aggregate_country oiac
	where
		oiac.year_month > to_char(:diagram_start_date::date, 'YYYY-MM')
		$country_sql
	order by
		oiac.year_month,
		oiac.interaction_type_id
"
# ad_return_complaint 1 "<pre>$interaction_sql</pre><br>[im_ad_hoc_query -format html "$interaction_sql"]"
db_foreach interaction $interaction_sql {
    set key "$interaction_type_id-$year_month"
    set hash($key) $cnt
    set date_hash($year_month) $year_month
    set type_hash($interaction_type_id) $interaction_type_id
}
# ad_return_complaint 1 "[array get hash]"

# ----------------------------------------------------
# Dimensions
# ----------------------------------------------------

# Get the list of all interaction types
set type_sql "
	select	c.category_id as type_id
	from	im_categories c
	where	c.category_type = 'Intranet CRM Interaction'
		-- and c.enabled_p = 't'
	order by coalesce(sort_order, category_id)
"

set type_sql "
select	type_id
from	(select	count(*) as cnt,
		oiac.interaction_type_id as type_id
	from	tmp_crm_online_interactions_aggregate_country oiac
	group by oiac.interaction_type_id
	) t
where	cnt > 100
order by cnt DESC
"


set type_list {""}
db_foreach type $type_sql {
    if {[info exists type_hash($type_id)]} { lappend type_list $type_id }
}
# ad_return_complaint 1 $type_list


# Get the month dimension
set months [qsort [array names date_hash]]


# ----------------------------------------------------
# Start looping
# ----------------------------------------------------


set cnt 0
foreach month $months {
    set line [list "'Date': new Date(\"$month\")"]

    foreach type_id $type_list {
        set value ""
	set key "$type_id-$month"
	if {[info exists hash($key)]} { set value $hash($key) }
	if {"" eq $value} { set value 0 }
	lappend line "'[im_category_from_id $type_id]': $value"
    }

    lappend rows "\{[join $line ", "]\}"
    incr cnt
}


# ----------------------------------------------------
# Create JSON for data source
# ----------------------------------------------------

set json "{\"success\": true, \"message\": \"Data loaded\", \"data\": \[\n[join $rows ",\n"]\n\]}"
doc_return 200 "application/json" $json

