xquery version "3.0";
(:
    ART-DECOR® STANDARD COPYRIGHT AND LICENSE NOTE
    Copyright © ART-DECOR Expert Group and ART-DECOR Open Tools GmbH
    see https://docs.art-decor.org/copyright and https://docs.art-decor.org/licenses

    This file is part of the ART-DECOR® tools suite.
:)
(:
    Xquery for setting statusCode of version/release object in a specific project
    Input: post of statusChange element:
    <version-release-status-change projectPrefix="vacc-" date="2014-05-20T11:34:22" statusCode="active"/>
:)
import module namespace get = "http://art-decor.org/ns/art-decor-settings" at "art-decor-settings.xqm";
import module namespace art = "http://art-decor.org/ns/art" at "art-decor.xqm";

(:let $statusChange := request:get-data()/version-release-status-change:)
let $statusChange := request:get-data()/*
(:
let $statusChange :=
    <version-release-status-change projectPrefix="vacc-" date="2014-05-20T11:34:22" statusCode="active"/>
:)

let $projectPrefix              := $statusChange/@projectPrefix[not(. = '')]
let $itemdate                   := $statusChange/@date[not(. = '')]
let $itemstatusCode             := $statusChange/@statusCode[not(. = '')]
let $itemdescription            := 
    for $node in $statusChange/note | $statusChange/desc
    return
        art:parseNode($node)

let $user                       := get:strCurrentUserName()

let $project                    := if (empty($projectPrefix)) then () else art:getDecorByPrefix($projectPrefix)
let $projectversionreleaseitem  := $project/project/release[@date = $itemdate] | $project/project/version[@date = $itemdate]

let $statusUpdate :=
    if ($user = $project/project/author/@username) then (
        if (empty($itemstatusCode)) then
            update delete $projectversionreleaseitem/@statusCode
        else
        if ($projectversionreleaseitem/@statusCode) then
            update value $projectversionreleaseitem/@statusCode with $itemstatusCode
        else (
            update insert attribute statusCode {$itemstatusCode} into $projectversionreleaseitem
        )
        ,
        if ($itemdescription) then (
            update delete $projectversionreleaseitem/*,
            update insert $itemdescription into $projectversionreleaseitem
        )
        else ()
        ,
        <response projectPrefix="{$projectPrefix}" date="{$itemdate}" statusCode="{$itemstatusCode}" targetDate="{$projectversionreleaseitem/@date}">OK</response>
    ) else (
        <response>NO PERMISSION</response>
    )

return
    $statusUpdate
