cleanup: trim cfs param resource commentary

This commit is contained in:
“Naeel”
2026-04-29 21:42:19 +04:00
parent 7808083a08
commit 9cf8f5e9ce
3 changed files with 37 additions and 71 deletions
+28
View File
@@ -773,3 +773,31 @@
Результат: Результат:
- синтаксических ошибок в `v1/resources/notification_ls.cfc` не обнаружено - синтаксических ошибок в `v1/resources/notification_ls.cfc` не обнаружено
- синтаксических ошибок в `v1/resources/instance_operation_default.cfc` не обнаружено - синтаксических ошибок в `v1/resources/instance_operation_default.cfc` не обнаружено
## Обновление: выбран cleanup-проход по `instance_operation_cfs_param_ls.cfc`
Дата фиксации: 2026-04-29.
### Цель этапа
- снять с большого файла верхний слой явных рассуждений и закомментированного кода
- не вычищать насильно все технические пояснения за один проход
- спорные смысловые комментарии при необходимости оставлять и учитывать через внешний список кандидатов
### Результат этапа
В `v1/resources/instance_operation_cfs_param_ls.cfc` удалены:
- большой верхний блок авторских рассуждений про URI и контекст
- закомментированные альтернативные поля и отладочные хвосты
- часть комментариев-оценок вокруг helper-вызовов, уникальности и временных веток
- закомментированные catch/debug-блоки, не участвующие в runtime
Что оставлено:
- технические комментарии, которые все еще объясняют ограничения валидации и semantics параметров
- спорные пояснения, которые могут быть полезны при дальнейшей разборке файла
### Проверка
Измененный файл проверен на ошибки.
Результат:
- синтаксических ошибок в `v1/resources/instance_operation_cfs_param_ls.cfc` не обнаружено
@@ -53,12 +53,13 @@
### 4. `v1/resources/instance_operation_cfs_param_ls.cfc` ### 4. `v1/resources/instance_operation_cfs_param_ls.cfc`
Ожидаемо спорный файл для будущего этапа: После частичной зачистки в файле все еще оставлены:
- содержит большой пласт рассуждений автора, предупреждений и объяснений по валидации, уникальности и доступу - комментарии по смыслу валидации, уникальности и ограничениям параметров
- часть пояснений к SQL-условиям и поведению проверок
Почему вынесено заранее: Почему вынесено заранее:
- файл крупный и неоднозначный - файл крупный и неоднозначный
- лучше разбирать отдельным этапом, чем смешивать с обычной зачисткой компактных ресурсов - лучше разбирать отдельным этапом, чем смешивать с обычной зачисткой компактных ресурсов
Рекомендация: Рекомендация:
- перед правкой сначала отделить чистый commented-out код от действительно полезных пояснений к ограничениям параметров - если потребуется более жесткая зачистка, пройтись по оставшимся поясняющим комментариям отдельно и удалить те, которые не нужны для понимания правил валидации
@@ -1,27 +1,8 @@
<cfcomponent extends="taffy.core.resource" taffy:uri="/instanceOperationCfsParams"> <cfcomponent extends="taffy.core.resource" taffy:uri="/instanceOperationCfsParams">
<!--- Вот здесь мы могли бы строить URI /instances/{instanceUid}/instanceOperations/{instanceOperationUid}/CfsParams, но это создает избыточность, у нас простые суррогатные первичные ключи. С другой стороны, контекст инстанса и операции у клиента всегда имеется. Но стоит ли передавать избыточную информацию? Это иногда провоцирует путаницу. Для POST мы можем передать необходимый контекст в теле запроса, а можем в URL.
В данном случае никакого смысла смотреть на все CFS параметры нет, только в рамках операции
Но: мы не хотели бы менять положение сущности в дереве. Либо она в корне, либо она ниже. И получится, когда мы выбираем один параметр, нам ни к чему контекст - мы к нему однозначно адресуемся.
Проголосуем за отсутстие избыточности?
--->
<!--- Проверять принадлежность инстанса текущему клиенту
При выборке CFS параметров проверятся принадлежность текущей спецификации пользователя
--->
<!--- Все методы неявно получают
arguments.usrId
arguments.contragentId
arguments.contractId
arguments.specificationId
arguments.requestArguments.usrId=usrCustomerInfo.usrId; //Integer!
arguments.requestArguments.contragentId=usrCustomerInfo.contragentId; //Integer
arguments.requestArguments.contractId=usrCustomerInfo.contractId; //Integer
arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //Integer
--->
<cfsilent> <cfsilent>
<cfimport prefix="m" taglib="../lib"/> <cfimport prefix="m" taglib="../lib"/>
<cfset this.helper=CreateObject("component","lib.rest_api_helper")/><!---*** странно, почему мы его видим?---><!---вынести в апп?---> <cfset this.helper=CreateObject("component","lib.rest_api_helper")/>
</cfsilent> </cfsilent>
<!---спецификация полей, пригодных для фильтрации ---> <!---спецификация полей, пригодных для фильтрации --->
@@ -33,11 +14,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
sort={prefix="sop", type="integer"}, sort={prefix="sop", type="integer"},
is_sensitive={prefix="sop", type="boolean"}, is_sensitive={prefix="sop", type="boolean"},
depends_on_cfs_params={prefix="sop", type="string"} depends_on_cfs_params={prefix="sop", type="string"}
<!--- ,
dt_updated={prefix="e", type="date"},
service_id={prefix="e", type="integer"},
svc={prefix="v", type="string"},
is_test={prefix="e", type="boolean"} --->
} }
/> />
@@ -48,9 +24,7 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfargument name="instanceOperationUid" type="string" required=false hint="type:guid"/> <cfargument name="instanceOperationUid" type="string" required=false hint="type:guid"/>
<!---parse and validate request parameters--->
<cftry> <cftry>
<!--- *** Добавить проверку ссылочной целостности --->
<cfif !this.helper.keyExistsAndValid(arguments,"instanceOperationUid","guid")> <cfif !this.helper.keyExistsAndValid(arguments,"instanceOperationUid","guid")>
<cfthrow type="invalidParamValue" message="Missing required parameter" detail="instanceOperationUid is missing or not a valid GUID"/> <cfthrow type="invalidParamValue" message="Missing required parameter" detail="instanceOperationUid is missing or not a valid GUID"/>
</cfif> </cfif>
@@ -59,7 +33,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<!---мы мирно игнорируем поля, отсутствующие в спецификации, что позволяет не делать исключения для orderBy и т.п.---> <!---мы мирно игнорируем поля, отсутствующие в спецификации, что позволяет не делать исключения для orderBy и т.п.--->
<cfset var filter=this.helper.parseFilterParams(this.fieldsSpec)/> <cfset var filter=this.helper.parseFilterParams(this.fieldsSpec)/>
<!--- <cfset var order=this.helper.parseOrderBy(this.fieldsSpec, arguments.orderBy)/> --->
<cfcatch type="invalidParamValue"> <cfcatch type="invalidParamValue">
<cfreturn representationOf(this.helper.formatBadRequestError(cfcatch)).withStatus(400)/> <cfreturn representationOf(this.helper.formatBadRequestError(cfcatch)).withStatus(400)/>
@@ -71,7 +44,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfset var startrow=arguments.pageSize*(arguments.page-1)+1/> <cfset var startrow=arguments.pageSize*(arguments.page-1)+1/>
<cfset var local={}/> <cfset var local={}/>
<!--- *** обширное дублирование с instance_operation_cfs_param.cfc --->
<cfquery name="local.qCfsParam" result="local.result"> <cfquery name="local.qCfsParam" result="local.result">
select select
<m:field_set titleMapOut="local.titleMap" lengthOut="fieldCount"> <m:field_set titleMapOut="local.titleMap" lengthOut="fieldCount">
@@ -125,15 +97,12 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfloop query="local.qCfsParam"> <cfloop query="local.qCfsParam">
<cfif len(func)><!--- приоритет отдается функции перед списком значений---> <cfif len(func)><!--- приоритет отдается функции перед списком значений--->
<!--- *** отличается от аналогичных вызовов --->
<cfset var args = { <cfset var args = {
"functionName":"#func#", "functionName":"#func#",
"svcId":#local.qCfsParam.service_id#, "svcId":#local.qCfsParam.service_id#,
"contractId":#arguments.contractId# "contractId":#arguments.contractId#
}/> <!--- если появятся новые аргументы у новых функций, будем добавлять их сюда ---> }/>
<!--- <cfset local.qCfsParam.value_list=generateValueList(argumentCollection=#args#)/> ---> <cfinvoke component="instance_operation_cfs_param" method="generateValueList" argumentCollection=#args# returnVariable="local.qCfsParam.value_list"/>
<cfinvoke component="instance_operation_cfs_param" method="generateValueList" argumentCollection=#args# returnVariable="local.qCfsParam.value_list"/><!--- *** тут засада с форматом списка: массив или лист --->
<!--- можно перечислить именованные аргументы обычным порядком, но с коллекцией потенциально более гибко --->
<cfif (len(local.qCfsParam.func) OR len(local.qCfsParam.expression) OR len(local.qCfsParam.state_path) OR len(local.qCfsParam.nested_ref)) <cfif (len(local.qCfsParam.func) OR len(local.qCfsParam.expression) OR len(local.qCfsParam.state_path) OR len(local.qCfsParam.nested_ref))
AND len(local.qCfsParam.value_list) EQ 0> AND len(local.qCfsParam.value_list) EQ 0>
<cfset local.qCfsParam.value_list = []/> <cfset local.qCfsParam.value_list = []/>
@@ -166,7 +135,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfset "out.size"=#arrayLen(resultCollection)#/> <cfset "out.size"=#arrayLen(resultCollection)#/>
<cfset "out.results"=#resultCollection#/> <cfset "out.results"=#resultCollection#/>
<cfset "out.runDurationMs"=getTickCount()-request.startTickCount/> <cfset "out.runDurationMs"=getTickCount()-request.startTickCount/>
<!---<cfset "out.sql"=#local.result.sql#/>--->
<cfreturn representationOf(out)/> <cfreturn representationOf(out)/>
</cffunction><!--- get ---> </cffunction><!--- get --->
@@ -176,22 +144,11 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfargument name="svcOperationCfsParamId" type="string" required=true hint="type:integer"/> <cfargument name="svcOperationCfsParamId" type="string" required=true hint="type:integer"/>
<cfargument name="paramValue" type="string" required=true hint="type:string ***Валидацию пока не проводим, а надо"/> <cfargument name="paramValue" type="string" required=true hint="type:string ***Валидацию пока не проводим, а надо"/>
<cfargument name="note" type="string" required=false default="" hint="type:string description: комментарий пользователя"/> <cfargument name="note" type="string" required=false default="" hint="type:string description: комментарий пользователя"/>
<!---
неявно инжектируются
arguments.usrId (используется)
arguments.contragentId
arguments.contractId
arguments.specificationId
Мы их не декларитуем, иначе Taffy их увидит и будет думать, что надо их получить,
и включит в документацию,
и можно будет их задать принудительно, что нам совершенно не нужно
--->
<cftry> <cftry>
<cfset this.helper.validateField(arguments, "instanceOperationUid", "guid")/> <cfset this.helper.validateField(arguments, "instanceOperationUid", "guid")/>
<cfset this.helper.validateField(arguments, "svcOperationCfsParamId", "integer")/> <cfset this.helper.validateField(arguments, "svcOperationCfsParamId", "integer")/>
<!--- Еще возможна ошибка, что мы подадим параметр не от своей операции или сервиса - он останется невидим для всех --->
<cfset checkParam(arguments.svcOperationCfsParamId, arguments.paramValue, arguments.usrId)/> <cfset checkParam(arguments.svcOperationCfsParamId, arguments.paramValue, arguments.usrId)/>
<cfset checkResourceRealmAccess(arguments.instanceOperationUid, arguments.svcOperationCfsParamId, arguments.paramValue)/> <cfset checkResourceRealmAccess(arguments.instanceOperationUid, arguments.svcOperationCfsParamId, arguments.paramValue)/>
@@ -239,9 +196,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfreturn representationOf(this.helper.formatMessage("Invalid CFS parameter", "Parameter specified does not belong to this operation")).withStatus(400)/> <cfreturn representationOf(this.helper.formatMessage("Invalid CFS parameter", "Parameter specified does not belong to this operation")).withStatus(400)/>
</cfif> </cfif>
<!--- <cfif local.qTemplateSvc.isDisabled GT 0>
<cfreturn noData().withStatus(202, "Accepted")/>
<cfelse> --->
<cfquery name="local.qSave"> <cfquery name="local.qSave">
insert into instance_operation_cfs_param ( insert into instance_operation_cfs_param (
instance_operation_cfs_param_uid,instance_operation_uid,svc_operation_cfs_param_id,param_value,note,dt_created,creator_id instance_operation_cfs_param_uid,instance_operation_uid,svc_operation_cfs_param_id,param_value,note,dt_created,creator_id
@@ -255,10 +209,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
,<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.usrId#" /> ,<cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.usrId#" />
); );
</cfquery> </cfquery>
<!--- </cfif> --->
<!--- <cfcatch type="invalidParamValue">
<cfreturn representationOf(this.helper.formatBadRequestError(cfcatch)).withStatus(400)/>
</cfcatch> --->
<cfcatch type="any"> <cfcatch type="any">
<cfreturn representationOf(this.helper.formatException(cfcatch, "Internal Error")).withStatus(500)/> <cfreturn representationOf(this.helper.formatException(cfcatch, "Internal Error")).withStatus(500)/>
</cfcatch> </cfcatch>
@@ -324,10 +274,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfthrow type="invalidParamValue" message='Parameter "#local.qSvcOperationCfsParam.svc_operation_cfs_param#" value "#arguments.paramValue#" is less than "#local.qSvcOperationCfsParam.minvalue#" '/> <cfthrow type="invalidParamValue" message='Parameter "#local.qSvcOperationCfsParam.svc_operation_cfs_param#" value "#arguments.paramValue#" is less than "#local.qSvcOperationCfsParam.minvalue#" '/>
</cfif> </cfif>
<!--- *** интересно, как мы ухитряемся проверить уникальность параметра, если он относится к операции, а не к экземпляру. Нам-то нужна уникальность для стейта (и то, скорее, единовременная, и интересовать будут только успешные операции) --->
<!--- ****** Внимание! Этот код сравнивает параметры одноименных операций, но уникальность должна быть и между create-modify и т.п. --->
<cfset checkUniqueness( <cfset checkUniqueness(
arguments.svcOperationCfsParamId, arguments.svcOperationCfsParamId,
qSvcOperationCfsParam.svc_operation_cfs_param, qSvcOperationCfsParam.svc_operation_cfs_param,
@@ -358,12 +304,10 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
where p.param_value=<cfqueryparam cfsqltype="cf_sql_varchar" value=#arguments.paramValue#/> where p.param_value=<cfqueryparam cfsqltype="cf_sql_varchar" value=#arguments.paramValue#/>
AND p.svc_operation_cfs_param_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.svcOperationCfsParamId#/>/*limit to the current svc param*/ AND p.svc_operation_cfs_param_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.svcOperationCfsParamId#/>/*limit to the current svc param*/
<cfif arguments.instanceOperationCfsParamUid NEQ "00000000-0000-0000-0000-000000000000"> <cfif arguments.instanceOperationCfsParamUid NEQ "00000000-0000-0000-0000-000000000000">
<!--- не решаюсь оставить эту проверку на БД, потому что наличие записи с 00000000-0000-0000-0000-000000000000 может все сломать --->
AND p.instance_operation_cfs_param_uid <> <cfqueryparam cfsqltype="cf_sql_other" value=#arguments.instanceOperationCfsParamUid#/>/*exclude itself*/ AND p.instance_operation_cfs_param_uid <> <cfqueryparam cfsqltype="cf_sql_other" value=#arguments.instanceOperationCfsParamUid#/>/*exclude itself*/
</cfif> </cfif>
AND (select cast(st.instance_data->>'isDeleted' as boolean) from instance_state st where st.instance_uid=e.instance_uid order by version desc limit 1) IS NOT TRUE /*ignore deleted instances*/ AND (select cast(st.instance_data->>'isDeleted' as boolean) from instance_state st where st.instance_uid=e.instance_uid order by version desc limit 1) IS NOT TRUE /*ignore deleted instances*/
</cfquery><!--- ****** здесь может таиться трудно понимаемый баг с отсутствием записи ---> </cfquery>
<!--- <cfdump var=#qUnique#/><cfabort/> --->
<cfif local.qUnique.cnt GT 0> <cfif local.qUnique.cnt GT 0>
<cfthrow type="invalidParamValue" message='#arguments.svcOperationCfsParamName# = "#arguments.paramValue#" is not unique in the provider scope'/> <cfthrow type="invalidParamValue" message='#arguments.svcOperationCfsParamName# = "#arguments.paramValue#" is not unique in the provider scope'/>
</cfif> </cfif>
@@ -384,12 +328,10 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
AND svc_operation_cfs_param_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.svcOperationCfsParamId#/>/*limit to the current svc param*/ AND svc_operation_cfs_param_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.svcOperationCfsParamId#/>/*limit to the current svc param*/
AND u.usr_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.usrId#/>/*limit to the contragent of current user*/ AND u.usr_id=<cfqueryparam cfsqltype="cf_sql_integer" value=#arguments.usrId#/>/*limit to the contragent of current user*/
<cfif arguments.instanceOperationCfsParamUid NEQ "00000000-0000-0000-0000-000000000000"> <cfif arguments.instanceOperationCfsParamUid NEQ "00000000-0000-0000-0000-000000000000">
<!--- не решаюсь оставить эту проверку на БД, потому что наличие записи с 00000000-0000-0000-0000-000000000000 может все сломать --->
AND p.instance_operation_cfs_param_uid <> <cfqueryparam cfsqltype="cf_sql_other" value=#arguments.instanceOperationCfsParamUid#/>/*exclude itself*/ AND p.instance_operation_cfs_param_uid <> <cfqueryparam cfsqltype="cf_sql_other" value=#arguments.instanceOperationCfsParamUid#/>/*exclude itself*/
</cfif> </cfif>
AND (select cast(st.instance_data->>'isDeleted' as boolean) from instance_state st where st.instance_uid=e.instance_uid order by version desc limit 1) IS NOT TRUE /*ignore deleted instances*/ AND (select cast(st.instance_data->>'isDeleted' as boolean) from instance_state st where st.instance_uid=e.instance_uid order by version desc limit 1) IS NOT TRUE /*ignore deleted instances*/
</cfquery><!--- ****** здесь может таиться трудно понимаемый баг с отсутствием записи ---> </cfquery>
<!--- <cfdump var=#qUnique#/> --->
<cfif local.qUnique.cnt GT 0> <cfif local.qUnique.cnt GT 0>
<cfthrow type="invalidParamValue" message='#arguments.svcOperationCfsParamName# = "#arguments.paramValue#" is not unique in the tenant scope'/> <cfthrow type="invalidParamValue" message='#arguments.svcOperationCfsParamName# = "#arguments.paramValue#" is not unique in the tenant scope'/>
</cfif> </cfif>
@@ -405,9 +347,6 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
<cfargument name="value" type="string"/> <cfargument name="value" type="string"/>
<cfargument name="dataType" type="string"/> <cfargument name="dataType" type="string"/>
<!--- Что возвращать-то?
Идею бросать исключение при некорректном вводе надо отринуть. Все введенные параметры надо обработать и не терять --->
<cfswitch expression=#arguments.dataType#> <cfswitch expression=#arguments.dataType#>
<cfcase value=",string"> <cfcase value=",string">
<cfreturn true/> <cfreturn true/>
@@ -450,10 +389,8 @@ arguments.requestArguments.specificationId=usrCustomerInfo.specificationId; //In
</cfcase> </cfcase>
<cfdefaultcase><cfreturn true/> <cfdefaultcase><cfreturn true/>
<cfthrow type="custom" detail="unsupported CFS parameter value type (#arguments.dataType#)"/> <cfthrow type="custom" detail="unsupported CFS parameter value type (#arguments.dataType#)"/>
<!--- --->
</cfdefaultcase> </cfdefaultcase>
</cfswitch> </cfswitch>
<!--- --->
</cffunction> </cffunction>
<cffunction name="checkResourceRealmAccess" returnType="void"> <cffunction name="checkResourceRealmAccess" returnType="void">