xquery version "3.1";
import module namespace server="mod-server" at "xmldb:exist:///db/kwantu-resource/lib/mod-server.xql";
import module namespace format="format" at "xmldb:exist:///db/kwantu-resource/collectorServices/format.xqm";
import module namespace webhook2="webhook2" at "xmldb:exist:///db/kwantu-resource/modules/webhook2.xqm";
import module namespace couch-gateway = "http://www.kwantu.net/api/couchbase/couch-gateway.xqm" at "xmldb:exist:///db/kwantu-resource/api/couchbase/couch-gateway.xqm";
declare variable $local:communityId := request:get-parameter('communityId','');
declare variable $local:processUUID := request:get-parameter('subProcessUUID','');
declare variable $cmdAppId := request:get-parameter("appId", '');
declare variable $ms_1-8_connection := server:mysql_1-8_connection();
declare variable $local:maxElementLength := 100;
declare function local:getDoc($docId as xs:string, $communityId as xs:string ){
let $useCouchDb := $server:sync-bucket||"_" || $communityId
let $inputDoc1:= couch-gateway:fetchCouchbaseDoc($docId,$useCouchDb)
return $inputDoc1
};
declare function local:getAppId($profileId as xs:string, $communityId as xs:string) {
let $appConfig := local:getDoc($profileId, $communityId)?result
let $data := $appConfig?model?approved?data?*
return $data?refNo
};
declare function local:getConfig($docId as xs:string){
let $useCouchDb := $server:sync-config-bucket
let $inputDoc1:= couch-gateway:fetchCouchbaseDoc($docId,$useCouchDb)
return $inputDoc1
};
declare function local:getTaxonomy($docId as xs:string){
let $useCouchDb := $server:sync-taxonomy-bucket
let $inputDoc1:= couch-gateway:fetchCouchbaseDoc($docId,$useCouchDb)
return $inputDoc1
};
declare function local:getCategoryVersion($viewId as xs:string) {
let $config := local:getConfig($viewId)
return $config?result?view?*?categoryVersion
};
declare function local:removeDuplicateViews($views as item()*){
let $uuids := distinct-values($views?uuid)
return
for-each($uuids, function($u) {map { "uuid": $u, "version": distinct-values($views[?uuid eq $u]?version)}})
};
declare function local:strToSQLField($string as xs:string){
"`" || $string || "`"
};
declare function local:mergeListItems($list, $limit){
if($limit > 100)
then($list)
else(
try {
let $len := map:size($list)
return
$list
} catch * {
for $item in $list?*
return
try {
let $len := map:size($item)
return
$item
} catch * {
local:mergeListItems($item, $limit + 1)
}
}
)
};
declare function local:crossCheckSdoVersions($views as item()*, $appDoc as item()*){
let $sdoList := $appDoc?result?indicators?*
let $checkList :=
for $viewDoc in $views
let $uuid := $viewDoc?categoryId
let $ver := $viewDoc?categoryVersion
let $indicatorMatch := $sdoList[?setId eq $uuid]
return
if(count($indicatorMatch) eq 0)
then(
map {
"uuid": $uuid,
"version": $ver,
"isError": true(),
"message": "Data object uuid [" || $uuid || "] and version [" || $ver || "] does not have a matching uuid in the app config"
}
)
else(
let $sdoVersionInApp := $indicatorMatch[?version eq $ver]?version
return
if(string-length($sdoVersionInApp) eq 0)
then(
map {
"uuid": $uuid,
"version": $ver,
"isError": true(),
"message": "Data object uuid [" || $uuid || "] and version [" || $ver || "] does not match in App config with version [" || $sdoList[?id eq $uuid]?version || "]"
}
)
else(
map {
"uuid": $uuid,
"version": $ver,
"success": false(),
"message": ""
}
)
)
return
if($checkList?isError = true())
then(
map {
"isError": true(),
"message": string-join($checkList[?isError eq true()]?message, " | ")
}
)
else(
map {
"isError": false(),
"message": "success"
}
)
};
declare function local:getAppVersion($appId as xs:string, $communityId as xs:string, $setId as xs:string) {
let $appConfig := local:getDoc($appId, $communityId)
(: let $log := util:log("warn","debug crossCheckSdoVersions $appConfig: "|| format:map2jsonNoIndent($appConfig)):)
return
if($appConfig?isError)
then(0)
else(
let $links := $appConfig?result?links?*
(: let $log := util:log("warn","debug crossCheckSdoVersions $links: "|| format:map2jsonNoIndent($links)):)
let $appConfigurationId := $links[?Class eq "I" and ?setId eq $setId]?uuid
(: let $log := util:log("warn","debug crossCheckSdoVersions $appConfigurationId: "|| format:map2jsonNoIndent($appConfigurationId)):)
return
if(string-length($appConfigurationId) eq 0)
then(0)
else(
let $appConfigurationDoc := local:getDoc($appConfigurationId, $communityId)
(: let $log := util:log("warn","debug crossCheckSdoVersions $appConfigurationDoc: "|| format:map2jsonNoIndent($appConfigurationDoc)):)
return
if($appConfigurationDoc?isError)
then(0)
else(
let $data := $appConfigurationDoc?result?model?pending?data?*
return $data?version
)
)
)
};
declare function local:updatePublished($view as item()) {
let $configId := $view?view?code || ":" || $view?version
let $modelConfig := local:getConfig($configId)?result
return
if($modelConfig?published)
then(
map {
"ok": true(),
"message": "success",
"configId": $configId
}
)
else(
let $modelConfig := map:remove($modelConfig, "published")
let $modelConfig := map:put($modelConfig, "published", true())
return parse-json(couch-gateway:upsert-to-couchDb($server:sync-config-bucket, $modelConfig?_id, format:map2json($modelConfig)))
)
};
declare function local:updateJson($taxonomies as item()*, $json as item()*, $uuid as xs:string) {
let $seq :=
for $item at $seq in $taxonomies?*
where $item?global?uuid eq $uuid
return $seq
let $taxonomies := try{array:remove($taxonomies, $seq)} catch * {$taxonomies}
let $taxonomies := array:append($taxonomies, $json)
return $taxonomies
};
declare function local:updateSpStatusForProcess($processDoc as item ()*, $spStatus as xs:string, $appId as xs:string) {
try
{
let $entry := $processDoc
let $entry := map:remove($entry, "spStatus")
let $entry := map:put($entry, "spStatus", $spStatus)
let $upsert := parse-json(couch-gateway:upsert-to-couchDb($server:sync-bucket || "_" || $local:communityId, $local:processUUID, format:map2json($entry)))
return
if($spStatus eq "error")
then(
map {
"isError": "true",
"message": "Failed to update app doc with appId=" || $appId,
"upsert": $upsert
}
)
else(
if($upsert?ok)
then(
map {
"isError": "false",
"message": "success"
}
)
else(
map {
"isError": "true",
"message": "Failed to update spStatus in process document with processId=" || $local:processUUID || " spStatus=" || $spStatus
}
)
)
} catch * {
map {
"isError": "true",
"message": "Failed to update spStatus in process document with processId=" || $local:processUUID || " spStatus=" || $spStatus
}
}
};
let $processUUID := $local:processUUID,
$communityId := $local:communityId
let $processDoc1 := local:getDoc($processUUID, $communityId)
let $doc :=
if($processDoc1?isError)
then(<status isError="true" code="updateSqlModel" message="Input document with communityId {$communityId} and processUUID {$processUUID} not available"/>)
else (
let $processDoc := $processDoc1?result
let $indicators := try{$processDoc?indicators?*} catch * { () }
return
for $indicator in $indicators
let $uuid := $indicator?instances?*?uuid,
$title := $indicator?instances?*?title
let $doc1 := local:getDoc($uuid, $communityId)
return
if($doc1?isError)
then(<status isError="true" code="updateSqlModel" message="Input document with communityId {$communityId} and uuid {$uuid} not available"/>)
else (
let $doc := $doc1?result
let $meta-data := $doc?meta-data
let $data := $doc?model?pending?data?*
let $seq := $doc?model?pending?seq
let $appId := $meta-data?profileId
let $appConfig := local:getDoc($appId, $communityId)?result
let $views := $data?viewsRepeat?viewsDef?RepeatData
let $appVersion := local:getAppVersion($meta-data?profileId, $communityId, "configApplication")
let $appDoc := local:getConfig("applicationConfig_" || $appId || ":" || $appVersion)
let $coreViews :=
for $view in $views?*
let $isModel :=
if(contains($view?view?code, 'ViewConfig'))
then(false())
else(true())
return
if($isModel)
then(
let $configId := $view?view?code || ":" || $view?view?version
let $modelConfig := local:getConfig($configId)?result
return
for $coreView in $modelConfig?coreViews
return local:getConfig($coreView?uuid)?result?view
)
else(
local:getConfig($view?view?code)?result?view
)
let $coreViews := array:flatten($coreViews)
let $check := local:crossCheckSdoVersions($coreViews, $appDoc)
let $fileName := "sqlModels_1_Application_" || $meta-data?profileId || ":" || $appVersion
let $json :=
if(not($check?isError))
then(
let $json :=
map {
"_id": $fileName,
"data" : map {
"items": map {
"item": array {
for $view in $views?*
let $updatePublished := local:updatePublished($view)
return map {
"code": $view?view?code || ":" || $view?version,
"label": map {
"en": $view?view?label
}
}
}
}
}
}
return
map {
"isError": false(),
"message": "success",
"json": $json
}
)
else($check)
return
if($json?isError)
then($json)
else(
let $upsert := parse-json(couch-gateway:upsert-to-couchDb($server:sync-taxonomy-bucket, $json?json?_id, format:map2json($json?json)))
let $appDoc1 := local:getConfig("applicationConfig_" || $cmdAppId)
let $appDoc := $appDoc1?result
let $taxonomies := $appDoc?taxonomies
let $sqlModelsJson :=
map {
"global": map {
"dependsOn": "Application",
"version": "1",
"id": "sqlModels",
"uuid": "sqlModels"
}
}
let $applicationsJson :=
map {
"global": map {
"dependsOn": "Community",
"version": "",
"id": "Application",
"uuid": "Application"
}
}
let $communityJson :=
map {
"global": map {
"version": "",
"id": "Community",
"uuid": "Community"
}
}
let $taxonomies := local:updateJson($taxonomies, $sqlModelsJson, "sqlModels")
let $taxonomies := local:updateJson($taxonomies, $applicationsJson, "Application")
let $taxonomies := local:updateJson($taxonomies, $communityJson, "Community")
let $appDoc := map:remove($appDoc, "taxonomies")
let $appDoc := map:put($appDoc, "taxonomies", $taxonomies)
let $upsert := parse-json(couch-gateway:upsert-to-couchDb($server:sync-config-bucket, $appDoc?_id, format:map2json($appDoc)))
return
if($upsert?ok)
then(
map {
"isError": false(),
"appId": $appId
}
)
else(
map {
"isError": true(),
"appId": $appId
}
)
)
)
)
let $processDoc := $processDoc1?result
return
if($doc?isError)
then(
let $spStatus := "error"
return local:updateSpStatusForProcess($processDoc, $spStatus, $doc?appId)
)
else (
let $spStatus := "success"
return local:updateSpStatusForProcess($processDoc, $spStatus, $doc?appId)
)