098 payg form corrected, fix prices excluded

This commit is contained in:
2026-10-26 12:47:55 +03:00
parent c9827623e9
commit fd056ec435
3 changed files with 124 additions and 67 deletions
+1 -1
View File
@@ -89,7 +89,7 @@
<!--- global settings --->
<!--- *************************************************************************************************** --->
<cfset request.APP_VERSION="0.00.097"/> <!--- *********************************************************** --->
<cfset request.APP_VERSION="0.00.098"/> <!--- *********************************************************** --->
<!--- *************************************************************************************************** --->
<cfset request.STAND=getStand()/>
<cfset request.RECORDS_PER_PAGE=500/>
+47 -17
View File
@@ -185,6 +185,7 @@
,p.cnt as p_cnt
,p.ed_izm
,p.code
,p.type as p_type
,p.discount as p_discount
,p.__id as p_uid
,p.name
@@ -245,22 +246,23 @@
<!--- <td class="c">#__name#</td> --->
<td class="l">#user_description#</td>
<td>
<table class="wide">
<cfset cost=0/>
<cfoutput group="p_uid">
<cfif p_cnt NEQ 0>
<tr>
<td class="nw">#code#</td>
<td>#name#</td>
<td>#p_cnt#</td>
<td>#ed_izm#</td>
<td class="r nw">#nFmt(price,3)#</td>
<td class="r">#p_discount#%</td>
</tr>
<cfset cost+=price*p_cnt*(100-(isNumeric(p_discount)?p_discount:0))/100 />
</cfif>
</cfoutput>
</table>
<table class="wide">
<cfset cost=0/>
<cfoutput group="p_uid">
<cfif p_cnt NEQ 0>
<tr>
<td class="nw">#code#</td>
<td>#name#</td>
<td>#p_cnt#</td>
<td>#ed_izm#</td>
<td class="r nw">#nFmt(price,3)#</td>
<td class="r">#p_discount#%</td>
<td class="r"><cftry>#gaussianRound((100.-discount)/100.*price*(100.-p_discount)/100.,2)#<cfcatch type="any"></cfcatch></cftry></td>
</tr>
<cfset cost+=price*p_cnt*(100-(isNumeric(p_discount)?p_discount:0))/100 />
</cfif>
</cfoutput>
</table>
</td>
<td class="c">#cnt#</td>
<td class="c">#discount#%</td>
@@ -536,4 +538,32 @@
</table>
</cfif><!--- len(d.__id) --->
<layout:page section="footer"/>
<layout:page section="footer"/>
<cfscript>
string function gaussianRoundSafe(any num, numeric precision = 0, string default="") {
return (isNumeric(arguments.num)) ? gaussianRound(arguments.num, arguments.precision) : arguments.default;
}
function gaussianRound(numeric number, numeric precision = 0) {
var factor = 10 ^ precision;
var scaledNumber = number * factor;
var absScaled = abs(scaledNumber);
var sign = sgn(scaledNumber);
var floored = int(absScaled);
// If it's not ending in exactly .5, use standard rounding or precision scaling
if (absScaled - floored != 0.5) {
return round(number * factor) / factor;
}
// If it is exactly .5, round towards the nearest even number
if (floored % 2 != 0) {
// Nearest even is UP
return (floored + 1) * sign / factor;
} else {
// Nearest even is DOWN
return floored * sign / factor;
}
}
</cfscript>
+76 -49
View File
@@ -7,27 +7,34 @@
<m:prepare_ls entity="payg" accessObject="" pageInfoOut="pageInfo" trackOut="tr"/>
<!--- проблема: пустой чек-бокс не передается, невозможно отличить "чек-бокс очищен" от "параметров нет, использовать дефолт" (например, при обращении к странице по GET)
решение: если передается форма, то отсутствие чек-бокса однозначно означает, что он очищен.
Передачу формы можно надежно обозначить скрытым полем. Можно для экономии использовать имя кнопки, но кнопок у меня 2, сабмит и дебаг
NB при передаче формы GET структура FORM пустая
мне подсказывают, что удобно передавать qwery or filter гетом, тогда можно урлу сохранить --->
<cfparam name="submit" default=""/>
<cfparam name="debug" default=""/>
<cfif len(submit) or len(debug)>
<!--- считаем, что отправлена форма и отсутствие чекбокса нужно трактовать как FALSE --->
<cfparam name="only_articles_in_spec" default=0/>
<cfparam name="inner_join" default=0/>
<cfelse>
<!--- это обращение по неквалифицированному URL и отсутствие чекбокса означает USE DEFAULT --->
<cfparam name="only_articles_in_spec" default=1/>
<cfparam name="inner_join" default=1/>
</cfif>
<cfparam name="code" default=""/>
<!---
<cfparam name="dt_finish" type="date" default=#createDateTime(year(Now()),month(Now()),1,0,0,0)#/>
<cfparam name="dt_start" type="date" default=#dateAdd('m',-1,dt_finish)#/> --->
<cfparam name="dt_start" type="date" default=#dateAdd('m',-1,dt_finish)#/> --->и
<cfparam name="dt_finish" type="date" default=#dateAdd('d',-1,createDateTime(year(Now()),month(Now()),1,0,0,0))#/>
<cfparam name="dt_start" type="date" default=#dateAdd('m',-1,createDateTime(year(Now()),month(Now()),1,0,0,0))#/>
<cfset hours=dateDiff('h', dt_start, dateAdd('d', 1, dt_finish))/>
<cfparam name="wz" default=""/>
<!--- *** костыль --->
<!--- нужно также позаботиться о передаче через url --->
<cfparam name="only_articles_in_spec" default=0/>
<cfset local.only_articles_in_spec=only_articles_in_spec/><!--- *** некорректное название --->
<cfparam name="inner_join" default=0/>
<cfset local.inner_join=inner_join/>
<!--- <cfparam name="local.only_articles_in_spec" type="boolean" default=#structIsEmpty(form)? true : (form?.only_articles_in_spec GT 0)# /> <!--- не вполне корректный способ определить наличие формы, если там все чекбоксы и ни один не выбран... --->
<cfparam name="local.inner_join" type="boolean" default=#structIsEmpty(form)? true : (form?.inner_join GT 0)# /> --->
<cfparam name="code" default=""/>
<!--- *** коды лучше взять из каталога --->
<cfquery name="qCode" datasource="dwh" cachedWithin=#createTimeSpan(0, 0, 20, 0)#>
select distinct p.code
@@ -64,11 +71,13 @@
AS (VALUES
('Закрыта неуспешно',7,0),('Закрыта успешно',6,100),('Договор подписан',5,100),('Договор на подписании',15,90),('Договор на согласовании',12,70),
('Тестирование',8,50),('Отправлено ТКП',10,20),('Внутреннее согласование',37,10),('Проработка решения',4,10),('Сбор потребностей',1,0)
)
select upper(trim(k.id_klienta)) as wz,
),
line as (
select
upper(trim(k.id_klienta)) as wz,
k.__id::text as contragent_uid,
p.code,
SUBSTRING(p.code FROM 1 FOR LENGTH(p.code) - 2) as sku_code,
SUBSTRING(p.code FROM 1 FOR LENGTH(p.code) - 2) as sku_code, --оказывается, есть ошибки в данных, когда суффикс потерян, на этот случай надо парсить код
p.price,
p.discount as component_discount,
k.__name as contragent,
@@ -76,6 +85,7 @@
a.__id::text as contract_uid,
d.__name as deal,
d.__id::text as deal_uid,
d.__index AS deal_index,
siv.abstractive_service as abstract_service,
siv.modifier, siv.user_description,
siv.hash as line_key
@@ -83,30 +93,24 @@
siv.date_end as serviceEnd,
siv.discount as service_discount,
siv.cnt as service_quantity
/*,p.__name as line_key*/, p.ed_izm, p.name as component, p.type, p.cnt*coalesce(siv.cnt,1) as component_quantity,
, p.ed_izm, p.name as component, p.type, p.cnt*coalesce(siv.cnt,1) as component_quantity,
aa.__name as additional_agreement, aa.__id::text as additional_agreement_uid
--, aa.is_actual
,siv.end_customer::text as end_customer_uid
,z.id_klienta as end_customer_wz
,z.__name as end_customer_name
--,ft.free_tier
,s.probability_pc
,siv.__id::text as siv_uid
,coalesce(siv.cnt*(100.-siv.discount)/100.*p.price*(100.-p.discount)/100., 0.) as discounted_price
,CASE WHEN p.type=3 THEN coalesce(siv.cnt*(100.-siv.discount)/100.*p.price*(100.-p.discount)/100., 0.) ELSE NULL END as discounted_price
from elma.deals d
JOIN STATUS s ON (d.__status_status = s.status_id)
join elma.deals_services siv on (d.__id=ANY(siv.deal))
--join elma.service_parametrs p on (p.__id = ANY(siv.params))
LEFT JOIN LATERAL unnest(siv.params) AS arr(param_id) ON TRUE
JOIN elma.service_parametrs p ON (p.__id = arr.param_id)
join elma.companies k on (d._companies=k.__id)
join elma.additional_agreements aa on (aa.__id = ANY(siv.additional_agreement))
join elma.aggrements a on (aa.contract_uid = a.__id)
left outer join elma.companies z on (siv.end_customer=z.__id)
where p.type IN (2,3) AND aa.is_actual
AND siv.date_nop < <cfqueryparam cfsqltype="cf_sql_timestamp" value=#dt_finish#/>
AND (siv.date_end > <cfqueryparam cfsqltype="cf_sql_timestamp" value=#dt_start#/> OR siv.date_end IS NULL)/*****/
LEFT OUTER JOIN elma.companies z on (siv.end_customer=z.__id)
WHERE p.type IN (2,3) AND aa.is_actual
AND aa."__deletedAt" IS NULL
AND a."__deletedAt" IS NULL
AND d."__deletedAt" IS NULL
@@ -119,19 +123,42 @@
<cfif len(code)>
AND p.code like <cfqueryparam cfsqltype="cf_sql_varchar" value="%#code#%"/>
</cfif>
<cfif local.only_articles_in_spec>
<cfif only_articles_in_spec>
AND p.type=3
</cfif>
--AND k.id_klienta='WZ01031'
--AND k.id_klienta='WZ01112'
order by k.id_klienta, p.code
),
stair
AS (
SELECT *
FROM (
SELECT *
,MIN(serviceStart) OVER (
PARTITION BY line_key ORDER BY deal_index DESC
) running_min_dt
,COALESCE((
LEAD(serviceStart) OVER (
PARTITION BY line_key ORDER BY serviceStart
,deal_index
)
), (
SELECT CURRENT_TIMESTAMP + INTERVAL '1 day' --*** not sure
)) dt_next
FROM line
WHERE probability_pc = 100
) t
WHERE t.serviceStart = t.running_min_dt
)
select d.* from stair d
WHERE d.serviceStart < <cfqueryparam cfsqltype="cf_sql_timestamp" value=#dt_finish#/>
AND (d.serviceEnd > <cfqueryparam cfsqltype="cf_sql_timestamp" value=#dt_start#/> OR d.serviceEnd IS NULL)
order by wz, type DESC, code
</cfquery>
<!--- select * from elma.deals_services where __id='019edf9c-c1e8-7acd-8b63-5369e5be5bf5'
union all
select * from elma.deals_services where __id='019edf9c-c23d-7ad6-a990-643dd09579b8' --->
<!--- здесь имеем список кодов с ценами и WZ. Каждому коду можно поставить в соответствие запрос, который даст по нему выборку. Изредка один запрос может вывести 2 кода, но разбить на 2 запроса легко. Кроме того, запросы можно объединить через union в один - может быть, так будет лучше читаться (быстрее выполняться не будет) --->
<cfoutput>qSpec:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qSpec#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -180,7 +207,7 @@ select * from elma.deals_services where __id='019edf9c-c23d-7ad6-a990-643dd09579
<cfoutput>qComputing:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qComputing#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -237,7 +264,7 @@ select * from elma.deals_services where __id='019edf9c-c23d-7ad6-a990-643dd09579
<cfoutput>qStorage:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qStorage#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -280,7 +307,7 @@ HOT_FREE_LIMIT 1 10 1 100
<cfoutput>qS3Vol:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qS3Vol#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -351,7 +378,7 @@ select
<cfoutput>qS3OpsTrf:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qS3OpsTrf#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -376,7 +403,7 @@ select
</cfquery>
<cfoutput>qS3User:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qS3User#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -416,7 +443,7 @@ select
<cfoutput>qGpu:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qGpu#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -502,7 +529,7 @@ select
<cfoutput>qUnifiedMetric:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qUnifiedMetric#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -647,7 +674,7 @@ SELECT
</d:field_set>
<!--- --,'***' as delim,s.* --->
FROM metric m
<cfif local.inner_join>
<cfif inner_join>
INNER
<cfelse>
FULL
@@ -680,7 +707,7 @@ ORDER BY coalesce(coalesce(c.wz, m.wz), s.wz), coalesce(s.code, m.code)
<!--- <cfdump var=#qCharge#/> --->
<cfoutput>qCharge:#getTickCount()-request.startTickCount#</cfoutput><cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
<cfif isDefined("DEBUG")>
<cfif len(debug)>
<cfdump var=#qCharge#/>
<cfif !isDefined("output_xls") AND !isDefined("output_json")><cfflush/></cfif>
</cfif>
@@ -711,18 +738,18 @@ ORDER BY coalesce(coalesce(c.wz, m.wz), s.wz), coalesce(s.code, m.code)
<br/>
Даты актуальности пока проверять вручную. Обращать внимание на замножение строк.
<cfoutput>
<form method="post" action="">
<form method="get" action="">
Период с <input type="text" name="dt_start" value="#dateFormat(dt_start,'YYYY-MM-DD')#"/>
по <input type="text" name="dt_finish" value="#dateFormat(dt_finish,'YYYY-MM-DD')#"/>
<input type="checkbox" name="only_articles_in_spec" id="only_articles_in_spec" value="1"<cfif local.only_articles_in_spec> checked</cfif>/><label for="only_articles_in_spec">Только PAYG </label>
<input type="checkbox" name="inner_join" id="inner_join" value="1"<cfif local.inner_join> checked</cfif>/><label for="inner_join">Только найденные в договоре</label>
<input type="checkbox" name="only_articles_in_spec" id="only_articles_in_spec" value="1"<cfif only_articles_in_spec> checked</cfif>/><label for="only_articles_in_spec">Только PAYG </label>
<input type="checkbox" name="inner_join" id="inner_join" value="1"<cfif inner_join> checked</cfif>/><label for="inner_join">Только найденные в договоре</label>
&nbsp;&nbsp;&nbsp;
WZ <input type="text" name="wz" value="#wz#"/>по вхождению, с регистром
&nbsp;&nbsp;&nbsp;
Код <input type="text" name="code" value="#code#"/>по вхождению
&nbsp;&nbsp;&nbsp;
<input type="submit" style="cursor:pointer;"/>
<input type="submit" name="DEBUG" value="DEBUG" style="cursor:pointer;"/><!--- #dateFormat( input, "yyyy-mm-dd" )#T#timeFormat( input, "HH:mm:ss.lXX" )# --->
<input type="submit" name="submit" style="cursor:pointer;"/>
<input type="submit" name="debug" value="DEBUG" style="cursor:pointer;"/><!--- #dateFormat( input, "yyyy-mm-dd" )#T#timeFormat( input, "HH:mm:ss.lXX" )# --->
</form>
Часов в периоде: <b>#hours#</b> Строк в отчете: <b>#qCharge.recordCount#</b><br/>
Актуальность данных:
@@ -735,9 +762,9 @@ S3 операции и трафик: <b<cfif datediff("h",qS3OpsTrfAge.dt_load,
<!--- <a href="#request.thisPage#?output_xls" title="экспорт в Excel" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/xls.gif" style="vertical-align:text-bottom;"/></a>
<a href="#request.thisPage#?output_json" title="экспорт в json" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/json.svg" style="vertical-align:text-bottom;" width="13" height="13"/></a> --->
<a href="#request.thisPage#?output_xls&dt_start=#dateFormat(dt_start,'YYYY-MM-DD')#&dt_finish=#dateFormat(dt_finish,'YYYY-MM-DD')#&inner_join=#local.inner_join#&only_articles_in_spec=#local.only_articles_in_spec#&code=#code#&wz=#wz#" title="экспорт в Excel" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/xls.gif" style="vertical-align:text-bottom;"/></a>
<a href="#request.thisPage#?output_xls&submit=1&dt_start=#dateFormat(dt_start,'YYYY-MM-DD')#&dt_finish=#dateFormat(dt_finish,'YYYY-MM-DD')#&inner_join=#inner_join#&only_articles_in_spec=#only_articles_in_spec#&code=#code#&wz=#wz#" title="экспорт в Excel" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/xls.gif" style="vertical-align:text-bottom;"/></a>
<a href="#request.thisPage#?output_json&dt_start=#dateFormat(dt_start,'YYYY-MM-DD')#&dt_finish=#dateFormat(dt_finish,'YYYY-MM-DD')#&inner_join=#local.inner_join#&only_articles_in_spec=#local.only_articles_in_spec#&code=#code#&wz=#wz#" title="экспорт в json" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/json.svg" style="vertical-align:text-bottom;" width="13" height="13"/></a>
<a href="#request.thisPage#?output_json&submit=1&dt_start=#dateFormat(dt_start,'YYYY-MM-DD')#&dt_finish=#dateFormat(dt_finish,'YYYY-MM-DD')#&inner_join=#inner_join#&only_articles_in_spec=#only_articles_in_spec#&code=#code#&wz=#wz#" title="экспорт в json" style="margin-left:.5em; height:100%;" target="_blank"><img src="img/json.svg" style="vertical-align:text-bottom;" width="13" height="13"/></a>
<i><b>(перед выгрузкой отчета на произвольную дату или с параметрами сначала просмотрите его в браузере)</b></i>
<br/>
<span class="gray">серая строка</span> - нет метрик; <span class="err">красное</span> число в поле "Кол-во специф." - для PAYG в спецификации кол-во не 1
@@ -883,7 +910,7 @@ S3 операции и трафик: <b<cfif datediff("h",qS3OpsTrfAge.dt_load,
<td class="b r">#current_price#</td>
<td class="b r">#gaussianRoundSafe(cost_dimension_1,2)#</td>
<td colspan="7"></td>
<td class="b r" title="сумма корректна, если нет замножения строк из-за наличия PAYG и FIX по одному артикулу">#request.roundSafe(accum_metric_dimension_1_all,3)#<!--- #final_metric_dimension_1_all# ---></td>
<td class="b r" title="сумма корректна, если нет замножения строк из-за наличия PAYG и FIX по одному артикулу"><!--- #request.roundSafe(accum_metric_dimension_1_all,3)# --->#final_metric_dimension_1_all#</td>
</tr>
</cfoutput><!--- serviceStart --->
</cfoutput><!--- code --->