xquery version "3.1";
import module namespace sqlQueryGenerator="sqlQueryGenerator.xqm" at "xmldb:exist:///db/kwantu-resource/webhookServices/customAPIServices/Reports/sqlQueryGenerator.xqm";
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:processUUID := request:get-parameter('subProcessUUID','');
declare variable $local:communityId := request:get-parameter('communityId','');
declare variable $local:transformRequired := true();
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: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:capitalizeFirst($str as xs:string) {
upper-case(substring($str, 1, 1)) || lower-case(substring($str, 2))
};
declare function local:updateSpStatusForProcess($processDoc as item ()*, $spStatus as xs:string, $message as xs:string, $id as xs:string, $instanceInfo as item()*) {
try
{
let $entry := $processDoc
let $entry := map:remove($entry, "spStatus")
let $entry := map:put($entry, "spStatus", $spStatus)
let $entry :=
if($spStatus eq "error")
then(
$entry
)
else(
let $indicators := $entry?indicators
let $indicators :=
for $indicator in $indicators?*
return
if($indicator?id eq $id)
then(
map {
"id": $id,
"instances": array {
for $instance in $indicator?instances?*
return
if($instance?uuid eq $instanceInfo?id)
then(
map {
"rev": $instanceInfo?rev,
"title": $instance?title,
"uuid": $instanceInfo?id,
"seq": $instance?seq,
"key": $instance?key
}
)
else(
$instance
)
}
}
)
else(
$indicator
)
let $newEntry := map:remove($entry, "indicators")
return map:put($newEntry, "indicators", $indicators)
)
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": $message
}
)
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": $err:description
}
}
};
declare function local:cleanId($str as xs:string) {
let $cleaned := tokenize($str, "[.]")[1]
let $cleaned := replace($cleaned, '[^A-Za-z_0-9 ]', '')
return
if(contains($cleaned, " "))
then(local:camelCase($cleaned))
else($cleaned)
};
declare function local:camelCase($str as xs:string){
let $strL := tokenize($str, " ")
let $strL := for-each($strL, function($l) {local:capitalizeFirst($l)})
let $cleaned := string-join($strL, '')
return lower-case(substring($cleaned, 1,1)) || substring($cleaned, 2)
};
declare function local:getElField($field as item()*, $type as xs:string, $views as item()*) {
<elField id="{local:cleanId($field?code)}">
<displays>
{
for $view in $views?*
return
<display show="true" mode="{$view}" widget="label">
<label show="true">
<i18n xml:lang="en">{$field?label}</i18n>
</label>
<style width="70%"/>
</display>
}
</displays>
<fieldData dataType="{$type}"/>
</elField>
};
declare function local:getUiTemplate($view as xs:string) {
<uiTemplate id="document_{$view}" name="Create/Edit {$view}" mode="{$view}" uiLayoutId="{$view}">
<uiDevice deviceType="Web"/>
<uiDevice deviceType="Android"/>
</uiTemplate>
};
declare function local:getUiLayout($view as xs:string, $fields as item()*) {
<uiLayout id="{$view}">
<layout id="vbPanel1" orientation="vertical">
{
for $field in $fields
return
<element ref="{local:cleanId($field)}"/>
}
</layout>
</uiLayout>
};
declare function local:createAndStoreConfig($doc as item()*, $communityId as xs:string) {
let $setId := local:camelCase($doc?View?label)
let $views := array{"readOnly", "edit"}
let $fields := $doc?selectRepeat?selectDef?RepeatData?*
let $xml :=
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:kwantu="http://www.kwantumedia.com/2012/AtomExtension" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<id>urn:uuid:config_1_{$setId}</id>
<title type="text">{$setId}</title>
<summary type="text">{$setId}</summary>
<published>2014-07-04T15:39:08.315+05:30</published>
<updated>2014-07-04T15:39:08.315+05:30</updated>
<author type="user">
<kwantu:community>10004</kwantu:community>
<kwantu:profile>10007</kwantu:profile>
<name>Admin</name>
</author>
<contributor>
<kwantu:community>10004</kwantu:community>
<kwantu:profile>10007</kwantu:profile>
<name>Admin</name>
</contributor>
<icon src=""/>
<link href="/db/data/10004/workspace/10004-10002/editor/.feed.entry/config_1_{$setId}.entry.atom" rel="edit" type="application/atom+xml"/>
<category term="config" label="Config" scheme="schemas/comment.xsd"/>
<kwantu:control>
<kwantu:global-meta-info>
<kwantu:info key="indicator" value="config"/>
<kwantu:info key="set" value="config"/>
<kwantu:info key="app_id" value="10004-10002"/>
</kwantu:global-meta-info>
<kwantu:draft>true</kwantu:draft>
<kwantu:moderation required="false" status=""/>
<kwantu:privacy>
<kwantu:add level="0">Everyone</kwantu:add>
<kwantu:create level="0">Everyone</kwantu:create>
<kwantu:read level="0">Everyone</kwantu:read>
<kwantu:update level="0">Everyone</kwantu:update>
<kwantu:delete level="0">Everyone</kwantu:delete>
</kwantu:privacy>
<kwantu:deleted profileId="" date="">false</kwantu:deleted>
<kwantu:expired date="">false</kwantu:expired>
<kwantu:status code="0">Active</kwantu:status>
<kwantu:featured startDateTime="" endDateTime="">false</kwantu:featured>
<kwantu:release date=""/>
<kwantu:locked>
<kwantu:reserved locked="false" date="" profileId="" expire="" requestRelease=""/>
<kwantu:session locked="false" date="" profileId="" token="" expire="" requestRelease=""/>
<kwantu:form locked="false" date="" profileId="" formId="" requestRelease=""/>
<kwantu:device locked="false" date="" profileId="" deviceId="" requestRelease=""/>
</kwantu:locked>
<kwantu:refresh period="0">N/A</kwantu:refresh>
</kwantu:control>
<content>
<kwantu:sequence num="1" current="true" locked="false">
<kwantu:trace>
<kwantu:timestamps>
<kwantu:submission>2014-07-04T15:39:08.315+05:30</kwantu:submission>
</kwantu:timestamps>
<kwantu:contributor>
<kwantu:community>10004</kwantu:community>
<kwantu:profile>10007</kwantu:profile>
</kwantu:contributor>
<kwantu:moderation required="false" status=""/>
</kwantu:trace>
<kwantu:data>
<component xmlns="">
<identification id="{$setId}" applicationId="10002" baseComponentType="indicator">
<name>
<i18n xml:lang="">Kwantu Default Content</i18n>
</name>
<documentation>
<i18n xml:lang="">Kwantu Default Content Indicator</i18n>
</documentation>
</identification>
<configuration>
<indicator id="{$setId}">
<set id="{$setId}" currentVersion="1.5.0" devVersion="1.5.0">
<version version="1.5.0">
<versionInfo>
<publish/>
<upgradeInformation/>
<documentation>
<i18n xml:lang=""/>
</documentation>
</versionInfo>
<settings>
<heading>
<i18n xml:lang="en">AppCategory</i18n>
<i18n xml:lang="pt">AppCategory</i18n>
</heading>
<searchable>true</searchable>
<dataStore type="application" baseCollection="profile" collection="library/.feed.entry"/>
<privacy>
<add>
<roles>
<role id="member">Member</role>
</roles>
</add>
<create>
<roles>
<role id="member">Member</role>
</roles>
</create>
<read>
<roles>
<role id="sysAdmin">System Administrator</role>
<role id="sysConfig">System Configurator</role>
<role id="admin">Administrator</role>
<role id="owner">Owner</role>
<role id="member">Member</role><!--<role id="guest">Guest User</role>-->
</roles>
</read>
<update>
<roles>
<role id="sysAdmin">System Administrator</role>
<role id="sysConfig">System Configurator</role>
<role id="admin">Administrator</role>
<role id="owner">Owner</role>
</roles>
</update>
<delete>
<roles>
<role id="sysAdmin">System Administrator</role>
<role id="sysConfig">System Configurator</role>
<role id="admin">Administrator</role>
<role id="owner">Owner</role>
</roles>
</delete>
</privacy>
<uiTemplates>
{
for $view in $views?*
return local:getUiTemplate($view)
}
</uiTemplates>
</settings>
<uiLayouts>
{
for $view in $views?*
return local:getUiLayout($view, $fields?reference)
}
</uiLayouts>
<elements>
{
for $field in $fields
let $fieldData :=
map {
"code": $field?reference,
"label": $field?columnHeader
}
return local:getElField($fieldData, $field?dataType, $views)
}
</elements>
</version>
</set>
</indicator>
</configuration>
</component>
</kwantu:data>
</kwantu:sequence>
</content>
<kwantu:map/>
<kwantu:calendar/>
<kwantu:tags/>
<kwantu:likes/>
</entry>
let $login := xmldb:login($server:indicator_configs_path, $server:USERNAME, $server:PASSWORD)
let $store := xmldb:store($server:indicator_configs_path, "config_1_" || $setId || ".entry.atom", $xml)
return
map {
"location": $store,
"setId": $setId,
"title": $doc?View?label
}
};
declare function local:generateConfig($doc as item()*, $communityId as xs:string, $id as xs:string, $connection as xs:long){
let $dbName := sqlQueryGenerator:getDbName($communityId, $connection)
let $config := map {
"_id": $id,
"communityId": $communityId,
"db": $dbName,
"joins": [],
"context": "approved",
"isCrossTabReport": false(),
"etlType": "No",
"title": $doc?View?label,
"crossTabSettings": map {},
"type": "SDOReportSql",
"select": array{
for $row in $doc?selectRepeat?selectDef?RepeatData?*
let $columnWidth := if($row?columnWidth?code eq "No")then(0)else(xs:integer($row?columnWidth?code))
return
map {
"viewId": $doc?View?code,
"datatype": $row?dataType,
"header": $row?columnHeader,
"columnWidth": $columnWidth,
"agregationDo": "None",
"showINColumn": true(),
"field": $row?selectField,
"seq": $row?displayOrder
}
},
"sort": []
}
let $upsert := parse-json(couch-gateway:upsert-to-couchDb($server:sync-config-bucket, $id, format:map2json($config)))
return
if($upsert?ok)
then(
map {
"isError": "false",
"message": "success",
"upsert": $upsert
}
)
else(
map {
"isError": "true",
"message": "Failed to upsert doc with id = " || $doc?_id || " | reason = " || $upsert?reason
}
)
};
declare function local:addSdoToAppConfig($setId as xs:string, $title as xs:string, $applicationId as xs:string, $communityId as xs:string){
let $appConfig := local:getConfig("applicationConfig_" || $applicationId)?result
let $json :=
map {
"name": $title,
"cardinality": "single",
"desc": $title || " custom reporting object",
"version": "1",
"id": $setId,
"setId": $setId
}
let $indicators := array:filter($appConfig?indicators, function($x) {not($x?id eq $setId)})
let $indicators := array:append($indicators, $json)
let $entry := map:remove($appConfig, "indicators")
let $entry := map:put($appConfig, "indicators", $indicators)
let $upsert := parse-json(couch-gateway:upsert-to-couchDb($server:sync-config-bucket, $appConfig?_id, format:map2json($entry)))
return
if($upsert?ok)
then(
map {
"isError": "false",
"message": "success",
"upsert": $upsert
}
)
else(
map {
"isError": "true",
"message": "Failed to upsert doc with id = " || $appConfig?_id || " | reason = " || $upsert?reason
}
)
};
let $processUUID := $local:processUUID,
$communityId := $local:communityId
let $connection := server:mysql_1-8_connection()
let $processDoc1 := local:getDoc($processUUID, $communityId)
return
if($processDoc1?isError)
then(
map {
"isError": "true"
}
)
else (
let $processDoc := $processDoc1?result
let $indicators := try{$processDoc?indicators?*} catch * { () }
let $run :=
for $indicator in $indicators
where $indicator?id eq 'SDOReportSql'
let $uuid := $indicator?instances?*?uuid,
$title := $indicator?instances?*?title
let $doc1 := local:getDoc($uuid, $communityId)
return
if($doc1?isError)
then(
map {
"isError": "true"
}
)
else (
let $doc := $doc1?result?model?pending?data?SDOReportSql
let $setId := local:camelCase($doc?View?label),
$title := $doc?View?label,
$applicationId := $doc?Application?code
let $dashboard :=
if($doc?isDashboard eq "Yes")
then(
let $config := local:createAndStoreConfig($doc, $communityId)
let $updateAppConfig := local:addSdoToAppConfig($setId, $title, $applicationId, $communityId)
return
if($local:transformRequired)
then(
let $transformURI1 := $server:TRANSFORMATION_SERVER || "/db/kwantu-resource/api/rest/serializeIndicatorTemplatesToCouch.xql?communityId=" || $communityId || "&appId=" || tokenize($applicationId, ":")[1] || "&id=config_1_" || $setId || "&bootstrap=true"
let $transform1 := httpclient:get($transformURI1, false(), <headers/>)
let $transformURI2 := $server:TRANSFORMATION_SERVER || "/db/kwantu-resource/etl/pushConfigFilesToRemote.xql?communityId=" || $communityId
let $transform2 := httpclient:get($transformURI2, false(), <headers/>)
let $buildURI := $server:TRANSFORMATION_SERVER || "/db/kwantu-resource/api/rest/publishCommunityConfiguration.xq?communityId=" || $communityId || "&env=STAGE"
let $build := httpclient:get($buildURI, false(), <headers/>)
return $build
)
else(
$updateAppConfig
)
)
else ()
let $config := local:generateConfig($doc, $communityId, $doc1?result?_id, $connection)
return $config
)
return
if($run?isError eq "false")
then(
let $spStatus := "success"
return local:updateSpStatusForProcess($processDoc, $spStatus, $run?message, "", $run?upsert)
)
else(
let $spStatus := "error"
return local:updateSpStatusForProcess($processDoc, $spStatus, $run?message, "", map {})
)
)