Fixed test.

Fixed test.

import module namespace response = "http://www.28msec.com/modules/http-response";
import module namespace request = "http://www.28msec.com/modules/http-request";
import module namespace test = "http://apps.28.io/test";
import module namespace config = "http://apps.28.io/config";

declare variable $local:expected as object :=
    {
      "dow30" : [ "http://www.sec.gov/CIK 0000066740", "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000012927", "http://www.sec.gov/CIK 0000018230", "http://www.sec.gov/CIK 0000093410", "http://www.sec.gov/CIK 0000858877", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000030554", "http://www.sec.gov/CIK 0000034088", "http://www.sec.gov/CIK 0000040545", "http://www.sec.gov/CIK 0000886982", "http://www.sec.gov/CIK 0000354950", "http://www.sec.gov/CIK 0000050863", "http://www.sec.gov/CIK 0000051143", "http://www.sec.gov/CIK 0000200406", "http://www.sec.gov/CIK 0000019617", "http://www.sec.gov/CIK 0000063908", "http://www.sec.gov/CIK 0000789019", "http://www.sec.gov/CIK 0000310158", "http://www.sec.gov/CIK 0000320187", "http://www.sec.gov/CIK 0000078003", "http://www.sec.gov/CIK 0000080424", "http://www.sec.gov/CIK 0000086312", "http://www.sec.gov/CIK 0000101829", "http://www.sec.gov/CIK 0000731766", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001403161", "http://www.sec.gov/CIK 0000104169", "http://www.sec.gov/CIK 0001001039" ],
      "generic" : [ "http://www.sec.gov/CIK 0000004962" ],
      "cik" : [ "http://www.sec.gov/CIK 0000004962" ],
      "ticker" : [ "http://www.sec.gov/CIK 0000104169" ],
      "ticker2" : [ "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000104169" ],
      "sic" : [ "http://www.sec.gov/CIK 0001585644", "http://www.sec.gov/CIK 0001608249", "http://www.sec.gov/CIK 0001023731", "http://www.sec.gov/CIK 0001089511", "http://www.sec.gov/CIK 0000104777", "http://www.sec.gov/CIK 0001047919", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000879585", "http://www.sec.gov/CIK 0001122063", "http://www.sec.gov/CIK 0001104358", "http://www.sec.gov/CIK 0001205727", "http://www.sec.gov/CIK 0000018926", "http://www.sec.gov/CIK 0000716133", "http://www.sec.gov/CIK 0001161706", "http://www.sec.gov/CIK 0001457737", "http://www.sec.gov/CIK 0001304421", "http://www.sec.gov/CIK 0001086740", "http://www.sec.gov/CIK 0001352819", "http://www.sec.gov/CIK 0001084384", "http://www.sec.gov/CIK 0001101239", "http://www.sec.gov/CIK 0000766561", "http://www.sec.gov/CIK 0001062613", "http://www.sec.gov/CIK 0001504678", "http://www.sec.gov/CIK 0000020520", "http://www.sec.gov/CIK 0001071411", "http://www.sec.gov/CIK 0000075679", "http://www.sec.gov/CIK 0000808461", "http://www.sec.gov/CIK 0001061322", "http://www.sec.gov/CIK 0000746210", "http://www.sec.gov/CIK 0001384929", "http://www.sec.gov/CIK 0001315255", "http://www.sec.gov/CIK 0001006837", "http://www.sec.gov/CIK 0001005731", "http://www.sec.gov/CIK 0001041954", "http://www.sec.gov/CIK 0001292653", "http://www.sec.gov/CIK 0001160142", "http://www.sec.gov/CIK 0001084752", "http://www.sec.gov/CIK 0000794323", "http://www.sec.gov/CIK 0001130888", "http://www.sec.gov/CIK 0001520744", "http://www.sec.gov/CIK 0001005699", "http://www.sec.gov/CIK 0000732412", "http://www.sec.gov/CIK 0000071557", "http://www.sec.gov/CIK 0001328571", "http://www.sec.gov/CIK 0001288359", "http://www.sec.gov/CIK 0001372041", "http://www.sec.gov/CIK 0000090721", "http://www.sec.gov/CIK 0001558294", "http://www.sec.gov/CIK 0001405660", "http://www.sec.gov/CIK 0001458704", "http://www.sec.gov/CIK 0001143238", "http://www.sec.gov/CIK 0001037949", "http://www.sec.gov/CIK 0000068622", "http://www.sec.gov/CIK 0001341319", "http://www.sec.gov/CIK 0000354963", "http://www.sec.gov/CIK 0000101830", "http://www.sec.gov/CIK 0000943117", "http://www.sec.gov/CIK 0001560158", "http://www.sec.gov/CIK 0001051512", "http://www.sec.gov/CIK 0001101688", "http://www.sec.gov/CIK 0001499355", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001270400", "http://www.sec.gov/CIK 0001322791", "http://www.sec.gov/CIK 0001353505", "http://www.sec.gov/CIK 0001272830", "http://www.sec.gov/CIK 0001562636", "http://www.sec.gov/CIK 0001282266", "http://www.sec.gov/CIK 0000919742", "http://www.sec.gov/CIK 0001111634", "http://www.sec.gov/CIK 0001448962", "http://www.sec.gov/CIK 0001502756", "http://www.sec.gov/CIK 0001373444", "http://www.sec.gov/CIK 0001057758" ],
      "sic-dow30": [ "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000732712" ],
      "mixed" : [ "http://www.sec.gov/CIK 0001585644", "http://www.sec.gov/CIK 0001608249", "http://www.sec.gov/CIK 0001023731", "http://www.sec.gov/CIK 0001089511", "http://www.sec.gov/CIK 0000104777", "http://www.sec.gov/CIK 0001047919", "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000879585", "http://www.sec.gov/CIK 0001122063", "http://www.sec.gov/CIK 0001104358", "http://www.sec.gov/CIK 0001205727", "http://www.sec.gov/CIK 0000018926", "http://www.sec.gov/CIK 0000716133", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0001161706", "http://www.sec.gov/CIK 0001457737", "http://www.sec.gov/CIK 0001304421", "http://www.sec.gov/CIK 0001086740", "http://www.sec.gov/CIK 0001352819", "http://www.sec.gov/CIK 0001084384", "http://www.sec.gov/CIK 0001101239", "http://www.sec.gov/CIK 0000766561", "http://www.sec.gov/CIK 0001062613", "http://www.sec.gov/CIK 0001504678", "http://www.sec.gov/CIK 0000020520", "http://www.sec.gov/CIK 0001071411", "http://www.sec.gov/CIK 0000075679", "http://www.sec.gov/CIK 0000808461", "http://www.sec.gov/CIK 0001061322", "http://www.sec.gov/CIK 0000746210", "http://www.sec.gov/CIK 0001384929", "http://www.sec.gov/CIK 0001315255", "http://www.sec.gov/CIK 0001006837", "http://www.sec.gov/CIK 0001005731", "http://www.sec.gov/CIK 0001041954", "http://www.sec.gov/CIK 0001292653", "http://www.sec.gov/CIK 0001160142", "http://www.sec.gov/CIK 0001084752", "http://www.sec.gov/CIK 0000794323", "http://www.sec.gov/CIK 0001130888", "http://www.sec.gov/CIK 0001520744", "http://www.sec.gov/CIK 0001005699", "http://www.sec.gov/CIK 0000732412", "http://www.sec.gov/CIK 0000071557", "http://www.sec.gov/CIK 0001328571", "http://www.sec.gov/CIK 0001288359", "http://www.sec.gov/CIK 0001372041", "http://www.sec.gov/CIK 0000090721", "http://www.sec.gov/CIK 0001558294", "http://www.sec.gov/CIK 0001405660", "http://www.sec.gov/CIK 0001458704", "http://www.sec.gov/CIK 0001143238", "http://www.sec.gov/CIK 0001037949", "http://www.sec.gov/CIK 0000068622", "http://www.sec.gov/CIK 0001341319", "http://www.sec.gov/CIK 0000354963", "http://www.sec.gov/CIK 0000101830", "http://www.sec.gov/CIK 0000943117", "http://www.sec.gov/CIK 0001560158", "http://www.sec.gov/CIK 0001051512", "http://www.sec.gov/CIK 0001101688", "http://www.sec.gov/CIK 0001499355", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001270400", "http://www.sec.gov/CIK 0001322791", "http://www.sec.gov/CIK 0001353505", "http://www.sec.gov/CIK 0001272830", "http://www.sec.gov/CIK 0001562636", "http://www.sec.gov/CIK 0000104169", "http://www.sec.gov/CIK 0001282266", "http://www.sec.gov/CIK 0000919742", "http://www.sec.gov/CIK 0001111634", "http://www.sec.gov/CIK 0001448962", "http://www.sec.gov/CIK 0001502756", "http://www.sec.gov/CIK 0001373444", "http://www.sec.gov/CIK 0001057758" ],
      "mixed-dow30": [ "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0000104169" ]
    };

declare %an:nondeterministic function local:test-example1() as item
{
  let $expected :=
  [ {
    "_id" : "http://www.sec.gov/CIK 0000021344",
    "Archives" : "http://" || request:server-name() || ":" || request:server-port() ||
      "/v1/_queries/public/api/filings.jq?_method=POST&token=" || $config:test-token || "&eid=http%3A%2F%2Fwww.sec.gov%2FCIK%200000021344&format=&profile-name=sec&fiscalYear=ALL&fiscalPeriod=ALL",
    "Profiles" : {
      "SEC" : {
        "Name" : "SEC",
        "CompanyName" : "COCA COLA CO",
        "CompanyType" : "Corporation",
        "CIK" : "0000021344",
        "SIC" : "2080",
        "SICDescription" : "BEVERAGES",
        "SICGroup" : 9,
        "Taxonomy" : "ci",
        "Sector" : "Food/Kindred Products",
        "Tickers" : [ "ko" ],
        "Tags" : [ "FORTUNE100", "DOW30", "RUSSELL1000", "SP500" ],
        "IsTrust" : false
      }
    }
  } ]
  let $endpoint := "entities"
  let $params := {cik:"21344"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].Entities
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-entities(
    $expected as array,
    $params as object) as item
{
    let $endpoint := "entities"
    let $request := test:invoke($endpoint, $params)
    let $actual as array := [ $request[2].Entities[]._id ]
    let $status as integer := $request[1]
    return test:assert-eq-array($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

let $dow30 := test:is-dow30()
return local:check({
    dow30: local:test-entities($local:expected.dow30, {tag:"DOW30"}),
    generic: local:test-entities($local:expected.generic, {eid:"http://www.sec.gov/CIK 0000004962", profile-name:"generic"}),
    cik: local:test-entities($local:expected.cik, {cik:"4962"}),
    ticker: local:test-entities($local:expected.ticker, {ticker:"wmt"}),
    ticker2: local:test-entities($local:expected.ticker2, {ticker:["wmt","ko"]}),
    sic: local:test-entities(if($dow30) then $local:expected.sic-dow30 else $local:expected.sic, {sic:"4813"}),
    mixed: local:test-entities(if($dow30) then $local:expected.mixed-dow30 else $local:expected.mixed, {cik:"4962", sic:"4813", ticker:[ "wmt", "ko" ]}),
    example1: local:test-example1()
})

import module namespace response = "http://www.28msec.com/modules/http-response";
import module namespace request = "http://www.28msec.com/modules/http-request";
import module namespace test = "http://apps.28.io/test";
import module namespace config = "http://apps.28.io/config";

declare variable $local:expected as object :=
    {
      "dow30" : [ "http://www.sec.gov/CIK 0000066740", "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000012927", "http://www.sec.gov/CIK 0000018230", "http://www.sec.gov/CIK 0000093410", "http://www.sec.gov/CIK 0000858877", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000030554", "http://www.sec.gov/CIK 0000034088", "http://www.sec.gov/CIK 0000040545", "http://www.sec.gov/CIK 0000886982", "http://www.sec.gov/CIK 0000354950", "http://www.sec.gov/CIK 0000050863", "http://www.sec.gov/CIK 0000051143", "http://www.sec.gov/CIK 0000200406", "http://www.sec.gov/CIK 0000019617", "http://www.sec.gov/CIK 0000063908", "http://www.sec.gov/CIK 0000789019", "http://www.sec.gov/CIK 0000310158", "http://www.sec.gov/CIK 0000320187", "http://www.sec.gov/CIK 0000078003", "http://www.sec.gov/CIK 0000080424", "http://www.sec.gov/CIK 0000086312", "http://www.sec.gov/CIK 0000101829", "http://www.sec.gov/CIK 0000731766", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001403161", "http://www.sec.gov/CIK 0000104169", "http://www.sec.gov/CIK 0001001039" ],
      "generic" : [ "http://www.sec.gov/CIK 0000004962" ],
      "cik" : [ "http://www.sec.gov/CIK 0000004962" ],
      "ticker" : [ "http://www.sec.gov/CIK 0000104169" ],
      "ticker2" : [ "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000104169" ],
      "sic" : [ "http://www.sec.gov/CIK 0001585644", "http://www.sec.gov/CIK 0001608249", "http://www.sec.gov/CIK 0001023731", "http://www.sec.gov/CIK 0001089511", "http://www.sec.gov/CIK 0000104777", "http://www.sec.gov/CIK 0001047919", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000879585", "http://www.sec.gov/CIK 0001122063", "http://www.sec.gov/CIK 0001104358", "http://www.sec.gov/CIK 0001205727", "http://www.sec.gov/CIK 0000018926", "http://www.sec.gov/CIK 0000716133", "http://www.sec.gov/CIK 0001161706", "http://www.sec.gov/CIK 0001457737", "http://www.sec.gov/CIK 0001304421", "http://www.sec.gov/CIK 0001086740", "http://www.sec.gov/CIK 0001352819", "http://www.sec.gov/CIK 0001084384", "http://www.sec.gov/CIK 0001101239", "http://www.sec.gov/CIK 0000766561", "http://www.sec.gov/CIK 0001062613", "http://www.sec.gov/CIK 0001504678", "http://www.sec.gov/CIK 0000020520", "http://www.sec.gov/CIK 0001071411", "http://www.sec.gov/CIK 0000075679", "http://www.sec.gov/CIK 0000808461", "http://www.sec.gov/CIK 0001061322", "http://www.sec.gov/CIK 0000746210", "http://www.sec.gov/CIK 0001384929", "http://www.sec.gov/CIK 0001315255", "http://www.sec.gov/CIK 0001006837", "http://www.sec.gov/CIK 0001005731", "http://www.sec.gov/CIK 0001041954", "http://www.sec.gov/CIK 0001292653", "http://www.sec.gov/CIK 0001160142", "http://www.sec.gov/CIK 0001084752", "http://www.sec.gov/CIK 0000794323", "http://www.sec.gov/CIK 0001130888", "http://www.sec.gov/CIK 0001520744", "http://www.sec.gov/CIK 0001005699", "http://www.sec.gov/CIK 0000732412", "http://www.sec.gov/CIK 0000071557", "http://www.sec.gov/CIK 0001328571", "http://www.sec.gov/CIK 0001288359", "http://www.sec.gov/CIK 0001372041", "http://www.sec.gov/CIK 0000090721", "http://www.sec.gov/CIK 0001558294", "http://www.sec.gov/CIK 0001405660", "http://www.sec.gov/CIK 0001458704", "http://www.sec.gov/CIK 0001143238", "http://www.sec.gov/CIK 0001037949", "http://www.sec.gov/CIK 0000068622", "http://www.sec.gov/CIK 0001341319", "http://www.sec.gov/CIK 0000354963", "http://www.sec.gov/CIK 0000101830", "http://www.sec.gov/CIK 0000943117", "http://www.sec.gov/CIK 0001560158", "http://www.sec.gov/CIK 0001051512", "http://www.sec.gov/CIK 0001101688", "http://www.sec.gov/CIK 0001499355", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001270400", "http://www.sec.gov/CIK 0001322791", "http://www.sec.gov/CIK 0001353505", "http://www.sec.gov/CIK 0001272830", "http://www.sec.gov/CIK 0001562636", "http://www.sec.gov/CIK 0001282266", "http://www.sec.gov/CIK 0000919742", "http://www.sec.gov/CIK 0001111634", "http://www.sec.gov/CIK 0001448962", "http://www.sec.gov/CIK 0001502756", "http://www.sec.gov/CIK 0001373444", "http://www.sec.gov/CIK 0001057758" ],
      "sic-dow30": [ "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000732712" ],
      "mixed" : [ "http://www.sec.gov/CIK 0001585644", "http://www.sec.gov/CIK 0001608249", "http://www.sec.gov/CIK 0001023731", "http://www.sec.gov/CIK 0001089511", "http://www.sec.gov/CIK 0000104777", "http://www.sec.gov/CIK 0001047919", "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000879585", "http://www.sec.gov/CIK 0001122063", "http://www.sec.gov/CIK 0001104358", "http://www.sec.gov/CIK 0001205727", "http://www.sec.gov/CIK 0000018926", "http://www.sec.gov/CIK 0000716133", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0001161706", "http://www.sec.gov/CIK 0001457737", "http://www.sec.gov/CIK 0001304421", "http://www.sec.gov/CIK 0001086740", "http://www.sec.gov/CIK 0001352819", "http://www.sec.gov/CIK 0001084384", "http://www.sec.gov/CIK 0001101239", "http://www.sec.gov/CIK 0000766561", "http://www.sec.gov/CIK 0001062613", "http://www.sec.gov/CIK 0001504678", "http://www.sec.gov/CIK 0000020520", "http://www.sec.gov/CIK 0001071411", "http://www.sec.gov/CIK 0000075679", "http://www.sec.gov/CIK 0000808461", "http://www.sec.gov/CIK 0001061322", "http://www.sec.gov/CIK 0000746210", "http://www.sec.gov/CIK 0001384929", "http://www.sec.gov/CIK 0001315255", "http://www.sec.gov/CIK 0001006837", "http://www.sec.gov/CIK 0001005731", "http://www.sec.gov/CIK 0001041954", "http://www.sec.gov/CIK 0001292653", "http://www.sec.gov/CIK 0001160142", "http://www.sec.gov/CIK 0001084752", "http://www.sec.gov/CIK 0000794323", "http://www.sec.gov/CIK 0001130888", "http://www.sec.gov/CIK 0001520744", "http://www.sec.gov/CIK 0001005699", "http://www.sec.gov/CIK 0000732412", "http://www.sec.gov/CIK 0000071557", "http://www.sec.gov/CIK 0001328571", "http://www.sec.gov/CIK 0001288359", "http://www.sec.gov/CIK 0001372041", "http://www.sec.gov/CIK 0000090721", "http://www.sec.gov/CIK 0001558294", "http://www.sec.gov/CIK 0001405660", "http://www.sec.gov/CIK 0001458704", "http://www.sec.gov/CIK 0001143238", "http://www.sec.gov/CIK 0001037949", "http://www.sec.gov/CIK 0000068622", "http://www.sec.gov/CIK 0001341319", "http://www.sec.gov/CIK 0000354963", "http://www.sec.gov/CIK 0000101830", "http://www.sec.gov/CIK 0000943117", "http://www.sec.gov/CIK 0001560158", "http://www.sec.gov/CIK 0001051512", "http://www.sec.gov/CIK 0001101688", "http://www.sec.gov/CIK 0001499355", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0001270400", "http://www.sec.gov/CIK 0001322791", "http://www.sec.gov/CIK 0001353505", "http://www.sec.gov/CIK 0001272830", "http://www.sec.gov/CIK 0001562636", "http://www.sec.gov/CIK 0000104169", "http://www.sec.gov/CIK 0001282266", "http://www.sec.gov/CIK 0000919742", "http://www.sec.gov/CIK 0001111634", "http://www.sec.gov/CIK 0001448962", "http://www.sec.gov/CIK 0001502756", "http://www.sec.gov/CIK 0001373444", "http://www.sec.gov/CIK 0001057758" ],
      "mixed-dow30": [ "http://www.sec.gov/CIK 0000004962", "http://www.sec.gov/CIK 0000732717", "http://www.sec.gov/CIK 0000021344", "http://www.sec.gov/CIK 0000732712", "http://www.sec.gov/CIK 0000104169" ]
    };

declare %an:nondeterministic function local:test-example1() as item
{
  let $expected :=
  [ {
    "_id" : "http://www.sec.gov/CIK 0000021344",
    "Archives" : "http://" || request:server-name() || ":" || request:server-port() ||
      "/v1/_queries/public/api/filings.jq?_method=POST&token=" || $config:test-token || "&eid=http%3A%2F%2Fwww.sec.gov%2FCIK%200000021344&format=&profile-name=sec&fiscalYear=ALL&fiscalPeriod=ALL",
    "Profiles" : {
      "SEC" : {
        "Name" : "SEC",
        "CompanyName" : "COCA COLA CO",
        "CompanyType" : "Corporation",
        "CIK" : "0000021344",
        "SIC" : "2080",
        "SICDescription" : "BEVERAGES",
        "SICGroup" : 9,
        "Taxonomy" : "ci",
        "Sector" : "Food/Kindred Products",
        "Tickers" : [ "ko" ],
        "Tags" : [ "FORTUNE100", "DOW30", "RUSSELL1000", "SP500" ],
        "IsTrust" : false
      }
    }
  } ]
  let $endpoint := "entities"
  let $params := {cik:"21344"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].Entities
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-entities(
    $expected as array,
    $params as object) as item
{
    let $endpoint := "entities"
    let $request := test:invoke($endpoint, $params)
    let $actual as array := [ $request[2].Entities[]._id ]
    let $status as integer := $request[1]
    return test:assert-eq-array($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-entities-generic(
    $expected as array,
    $params as object) as item
{
    let $endpoint := "entities"
    let $request := test:invoke($endpoint, $params)
    let $actual as array := [ $request[2].Entities[].EID ]
    let $status as integer := $request[1]
    return test:assert-eq-array($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

let $dow30 := test:is-dow30()
return local:check({
    dow30: local:test-entities($local:expected.dow30, {tag:"DOW30"}),
    generic: local:test-entities-generic($local:expected.generic, {eid:"http://www.sec.gov/CIK 0000004962", profile-name:"generic"}),
    cik: local:test-entities($local:expected.cik, {cik:"4962"}),
    ticker: local:test-entities($local:expected.ticker, {ticker:"wmt"}),
    ticker2: local:test-entities($local:expected.ticker2, {ticker:["wmt","ko"]}),
    sic: local:test-entities(if($dow30) then $local:expected.sic-dow30 else $local:expected.sic, {sic:"4813"}),
    mixed: local:test-entities(if($dow30) then $local:expected.mixed-dow30 else $local:expected.mixed, {cik:"4962", sic:"4813", ticker:[ "wmt", "ko" ]}),
    example1: local:test-example1()
})


stabilize test with empty body

stabilize test with empty body

import module namespace response = "http://www.28msec.com/modules/http-response";
import module namespace test = "http://apps.28.io/test";

declare %an:nondeterministic function local:test-facttable($expected as integer, $params as object) as item
{
    let $endpoint := "facts"
    let $request := test:invoke($endpoint, $params)
    let $actual as integer := count($request[2].FactTable[])
    let $status as integer := $request[1]
    return test:assert-eq($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-empty($params as object) as item
{
    let $endpoint := "facts"
    let $res as object := test:invoke-raw($endpoint, $params)
    return if($res.status eq 200 and ($res.headers."Content-Length" eq "0" or empty($res.body.content))) then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res
    }
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

declare %an:nondeterministic function local:test-labels() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: [ "fac:Assets", "us-gaap:CashAndCashEquivalentsAtCarryingValue" ],
        report: "FundamentalAccountingConcepts",
        format: "csv",
        ticker: "ko",
        fiscalYear: 2013,
        fiscalPeriod: "Q3",
        labels: true
    }
    let $res as object := test:invoke-raw($endpoint, $params)
    let $actual := $res.body.content
    let $expectedLines := (
        "Accession Number,Concept,Entity,Period,Fiscal Period,Fiscal Period Type,Fiscal Year,Accepted,Legal Entity,Unit,Value,Decimals",
        "0000021344-13-000050,\"Cash and Cash Equivalents, at Carrying Value\",COCA COLA CO,2013-09-27,Q3,instant,2013,20131024121047,Default Legal Entity,USD,11118000000,-6",
        "0000021344-13-000050,Assets,COCA COLA CO,2013-09-27,Q3,instant,2013,20131024121047,Default Legal Entity,USD,89432000000,-6"
    )
    return if($res.status eq 200 and (every $line in $expectedLines satisfies contains($actual,$line))) then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res
    }
};

declare %an:nondeterministic function local:test-labels-aids() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: "disc:AdvertisingCostsPolicyTextBlock",
        map: "Disclosures",
        format: "json",
        fiscalYear: 2014,
        fiscalPeriod: "FY",
        labels: true,
        aid: "0000858877-14-000029"
    }
    let $res := test:invoke($endpoint, $params)
    let $actual := [
            for $labels in $res[2].FactTable[].Labels
            return (keys($labels) ! $labels.$$)
        ]
    let $expected := [ "Advertising Costs, Policy", "Default Legal Entity", "Accession Number", "Concept", "Entity", "CISCO SYSTEMS, INC.", "Period", "Fiscal Period", "Fiscal Period Type", "Fiscal Year", "Accepted", "Unit", "Legal Entity" ]
    let $status as integer := $res[1]
    return test:assert-eq-array($expected, $actual, $status, test:url($endpoint, $params))
};

local:check({
    cocacola: local:test-facttable(468, {
        ticker:"ko"
    }),
    cocacola-all: local:test-facttable(468, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "instant", "YTD", "QTD" ]
    }),
    cocacola-instant: local:test-facttable(163, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "instant" ]
    }),
    cocacola-ytd: local:test-facttable(305, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "YTD" ]
    }),
    cocacola-qtd: local:test-facttable(90, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "Q2" ],
        fiscalPeriodType: [ "QTD" ]
    }),
    cocacolaCSVLabels: local:test-labels(),
    ciscoLabelsByAid: local:test-labels-aids(),
    tickerconcept: local:test-facttable(1, {
        ticker:"ko",
        concept:"us-gaap:Assets"
    }),
    tickerfyfprole: local:test-facttable(1, {
        ticker:"ko",
        fiscalYear:"2012",
        fiscalPeriod:"Q1",
        concept:"us-gaap:Assets"
    }),
    tagconcept: local:test-facttable(30, {
        tag:"DOW30",
        concept:"us-gaap:Assets"
    }),
    tagfyfprole: local:test-facttable(30, {
        tag:"DOW30",
        fiscalYear:"2012",
        fiscalPeriod:"Q1",
        concept:"us-gaap:Assets"
    }),
    testNoEntity4Sic: local:test-empty({
        concept:"fac:Assets",
        map:"FundamentalAccountingConcepts",
        format:"csv",
        sic:"5052",
        fiscalYear:"2010",
        fiscalPeriod:"Q3"
    }),
    quartersfact: local:test-facttable(0, { (: this fact is not reported in the raw XML filing :)
        aid: "0000051143-13-000007",
        concept: "disc:AssetRetirementObligationsPolicy",
        fiscalPeriod: "Q3",
        fiscalYear: "2013",
        map: "Disclosures"
    }),
    quartersfact2: local:test-facttable(1, {
        aid: "0001193125-12-207154",
        concept: "disc:CashFlowOperatingCapitalTableTextBlock",
        fiscalPeriod: "Q1",
        fiscalYear: "2012",
        map: "Disclosures"
    }),
    generic: local:test-facttable(2, {
        "xbrl:Entity":"http://www.sec.gov/CIK%200000021344",
        "sec:Accepted":"20140227132423",
        concept:"us-gaap:Assets",
        profile-name: "generic"
    })
})

import module namespace response = "http://www.28msec.com/modules/http-response";
import module namespace test = "http://apps.28.io/test";

declare %an:nondeterministic function local:test-facttable($expected as integer, $params as object) as item
{
    let $endpoint := "facts"
    let $request := test:invoke($endpoint, $params)
    let $actual as integer := count($request[2].FactTable[])
    let $status as integer := $request[1]
    return test:assert-eq($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-empty($params as object) as item
{
    let $endpoint := "facts"
    let $res as object := test:invoke-raw($endpoint, $params)
    return if($res.status eq 200 and $res.headers."Content-Length" eq "0") then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res
    }
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

declare %an:nondeterministic function local:test-labels() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: [ "fac:Assets", "us-gaap:CashAndCashEquivalentsAtCarryingValue" ],
        report: "FundamentalAccountingConcepts",
        format: "csv",
        ticker: "ko",
        fiscalYear: 2013,
        fiscalPeriod: "Q3",
        labels: true
    }
    let $res as object := test:invoke-raw($endpoint, $params)
    let $actual := $res.body.content
    let $expectedLines := (
        "Accession Number,Concept,Entity,Period,Fiscal Period,Fiscal Period Type,Fiscal Year,Accepted,Legal Entity,Unit,Value,Decimals",
        "0000021344-13-000050,\"Cash and Cash Equivalents, at Carrying Value\",COCA COLA CO,2013-09-27,Q3,instant,2013,20131024121047,Default Legal Entity,USD,11118000000,-6",
        "0000021344-13-000050,Assets,COCA COLA CO,2013-09-27,Q3,instant,2013,20131024121047,Default Legal Entity,USD,89432000000,-6"
    )
    return if($res.status eq 200 and (every $line in $expectedLines satisfies contains($actual,$line))) then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res
    }
};

declare %an:nondeterministic function local:test-labels-aids() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: "disc:AdvertisingCostsPolicyTextBlock",
        map: "Disclosures",
        format: "json",
        fiscalYear: 2014,
        fiscalPeriod: "FY",
        labels: true,
        aid: "0000858877-14-000029"
    }
    let $res := test:invoke($endpoint, $params)
    let $actual := [
            for $labels in $res[2].FactTable[].Labels
            return (keys($labels) ! $labels.$$)
        ]
    let $expected := [ "Advertising Costs, Policy", "Default Legal Entity", "Accession Number", "Concept", "Entity", "CISCO SYSTEMS, INC.", "Period", "Fiscal Period", "Fiscal Period Type", "Fiscal Year", "Accepted", "Unit", "Legal Entity" ]
    let $status as integer := $res[1]
    return test:assert-eq-array($expected, $actual, $status, test:url($endpoint, $params))
};

local:check({
    cocacola: local:test-facttable(468, {
        ticker:"ko"
    }),
    cocacola-all: local:test-facttable(468, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "instant", "YTD", "QTD" ]
    }),
    cocacola-instant: local:test-facttable(163, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "instant" ]
    }),
    cocacola-ytd: local:test-facttable(305, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "FY" ],
        fiscalPeriodType: [ "YTD" ]
    }),
    cocacola-qtd: local:test-facttable(90, {
        ticker:"ko",
        fiscalYear: 2013,
        fiscalPeriod: [ "Q2" ],
        fiscalPeriodType: [ "QTD" ]
    }),
    cocacolaCSVLabels: local:test-labels(),
    ciscoLabelsByAid: local:test-labels-aids(),
    tickerconcept: local:test-facttable(1, {
        ticker:"ko",
        concept:"us-gaap:Assets"
    }),
    tickerfyfprole: local:test-facttable(1, {
        ticker:"ko",
        fiscalYear:"2012",
        fiscalPeriod:"Q1",
        concept:"us-gaap:Assets"
    }),
    tagconcept: local:test-facttable(30, {
        tag:"DOW30",
        concept:"us-gaap:Assets"
    }),
    tagfyfprole: local:test-facttable(30, {
        tag:"DOW30",
        fiscalYear:"2012",
        fiscalPeriod:"Q1",
        concept:"us-gaap:Assets"
    }),
    testNoEntity4Sic: local:test-empty({
        concept:"fac:Assets",
        map:"FundamentalAccountingConcepts",
        format:"csv",
        sic:"5052",
        fiscalYear:"2010",
        fiscalPeriod:"Q3"
    }),
    quartersfact: local:test-facttable(0, { (: this fact is not reported in the raw XML filing :)
        aid: "0000051143-13-000007",
        concept: "disc:AssetRetirementObligationsPolicy",
        fiscalPeriod: "Q3",
        fiscalYear: "2013",
        map: "Disclosures"
    }),
    quartersfact2: local:test-facttable(1, {
        aid: "0001193125-12-207154",
        concept: "disc:CashFlowOperatingCapitalTableTextBlock",
        fiscalPeriod: "Q1",
        fiscalYear: "2012",
        map: "Disclosures"
    }),
    generic: local:test-facttable(2, {
        "xbrl:Entity":"http://www.sec.gov/CIK%200000021344",
        "sec:Accepted":"20140227132423",
        concept:"us-gaap:Assets",
        profile-name: "generic"
    })
})


Addressed review comment

Addressed review comment

jsoniq version "1.0";
module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";

import module namespace mw-sec = "http://28.io/modules/xbrl/profiles/sec/mongo-wrapper";
import module namespace mw-japan = "http://28.io/modules/xbrl/profiles/japan/mongo-wrapper";
import module namespace config = "http://apps.28.io/config";
import module namespace mongo = "http://www.28msec.com/modules/mongodb";
import module namespace credentials = "http://www.28msec.com/modules/credentials";

declare %an:strictlydeterministic function mw:connection() as anyURI
{
  let $credentials :=
      let $credentials := credentials:credentials("MongoDB", "xbrl")
      return if (empty($credentials))
             then error(QName("mw:CONNECTION-FAILED"), "no xbrl MongoDB configured")
             else $credentials
  return
    try {
      mongo:connect($credentials)
    } catch mongo:* {
      error(QName("mw:CONNECTION-FAILED"), $err:description)
    }
};

declare function mw:find($collection as string, $query as object) as object()*
{
  let $conn := mw:connection()
  return mongo:find($conn, $collection, mw:hint($collection, $query))
};

declare function mw:find($collection as string, $query as object, $projection as object) as object()*
{
  let $conn := mw:connection()
  return mongo:find($conn, $collection, mw:hint($collection, $query), $projection, {})
};

declare function mw:run-cmd-deterministic($command as object) as object*
{
  let $conn := mw:connection()
  return mongo:run-cmd-deterministic($conn, $command)
};

declare %private function mw:hint($collection as string, $query as object) as object
{
  switch(lower-case($config:profile-name))
    case "sec"
      return mw-sec:hint($collection, $query)
    case "japan"
      return mw-japan:hint($collection, $query)
    default
      return $query
};

(:
  Heuristics detection of whether a condition in the query is selective and should be
  used to decide the index to use
:)
declare %private function mw:is-selective($query as object, $field as string) as boolean
{
    exists($query($field)) and
      (
        not($query($field) instance of object) or (: Equality checks are of type atomic - not object - other kinds are disallowed :)
        exists($query($field)("$in")) (: $in operator :)
      )
};

jsoniq version "1.0";
module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";

import module namespace mw-sec = "http://28.io/modules/xbrl/profiles/sec/mongo-wrapper";
import module namespace mw-japan = "http://28.io/modules/xbrl/profiles/japan/mongo-wrapper";
import module namespace config = "http://apps.28.io/config";
import module namespace mongo = "http://www.28msec.com/modules/mongodb";
import module namespace credentials = "http://www.28msec.com/modules/credentials";

declare %an:strictlydeterministic function mw:connection() as anyURI
{
  let $credentials :=
      let $credentials := credentials:credentials("MongoDB", "xbrl")
      return if (empty($credentials))
             then error(QName("mw:CONNECTION-FAILED"), "no xbrl MongoDB configured")
             else $credentials
  return
    try {
      mongo:connect($credentials)
    } catch mongo:* {
      error(QName("mw:CONNECTION-FAILED"), $err:description)
    }
};

declare function mw:find($collection as string, $query as object) as object()*
{
  let $conn := mw:connection()
  return mongo:find($conn, $collection, mw:hint($collection, $query))
};

declare function mw:find($collection as string, $query as object, $projection as object) as object()*
{
  let $conn := mw:connection()
  return mongo:find($conn, $collection, mw:hint( $collection, $query), $projection, {})
};

declare function mw:run-cmd-deterministic($command as object) as object*
{
  let $conn := mw:connection()
  return mongo:run-cmd-deterministic($conn, $command)
};

declare %private function mw:hint($collection as string, $query as object) as object
{
  switch(lower-case($config:profile-name))
    case "sec"
      return mw-sec:hint($collection, $query)
    case "japan"
      return mw-japan:hint($collection, $query)
    default
      return $query
};

(:
  Heuristics detection of whether a condition in the query is selective and should be
  used to decide the index to use
:)
declare %private function mw:is-selective($query as object, $field as string) as boolean
{
    exists($query($field)) and
      (
        not($query($field) instance of object) or (: Equality checks are of type atomic - not object - other kinds are disallowed :)
        exists($query($field)("$in")) (: $in operator :)
      )
};


:green_heart: Fix facttable test.

:green_heart: Fix facttable test.

sec:Accepted xbrl:Period xbrl:Entity xbrl:Concept xbrl:Unit

fac:Assets[90,055,000,000 USD] = fac:LiabilitiesAndEquity[90,055,000,000 USD]

[BS4] Liabilities = CurrentLiabilities + NoncurrentLiabilities

fac:Liabilities[56,615,000,000 USD] = fac:CurrentLiabilities[27,811,000,000 USD] + fac:NoncurrentLiabilities[28,804,000,000 USD]

[BS1] Equity = EquityAttributableToParent + EquityAttributableToNoncontrollingInterest

fac:Equity[33,440,000,000 USD] = fac:EquityAttributableToParent[33,173,000,000 USD] + fac:EquityAttributableToNoncontrollingInterest[267,000,000 USD]

[BS3] Assets = CurrentAssets + NoncurrentAssets

fac:Assets[90,055,000,000 USD] = fac:CurrentAssets[31,304,000,000 USD] + fac:NoncurrentAssets[58,751,000,000 USD]

[BS5] LiabilitiesAndEquity = Liabilities + CommitmentsAndContingencies + TemporaryEquity + Equity

fac:LiabilitiesAndEquity[90,055,000,000 USD] = fac:Liabilities[56,615,000,000 USD] + CommitmentsAndContingencies[0] + TemporaryEquity[0] + fac:Equity[33,440,000,000 USD]

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:Assets -> us-gaap:Assets

fac:Equity -> us-gaap:StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest

fac:CurrentLiabilities -> us-gaap:LiabilitiesCurrent

fac:LiabilitiesAndEquity -> us-gaap:LiabilitiesAndStockholdersEquity

fac:TemporaryEquity = 0

fac:NoncurrentLiabilities[28,804,000,000 USD] = fac:Liabilities[56,615,000,000 USD] - fac:CurrentLiabilities[27,811,000,000 USD]

fac:CurrentAssets -> us-gaap:AssetsCurrent

fac:NoncurrentAssets[58,751,000,000 USD] = fac:Assets[90,055,000,000 USD] - fac:CurrentAssets[31,304,000,000 USD]

fac:Liabilities[56,615,000,000 USD] = fac:LiabilitiesAndEquity[90,055,000,000 USD] -  ( CommitmentsAndContingencies[0] + TemporaryEquity[0] + fac:Equity[33,440,000,000 USD] )

fac:EquityAttributableToNoncontrollingInterest -> us-gaap:MinorityInterest

fac:EquityAttributableToParent -> us-gaap:StockholdersEquity

fac:CommitmentsAndContingencies = 0

fac:RedeemableNoncontrollingInterest = 0

sec:Accepted xbrl:Period xbrl:Entity xbrl:Concept

fac:TradingSymbol['ko'] = entity(http://www.sec.gov/CIK 0000021344).Profiles.SEC.Tickers

fac:IncomeStatementFormat[Multi-step] = Multi-step (because fac:GrossProfit[28,433,000,000 USD], fac:CostOfRevenue[18,421,000,000 USD])

[IS3] IncomeLossBeforeEquityMethodInvestments = OperatingIncomeLoss + NonoperatingIncomeLossPlusInterestAndDebtExpense

fac:IncomeLossBeforeEquityMethodInvestments[10,875,000,000 USD] = fac:OperatingIncomeLoss[10,228,000,000 USD] + fac:NonoperatingIncomeLossPlusInterestAndDebtExpense[647,000,000 USD]

[IS4] IncomeLossFromContinuingOperationsBeforeTax = IncomeLossBeforeEquityMethodInvestments + IncomeLossFromEquityMethodInvestments

fac:IncomeLossFromContinuingOperationsBeforeTax[11,477,000,000 USD] = fac:IncomeLossBeforeEquityMethodInvestments[10,875,000,000 USD] + fac:IncomeLossFromEquityMethodInvestments[602,000,000 USD]

[IS5] IncomeLossFromContinuingOperationsAfterTax = IncomeLossFromContinuingOperationsBeforeTax - IncomeTaxExpenseBenefit

fac:IncomeLossFromContinuingOperationsAfterTax[8,626,000,000 USD] = fac:IncomeLossFromContinuingOperationsBeforeTax[11,477,000,000 USD] - fac:IncomeTaxExpenseBenefit[2,851,000,000 USD]

[IS7] NetIncomeLoss = NetIncomeLossAttributableToParent + NetIncomeLossAttributableToNoncontrollingInterest

fac:NetIncomeLoss[8,626,000,000 USD] = fac:NetIncomeLossAttributableToParent[8,584,000,000 USD] + fac:NetIncomeLossAttributableToNoncontrollingInterest[42,000,000 USD]

[IS8] NetIncomeLossAvailableToCommonStockholdersBasic = NetIncomeLossAttributableToParent - PreferredStockDividendsAndOtherAdjustments

fac:NetIncomeLossAvailableToCommonStockholdersBasic[8,584,000,000 USD] = fac:NetIncomeLossAttributableToParent[8,584,000,000 USD] - fac:PreferredStockDividendsAndOtherAdjustments[0 USD]

[IS9] ComprehensiveIncomeLoss = ComprehensiveIncomeLossAttributableToParent + ComprehensiveIncomeLossAttributableToNoncontrollingInterest

fac:ComprehensiveIncomeLoss[8,576,000,000 USD] = fac:ComprehensiveIncomeLossAttributableToParent[8,537,000,000 USD] + fac:ComprehensiveIncomeLossAttributableToNoncontrollingInterest[39,000,000 USD]

[CF6] NetCashFlowFromFinancingActivities = NetCashFlowFromFinancingActivitiesContinuing + NetCashFlowFromFinancingActivitiesDiscontinued

fac:NetCashFlowFromFinancingActivities[-3,745,000,000 USD] = fac:NetCashFlowFromFinancingActivitiesContinuing[-3,745,000,000 USD] + fac:NetCashFlowFromFinancingActivitiesDiscontinued[0 USD]

[CF5] NetCashFlowFromInvestingActivities = NetCashFlowFromInvestingActivitiesContinuing + NetCashFlowFromInvestingActivitiesDiscontinued

fac:NetCashFlowFromInvestingActivities[-4,214,000,000 USD] = fac:NetCashFlowFromInvestingActivitiesContinuing[-4,214,000,000 USD] + NetCashFlowFromInvestingActivitiesDiscontinued[0]

[CF4] NetCashFlowFromOperatingActivities = NetCashFlowFromOperatingActivitiesContinuing + NetCashFlowFromOperatingActivitiesDiscontinued

fac:NetCashFlowFromOperatingActivities[10,542,000,000 USD] = fac:NetCashFlowFromOperatingActivitiesContinuing[10,542,000,000 USD] + fac:NetCashFlowFromOperatingActivitiesDiscontinued[0 USD]

[IS10] ComprehensiveIncomeLoss = NetIncomeLoss + OtherComprehensiveIncomeLoss

fac:ComprehensiveIncomeLoss[8,576,000,000 USD] = fac:NetIncomeLoss[8,626,000,000 USD] + fac:OtherComprehensiveIncomeLoss[-50,000,000 USD]

[IS1] GrossProfit = Revenues - CostOfRevenue

fac:GrossProfit[28,433,000,000 USD] = fac:Revenues[46,854,000,000 USD] - fac:CostOfRevenue[18,421,000,000 USD]

[IS2] OperatingIncomeLoss = GrossProfit - OperatingExpenses + OtherOperatingIncomeExpenses

fac:OperatingIncomeLoss[10,228,000,000 USD] = fac:GrossProfit[28,433,000,000 USD] - OperatingExpenses[0] + OtherOperatingIncomeExpenses[0]

[CF3] NetCashFlowDiscontinued = NetCashFlowFromOperatingActivitiesDiscontinued + NetCashFlowFromInvestingActivitiesDiscontinued + NetCashFlowFromFinancingActivitiesDiscontinued

fac:NetCashFlowDiscontinued[0 USD] = fac:NetCashFlowFromOperatingActivitiesDiscontinued[0 USD] + NetCashFlowFromInvestingActivitiesDiscontinued[0] + fac:NetCashFlowFromFinancingActivitiesDiscontinued[0 USD]

[IS6] NetIncomeLoss = IncomeLossFromContinuingOperationsAfterTax + IncomeLossFromDiscontinuedOperationsNetOfTax + ExtraordinaryItemsOfIncomeExpenseNetOfTax

fac:NetIncomeLoss[8,626,000,000 USD] = fac:IncomeLossFromContinuingOperationsAfterTax[8,626,000,000 USD] + IncomeLossFromDiscontinuedOperationsNetOfTax[0] + ExtraordinaryItemsOfIncomeExpenseNetOfTax[0]

[IS11] OperatingIncomeLoss = Revenues - CostsAndExpenses + OtherOperatingIncomeExpenses

fac:OperatingIncomeLoss[10,228,000,000 USD] = fac:Revenues[46,854,000,000 USD] - CostsAndExpenses[0] + OtherOperatingIncomeExpenses[0]

[CF2] NetCashFlowContinuing = NetCashFlowFromOperatingActivitiesContinuing + NetCashFlowFromInvestingActivitiesContinuing + NetCashFlowFromFinancingActivitiesContinuing

fac:NetCashFlowContinuing[2,583,000,000 USD] = fac:NetCashFlowFromOperatingActivitiesContinuing[10,542,000,000 USD] + fac:NetCashFlowFromInvestingActivitiesContinuing[-4,214,000,000 USD] + fac:NetCashFlowFromFinancingActivitiesContinuing[-3,745,000,000 USD]

[CF1] NetCashFlow = NetCashFlowFromOperatingActivities + NetCashFlowFromInvestingActivities + NetCashFlowFromFinancingActivities [+ ExchangeGainsLosses]

fac:NetCashFlow[1,972,000,000 USD] = fac:NetCashFlowFromOperatingActivities[10,542,000,000 USD] + fac:NetCashFlowFromInvestingActivities[-4,214,000,000 USD] + fac:NetCashFlowFromFinancingActivities[-3,745,000,000 USD] + fac:ExchangeGainsLosses[-611,000,000 USD]

fac:BalanceSheetFormat[Classified] = Classified (because fac:CurrentAssets[31,304,000,000 USD], fac:NoncurrentAssets[58,751,000,000 USD], fac:NoncurrentLiabilities[28,804,000,000 USD], fac:CurrentLiabilities[27,811,000,000 USD])

Income Statement Start Period imputation

fac:IncomeStatementStartPeriodYearToDate[2013-01-01] = facts:duration-for-fact(fac:Revenues[46,854,000,000 USD]).Start

xbrl:Unit.Default = "xbrl28:NoUnit"

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:EntityRegistrantName -> dei:EntityRegistrantName

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:EntityCentralIndexKey -> dei:EntityCentralIndexKey

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:EntityFilerCategory -> dei:EntityFilerCategory

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalYearEnd -> dei:CurrentFiscalYearEndDate

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalPeriod -> dei:DocumentFiscalPeriodFocus

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalYear -> dei:DocumentFiscalYearFocus

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:BalanceSheetDate -> dei:DocumentPeriodEndDate

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:DocumentType -> dei:DocumentType

fac:NetIncomeLoss -> us-gaap:ProfitLoss

fac:Revenues -> us-gaap:SalesRevenueGoodsNet

fac:OperatingIncomeLoss -> us-gaap:OperatingIncomeLoss

fac:GrossProfit -> us-gaap:GrossProfit

fac:CostOfRevenue -> us-gaap:CostOfGoodsSold

Net Cash Flow from Investing Activities, Continuing

fac:NetCashFlowFromInvestingActivitiesContinuing[-4,214,000,000 USD] = fac:NetCashFlowFromInvestingActivities[-4,214,000,000 USD] - NetCashFlowFromInvestingActivitiesDiscontinued[0]

Income (Loss) Before Equity Method Investments

fac:IncomeLossBeforeEquityMethodInvestments[10,875,000,000 USD] = fac:IncomeLossFromContinuingOperationsBeforeTax[11,477,000,000 USD] - fac:IncomeLossFromEquityMethodInvestments[602,000,000 USD]

fac:NetCashFlowFromInvestingActivities -> us-gaap:NetCashProvidedByUsedInInvestingActivities

fac:NetCashFlowFromFinancingActivities -> us-gaap:NetCashProvidedByUsedInFinancingActivities

fac:NetCashFlowFromInvestingActivitiesDiscontinued = 0

fac:OperatingExpenses = 0

fac:NetCashFlowFromOperatingActivities -> us-gaap:NetCashProvidedByUsedInOperatingActivities

Net Cash Flow from Operating Activities, Discontinued

fac:NetCashFlowFromOperatingActivitiesDiscontinued[0 USD] = 0

Net Cash Flow from Operating Activities, Continuing

fac:NetCashFlowFromOperatingActivitiesContinuing[10,542,000,000 USD] = fac:NetCashFlowFromOperatingActivities[10,542,000,000 USD] - NetCashFlowFromOperatingActivitiesDiscontinued[0]

Net Cash Flow from Financing Activities, Discontinued

fac:NetCashFlowFromFinancingActivitiesDiscontinued[0 USD] = 0

fac:OtherOperatingIncomeExpenses = 0

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:IncomeLossFromEquityMethodInvestments -> us-gaap:IncomeLossFromEquityMethodInvestments

fac:IncomeLossFromContinuingOperationsBeforeTax -> us-gaap:IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest

fac:NetIncomeLossAttributableToParent -> us-gaap:NetIncomeLoss

Net Cash Flow from Financing Activities, Continuing

fac:NetCashFlowFromFinancingActivitiesContinuing[-3,745,000,000 USD] = fac:NetCashFlowFromFinancingActivities[-3,745,000,000 USD] - fac:NetCashFlowFromFinancingActivitiesDiscontinued[0 USD]

fac:ComprehensiveIncomeLoss -> us-gaap:ComprehensiveIncomeNetOfTaxIncludingPortionAttributableToNoncontrollingInterest

fac:CostsAndExpenses = 0

fac:NonoperatingIncomeLoss = 0

fac:InterestAndDebtExpense = 0

fac:ComprehensiveIncomeLossAttributableToNoncontrollingInterest -> us-gaap:ComprehensiveIncomeNetOfTaxAttributableToNoncontrollingInterest

Net Income (Loss) Available to Common Stockholders, Basic

fac:NetIncomeLossAvailableToCommonStockholdersBasic[8,584,000,000 USD] = fac:NetIncomeLossAttributableToParent[8,584,000,000 USD]

fac:OtherComprehensiveIncomeLoss[-50,000,000 USD] = fac:ComprehensiveIncomeLoss[8,576,000,000 USD] - fac:NetIncomeLoss[8,626,000,000 USD]

Income (Loss) from Continuing Operations After Tax

fac:IncomeLossFromContinuingOperationsAfterTax[8,626,000,000 USD] = fac:NetIncomeLoss[8,626,000,000 USD] - IncomeLossFromDiscontinuedOperationsNetOfTax[0] - ExtraordinaryItemsOfIncomeExpenseNetOfTax[0]

fac:ComprehensiveIncomeLossAttributableToParent -> us-gaap:ComprehensiveIncomeNetOfTax

fac:ExtraordinaryItemsOfIncomeExpenseNetOfTax = 0

fac:ExchangeGainsLosses -> us-gaap:EffectOfExchangeRateOnCashAndCashEquivalents

fac:NetIncomeLossAttributableToNoncontrollingInterest -> us-gaap:NetIncomeLossAttributableToNoncontrollingInterest

fac:IncomeLossFromDiscontinuedOperationsNetOfTax = 0

Preferred Stock Dividends and Other Adjustments

fac:PreferredStockDividendsAndOtherAdjustments[0 USD] = fac:NetIncomeLossAttributableToParent[8,584,000,000 USD] - fac:NetIncomeLossAvailableToCommonStockholdersBasic[8,584,000,000 USD]

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:NetCashFlow -> us-gaap:CashAndCashEquivalentsPeriodIncreaseDecrease

Nonoperating Income (Loss) + Interest and Debt Expense

fac:NonoperatingIncomeLossPlusInterestAndDebtExpense[647,000,000 USD] = fac:NonoperatingIncomePlusInterestAndDebtExpensePlusIncomeFromEquityMethodInvestments[1,249,000,000 USD] - fac:IncomeLossFromEquityMethodInvestments[602,000,000 USD]

Nonoperating Income (Loss) + Interest and Debt Expense + Income (Loss) from Equity Method Investments

fac:NonoperatingIncomePlusInterestAndDebtExpensePlusIncomeFromEquityMethodInvestments[1,249,000,000 USD] = fac:IncomeLossFromContinuingOperationsBeforeTax[11,477,000,000 USD] - fac:OperatingIncomeLoss[10,228,000,000 USD]

fac:IncomeTaxExpenseBenefit -> us-gaap:IncomeTaxExpenseBenefit

fac:ReturnOnEquity[0.26 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Equity[33,440,000,000 USD]

fac:ReturnOnAssets[0.1 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Assets[90,055,000,000 USD]

fac:ReturnOnSales[0.18 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Revenues[46,854,000,000 USD]

fac:SustainableGrowthRate[0.35 USD] =  (  ( fac:NetIncomeLoss[8,626,000,000 USD] div fac:Revenues[46,854,000,000 USD] ) *  ( 1 +  ( fac:Assets[90,055,000,000 USD] - fac:Equity[33,440,000,000 USD] ) div fac:Equity[33,440,000,000 USD] ) ) div  (  ( 1 div  ( fac:Revenues[46,854,000,000 USD] div fac:Assets[90,055,000,000 USD] ) ) -  (  ( fac:NetIncomeLoss[8,626,000,000 USD] div fac:Revenues[46,854,000,000 USD] ) *  ( 1 +  ( fac:Assets[90,055,000,000 USD] - fac:Equity[33,440,000,000 USD] ) div fac:Equity[33,440,000,000 USD] ) ) )

fac:ResearchAndDevelopment = 0

Generated by 28.io, for more information see http://www.28.io/xbrl (2015-02-13T16:03:58.023624Z)

xbrl:Concept xbrl:Entity xbrl:Period xbrl:Unit sec:Accepted

fac:Assets[90,055,000,000 USD] = fac:LiabilitiesAndEquity[90,055,000,000 USD]

[BS1] Equity = EquityAttributableToParent + EquityAttributableToNoncontrollingInterest

fac:Equity[33,440,000,000 USD] = fac:EquityAttributableToParent[33,173,000,000 USD] + fac:EquityAttributableToNoncontrollingInterest[267,000,000 USD]

[BS3] Assets = CurrentAssets + NoncurrentAssets

fac:Assets[90,055,000,000 USD] = fac:CurrentAssets[31,304,000,000 USD] + fac:NoncurrentAssets[58,751,000,000 USD]

[BS4] Liabilities = CurrentLiabilities + NoncurrentLiabilities

fac:Liabilities[56,615,000,000 USD] = fac:CurrentLiabilities[27,811,000,000 USD] + fac:NoncurrentLiabilities[28,804,000,000 USD]

[BS5] LiabilitiesAndEquity = Liabilities + CommitmentsAndContingencies + TemporaryEquity + Equity

fac:Assets -> us-gaap:Assets

fac:Equity -> us-gaap:StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest

fac:CurrentLiabilities -> us-gaap:LiabilitiesCurrent

fac:LiabilitiesAndEquity -> us-gaap:LiabilitiesAndStockholdersEquity

fac:TemporaryEquity = 0

fac:NoncurrentLiabilities[28,804,000,000 USD] = fac:Liabilities[56,615,000,000 USD] - fac:CurrentLiabilities[27,811,000,000 USD]

fac:NoncurrentAssets[58,751,000,000 USD] = fac:Assets[90,055,000,000 USD] - fac:CurrentAssets[31,304,000,000 USD]

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:CurrentAssets -> us-gaap:AssetsCurrent

fac:EquityAttributableToNoncontrollingInterest -> us-gaap:MinorityInterest

fac:EquityAttributableToParent -> us-gaap:StockholdersEquity

fac:CommitmentsAndContingencies = 0

fac:RedeemableNoncontrollingInterest = 0

[CF5] NetCashFlowFromInvestingActivities = NetCashFlowFromInvestingActivitiesContinuing + NetCashFlowFromInvestingActivitiesDiscontinued

[IS4] IncomeLossFromContinuingOperationsBeforeTax = IncomeLossBeforeEquityMethodInvestments + IncomeLossFromEquityMethodInvestments

[CF6] NetCashFlowFromFinancingActivities = NetCashFlowFromFinancingActivitiesContinuing + NetCashFlowFromFinancingActivitiesDiscontinued

[IS5] IncomeLossFromContinuingOperationsAfterTax = IncomeLossFromContinuingOperationsBeforeTax - IncomeTaxExpenseBenefit

[IS1] GrossProfit = Revenues - CostOfRevenue

fac:GrossProfit[28,433,000,000 USD] = fac:Revenues[46,854,000,000 USD] - fac:CostOfRevenue[18,421,000,000 USD]

[IS7] NetIncomeLoss = NetIncomeLossAttributableToParent + NetIncomeLossAttributableToNoncontrollingInterest

[IS10] ComprehensiveIncomeLoss = NetIncomeLoss + OtherComprehensiveIncomeLoss

fac:ComprehensiveIncomeLoss[8,576,000,000 USD] = fac:NetIncomeLoss[8,626,000,000 USD] + fac:OtherComprehensiveIncomeLoss[-50,000,000 USD]

[IS8] NetIncomeLossAvailableToCommonStockholdersBasic = NetIncomeLossAttributableToParent - PreferredStockDividendsAndOtherAdjustments

[IS3] IncomeLossBeforeEquityMethodInvestments = OperatingIncomeLoss + NonoperatingIncomeLossPlusInterestAndDebtExpense

[IS9] ComprehensiveIncomeLoss = ComprehensiveIncomeLossAttributableToParent + ComprehensiveIncomeLossAttributableToNoncontrollingInterest

[CF4] NetCashFlowFromOperatingActivities = NetCashFlowFromOperatingActivitiesContinuing + NetCashFlowFromOperatingActivitiesDiscontinued

[IS11] OperatingIncomeLoss = Revenues - CostsAndExpenses + OtherOperatingIncomeExpenses

fac:OperatingIncomeLoss[10,228,000,000 USD] = fac:Revenues[46,854,000,000 USD] - CostsAndExpenses[0] + OtherOperatingIncomeExpenses[0]

[IS2] OperatingIncomeLoss = GrossProfit - OperatingExpenses + OtherOperatingIncomeExpenses

fac:OperatingIncomeLoss[10,228,000,000 USD] = fac:GrossProfit[28,433,000,000 USD] - OperatingExpenses[0] + OtherOperatingIncomeExpenses[0]

xbrl:Concept xbrl:Entity xbrl:Period sec:Accepted

fac:TradingSymbol['ko'] = entity(http://www.sec.gov/CIK 0000021344).Profiles.SEC.Tickers

fac:IncomeStatementFormat[Multi-step] = Multi-step (because fac:GrossProfit[28,433,000,000 USD], fac:CostOfRevenue[18,421,000,000 USD])

Income Statement Start Period imputation

fac:IncomeStatementStartPeriodYearToDate[2013-01-01] = facts:duration-for-fact(fac:Revenues[46,854,000,000 USD]).Start

xbrl:Unit.Default = "xbrl28:NoUnit"

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:EntityRegistrantName -> dei:EntityRegistrantName

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:EntityCentralIndexKey -> dei:EntityCentralIndexKey

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:EntityFilerCategory -> dei:EntityFilerCategory

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalYearEnd -> dei:CurrentFiscalYearEndDate

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalPeriod -> dei:DocumentFiscalPeriodFocus

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:FiscalYear -> dei:DocumentFiscalYearFocus

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:BalanceSheetDate -> dei:DocumentPeriodEndDate

xbrl:Unit.Default = "xbrl28:NoUnit"

fac:DocumentType -> dei:DocumentType

fac:NetIncomeLoss -> us-gaap:ProfitLoss

fac:Revenues -> us-gaap:SalesRevenueGoodsNet

fac:OperatingIncomeLoss -> us-gaap:OperatingIncomeLoss

fac:GrossProfit -> us-gaap:GrossProfit

fac:CostOfRevenue -> us-gaap:CostOfGoodsSold

fac:NetCashFlowFromInvestingActivities -> us-gaap:NetCashProvidedByUsedInInvestingActivities

Income (Loss) Before Equity Method Investments

Net Cash Flow from Investing Activities, Continuing

fac:NetCashFlowFromFinancingActivities -> us-gaap:NetCashProvidedByUsedInFinancingActivities

fac:NetCashFlowFromInvestingActivitiesDiscontinued = 0

fac:NetCashFlowFromOperatingActivities -> us-gaap:NetCashProvidedByUsedInOperatingActivities

Net Cash Flow from Operating Activities, Discontinued

fac:NetCashFlowFromOperatingActivitiesDiscontinued[0 USD] = 0

Net Cash Flow from Operating Activities, Continuing

fac:OperatingExpenses = 0

fac:OtherOperatingIncomeExpenses = 0

Net Cash Flow from Financing Activities, Discontinued

fac:NetCashFlowFromFinancingActivitiesDiscontinued[0 USD] = 0

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:IncomeLossFromEquityMethodInvestments -> us-gaap:IncomeLossFromEquityMethodInvestments

Net Cash Flow from Financing Activities, Continuing

fac:NetIncomeLossAttributableToParent -> us-gaap:NetIncomeLoss

fac:ComprehensiveIncomeLoss -> us-gaap:ComprehensiveIncomeNetOfTaxIncludingPortionAttributableToNoncontrollingInterest

fac:CostsAndExpenses = 0

fac:NonoperatingIncomeLoss = 0

fac:InterestAndDebtExpense = 0

fac:ComprehensiveIncomeLossAttributableToNoncontrollingInterest -> us-gaap:ComprehensiveIncomeNetOfTaxAttributableToNoncontrollingInterest

Net Income (Loss) Available to Common Stockholders, Basic

fac:NetIncomeLossAvailableToCommonStockholdersBasic[8,584,000,000 USD] = fac:NetIncomeLossAttributableToParent[8,584,000,000 USD]

fac:OtherComprehensiveIncomeLoss[-50,000,000 USD] = fac:ComprehensiveIncomeLoss[8,576,000,000 USD] - fac:NetIncomeLoss[8,626,000,000 USD]

Income (Loss) from Continuing Operations After Tax

fac:ComprehensiveIncomeLossAttributableToParent -> us-gaap:ComprehensiveIncomeNetOfTax

fac:IncomeLossFromDiscontinuedOperationsNetOfTax = 0

fac:ExtraordinaryItemsOfIncomeExpenseNetOfTax = 0

fac:NetIncomeLossAttributableToNoncontrollingInterest -> us-gaap:NetIncomeLossAttributableToNoncontrollingInterest

fac:ExchangeGainsLosses -> us-gaap:EffectOfExchangeRateOnCashAndCashEquivalents

Preferred Stock Dividends and Other Adjustments

Nonoperating Income (Loss) + Interest and Debt Expense

dei:LegalEntityAxis.Default = "sec:DefaultLegalEntity"

fac:NetCashFlow -> us-gaap:CashAndCashEquivalentsPeriodIncreaseDecrease

Nonoperating Income (Loss) + Interest and Debt Expense + Income (Loss) from Equity Method Investments

fac:IncomeTaxExpenseBenefit -> us-gaap:IncomeTaxExpenseBenefit

fac:ReturnOnEquity[0.26 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Equity[33,440,000,000 USD]

fac:ReturnOnAssets[0.1 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Assets[90,055,000,000 USD]

fac:ReturnOnSales[0.18 USD] = fac:NetIncomeLoss[8,626,000,000 USD] div fac:Revenues[46,854,000,000 USD]

fac:ResearchAndDevelopment = 0

Generated by 28.io, for more information see http://www.28.io/xbrl (2014-12-12T16:45:35.976975Z)


:arrow_up: Migrate companies module.

:arrow_up: Migrate companies module.

jsoniq version "1.0";

(:
 : Copyright 2012-2013 28msec Inc.
 :)

(:~
 :
This module provides functionality for querying companies (XBRL entities)
 :  submitting to the SEC.

 :
SEC Companies are nothing else than XBRL entities. For XBRL-generic requests on
 : entities, use the generic entities module.

 :
 :
With this module, you can retrieve a company with its CIK (without converting
 : it to an EID). You can also retrieve companies by sector, by SIC code, by types,
 : by tags, by tickers.

 :
 : @author Charles Hoffman
 : @author Matthias Brantner
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :)
module namespace companies = "http://28.io/modules/xbrl/profiles/sec/companies";

import module namespace mw = "http://28.io/modules/xbrl/data-source-wrapper";

import module namespace csv = "http://zorba.io/modules/json-csv";

import module namespace entities = "http://28.io/modules/xbrl/entities";
import module namespace sec = "http://28.io/modules/xbrl/profiles/sec/core";
import module namespace archives = "http://28.io/modules/xbrl/archives";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 :
Return all companies

 :
 : @return all companies.
 :)
declare function companies:companies() as object*
{
  entities:entities()
};

(:~
 :
Return the companies with the given identifiers.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return the companies with the given identifiers
 :         the empty sequence if no company was found or if the input is an
 :         empty sequence.
 :)
declare function companies:companies($companies-or-ids as item*) as object*
{
  let $ids as atomic* :=
    for $s in $companies-or-ids
    where $s instance of atomic
    return $s
  let $companies as object* :=
    for $s in $companies-or-ids
    where $s instance of object
    return $s
  return
    (
      $companies,
      if (exists($ids))
      then mw:find($entities:col, { "_id" : [ $ids ! companies:eid($$) ] })
      else ()
    )
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, or sics.

 :
 : @param $ciks a set of CIKs.
 : @param $tags a set of tags (ALL retrieves all companies).
 : @param $tickers a set of tickers.
 : @param $sics a set of SIC codes.
 :
 : @return the companies with the given identifiers, tags, tickers, or sic codes.
 :)
declare function companies:companies(
    $ciks as string*,
    $tags as string*,
    $tickers as string*,
    $sics as string*,
    $eids as string*) as object*
{
    companies:companies($ciks, $tags, $tickers, $sics, $eids, ())
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, sics, or aids.

 :
 : @param $ciks a set of CIKs.
 : @param $tags a set of tags (ALL retrieves all companies).
 : @param $tickers a set of tickers.
 : @param $sics a set of SIC codes.
 : @param $aids a set of archive IDs.
 :
 : @return the companies with the given identifiers, tags, tickers, sic codes, or archive IDs.
 :)
declare function companies:companies(
    $ciks as string*,
    $tags as string*,
    $tickers as string*,
    $sics as string*,
    $eids as string*,
    $aids as string*) as object*
{
    if ($tags = "ALL")
    then companies:companies()
    else
        for $c in (
            companies:companies($ciks),
            companies:companies-for-tags($tags),
            companies:companies-for-tickers($tickers),
            companies:companies-for-SIC($sics),
            entities:entities($eids),
            companies:companies-for-archives($aids)
        )
        group by $c._id
        return $c[1]
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, or sics.

 :
 : @param $options an object of the form
 :   {
 :     ciks : [ ],
 :     tags : [ ],
 :     tickers : [ ],
 :     sics : [ ]
 :   }
 :
 : @return the companies with the given identifiers, tags, tickers, or sic codes.
 :)
declare function companies:companies-for(
  $options as object) as object*
{
  for $c in (
    companies:companies(flatten($options.ciks)),
    companies:companies-for-tags(flatten($options.tags)),
    companies:companies-for-tickers(flatten($options.tickers)),
    companies:companies-for-SIC(flatten($options.sic))
  )
  group by $c._id
  return $c[1]
};

(:~
 :
Retrieves the type of a company.

 :
 : @param $companies-or-ciks a sequence of companies or their identifiers (CIKs).
 :
 : @return all company types.
 :)
declare function companies:types($companies-or-ciks as item*) as string*
{
  let $companies := companies:companies($companies-or-ciks)
  return $companies.Profiles.SEC.CompanyType
};

(:~
 :
Retrieves all companies for the given archives.

 :
 : @param $archives a sequence of archive objects or ids.
 :
 : @return all companies for the given archives.
 :)
declare function companies:companies-for-archives($aids as string*) as object*
{
    if(empty($aids))
    then ()
    else
        let $entities := mw:find($archives:col, { "_id" : [ $aids ] }, { "Entity" : 1 })
        return entities:entities(distinct-values($entities.Entity))
};

(:~
 :
Retrieves all companies in the given sectors.

 :
 : @deprecated please use companies:companies-for-sectors#1
 : @param $sectors a sequence of sectors as strings.
 :
 : @return all companies in these sectors.
 :)
declare function companies:companies-for-sector($sectors as string*) as object*
{
  companies:companies-for-sectors($sectors)
};

(:~
 :
Retrieves all companies in the given sectors.

 :
 : @param $sectors a sequence of sectors as strings.
 :
 : @return all companies in these sectors.
 :)
declare function companies:companies-for-sectors($sectors as string*) as object*
{
  for $s in $sectors
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Sector" : $s } } })
};

(:~
 :
Retrieves all companies whose type of business
 : matches the SIC (Standard Industrial Classification) code.

 :
 : @param $sic-codes a sequence of SIC codes.
 :
 : @return all companies with one of these SIC codes.
 :)
declare function companies:companies-for-sic($sic-codes as string*) as object*
{
  mw:find($entities:col, { "Profiles" : { "SEC" : { "SIC" : [ $sic-codes ] } } })
};

(:~
 :
Retrieves all companies whose type of business
 : matches the SIC (Standard Industrial Classification) code.

 :
 : @deprecated please use companies:companies-for-sic
 : @param $sic-codes a sequence of SIC codes.
 :
 : @return all companies with one of these SIC codes.
 :)
declare function companies:companies-for-SIC($sic-codes as string*) as object*
{
  for $s in $sic-codes
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "SIC" : $s } } })
};

(:~
 :
Retrieves all companies whose company type matches the passed string(s).

 :
 : @deprecated please use companies:companies-for-types
 : @param $company-type a sequence of strings of "Corporation", "Partnership", or "unknown".
 :
 : @return all companies with matching company type.
 :)
declare function companies:companies-by-types($company-types as string*) as object*
{
  companies:companies-for-types($company-types)
};

(:~
 :
Retrieves all companies whose company type matches the passed string(s).

 :
 : @param $company-type a sequence of strings of "Corporation", "Partnership", or "unknown".
 :
 : @return all companies with matching company type.
 :)
declare function companies:companies-for-types($company-types as string*) as object*
{
  for $t in $company-types
  return
    if ($t = ("Corporation", "Partnership", "unknown"))
    then ();
    else error(QName("companies:UNKNOWN-COMPANY-TYPE"), $t || ": Unknown company type. Allowed values: \"Corporation\", \"Partnership\", or \"unknown\".");

  for $t in $company-types
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "CompanyType" : $t } } })
};

(:~
 :
Return all companies with any of the given tags.

 :
 : @param $tags the tags to filter.
 : @return all companies with the given tags.
 :)
declare function companies:companies-for-tags($tags as string*) as object*
{
  for $tag in $tags
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Tags" : $tag } } })
};

(:~
 :
Return all companies with any of the given ticker symbols.

 :
 :
Tickers are case insensitive

 :
 : @param $tickers the tickers to filter.
 : @return all companies with the given tickers.
 :)
declare function companies:companies-for-tickers(
  $tickers as  string*) as object*
{
  for $ticker in $tickers
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Tickers" : lower-case($ticker) } } })
};

(:~
 :
Return company type for a given company name. Company type can be one of:

 :

 :

 :
Corporation

 :
Partnership

 :
unknown

 :

 :

 :
 : @deprecated please use companies:types-for-names
 : @param $company-name the name of a company
 :
 : @return the company type string or "unknown" if the type can not be inferred
 :)
declare function companies:company-type($company-name as string) as string
{
  companies:types-for-names($company-name)
};

(:~
 :
Returns a CSV representation of the given companies.

 :
 :
Commas are used as column separators. Abscent values are serialized
 : as empty strings.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return a sequence of strings, each one representing one entity as CSV
 :)
declare function companies:to-csv($companies-or-ids as item*) as string*
{
  csv:serialize(
    for $e in companies:companies($companies-or-ids)
    return {
      ID : $e._id,
      Archives: $e.Archives,
      Profile : $e.Profiles.SEC.Name,
      EntityName : $e.Profiles.SEC.CompanyName,
      CompanyType : $e.Profiles.SEC.CompanyType,
      SIC : $e.Profiles.SEC.SIC,
      SICDescription : $e.Profiles.SEC.SICDescription,
      SICGroup :$e.Profiles.SEC.SICGroup,
      Sector : $e.Profiles.SEC.Sector,
      IsTrust : $e.Profiles.SEC.IsTrust,
      Tickers : string-join($e.Profiles.SEC.Tickers[], " "),
      Tags : string-join($e.Profiles.SEC.Tags[], " ")
    },
    { serialize-null-as : "" }
  )
};

(:~
 :
Returns an XML representation of the given companies.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return a sequence of elements, each one representing one entity as XML
 :)
declare function companies:to-xml($companies-or-ids as item*) as element()*
{
  for $e in companies:companies($companies-or-ids)
  return
    <Entity>
      <ID>{$e._id}</ID>
      <Profile name="{$e.Profiles.SEC.Name}">
          <EntityRegistrantName>{$e.Profiles.SEC.CompanyName}</EntityRegistrantName>
          <CompanyType>{$e.Profiles.SEC.CompanyType}</CompanyType>
          <SIC>{$e.Profiles.SEC.SIC}</SIC>
          <SICDescription>{$e.Profiles.SEC.SICDescription}</SICDescription>
          <SICGroup>{$e.Profiles.SEC.SICGroup}</SICGroup>
          <Sector>{$e.Profiles.SEC.Sector}</Sector>
          <IsTrust>{$e.Profiles.SEC.IsTrust}</IsTrust>
          <Tickers>{
              for $t in $e.Profiles.SEC.Tickers[]
              return <Ticker>{$t}</Ticker>
          }</Tickers>
          <Tags>
          {
              for $t in $e.Profiles.SEC.Tags[]
              return <Tag>{$t}</Tag>
          }
          </Tags>
      </Profile>
    </Entity>
};

(:~
 :
Return company types for a given sequence of company names. Company type can be one of:

 :

 :

 :
Corporation

 :
Partnership

 :
unknown

 :

 :

 :
 : @param $company-names the sequence of the names of the companies
 :
 : @return the company type string or "unknown" if the type can not be inferred
 :)
declare function companies:types-for-names($company-names as string*) as string*
{
  for $company-name in $company-names
  let $lower-name as string := lower-case($company-name)
  return
    switch (true)
    case contains($lower-name, " corp")
    case contains($lower-name, " inc")
    case contains($lower-name, " co")
    case contains($lower-name, " bancorp")
    case contains($lower-name, " bancshares")
    case contains($lower-name, " group")
    case contains($lower-name, " llc")
    case contains($lower-name, " l.l.c.")
      return "Corporation"
    case contains($lower-name, " plc")
    case contains($lower-name, " lp")
    case contains($lower-name, " l.p.")
    case contains($lower-name, " lllp")
    case contains($lower-name, " ltd")
    case contains($lower-name, " partnership")
      return "Partnership"
    default return "unknown"
};

(:~
 :
 :
Converts the input to a normalized CIK. The input
 : can be either a pure CIK without scheme, or an already
 : normalized CIK, or an entity object which contains a CIK
 : in its id field.

 :
 : @param $cik_or_entity a CIK or an entity.
 :
 : @error sec:INVALID_PARAMETER if the CIK or entity is not valid
 :
 : @return the normalized CIK.
 :)
declare function companies:eid($companies-or-eids-or-ciks as item*) as string*
{
  let $preprocessed := for $c in $companies-or-eids-or-ciks
                       return switch(true)
                              case not $c instance of atomic return $c
                              case $c castable as string return string($c)
                              default return $c
  let $eids := entities:eid($preprocessed)
  for $eid in $eids
  return typeswitch ($eid)
         case $cik as string return
           switch(true)
           case starts-with($cik, $sec:CIK) return $cik
           case contains($cik, " ") return
               (: cik seems to contain a scheme, but not a CIK scheme, i.e. it's invalid :)
               error(QName("sec:INVALID_PARAMETER"), $cik || ": not a valid CIK")
           case not $cik castable as integer return
               (: cik seems to not be an integer :)
               error(QName("sec:INVALID_PARAMETER"), $cik || ": not a valid integer")
           default return let $cik := normalize-space($cik)
                          return
                          $sec:CIK || " " ||
                          format-integer($cik cast as integer, "0000000000") cast as string
         default return error(
             QName("sec:INVALID_PARAMETER"),
             "Invalid entity or CIK (must be an object or a string): "
             || serialize($companies-or-eids-or-ciks))
};

jsoniq version "1.0";

(:
 : Copyright 2012-2013 28msec Inc.
 :)

(:~
 :
This module provides functionality for querying companies (XBRL entities)
 :  submitting to the SEC.

 :
SEC Companies are nothing else than XBRL entities. For XBRL-generic requests on
 : entities, use the generic entities module.

 :
 :
With this module, you can retrieve a company with its CIK (without converting
 : it to an EID). You can also retrieve companies by sector, by SIC code, by types,
 : by tags, by tickers.

 :
 : @author Charles Hoffman
 : @author Matthias Brantner
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :)
module namespace companies = "http://28.io/modules/xbrl/profiles/sec/companies";

import module namespace mw = "http://28.io/modules/xbrl/mongo-wrapper";

import module namespace csv = "http://zorba.io/modules/json-csv";

import module namespace entities = "http://28.io/modules/xbrl/entities";
import module namespace sec = "http://28.io/modules/xbrl/profiles/sec/core";
import module namespace archives = "http://28.io/modules/xbrl/archives";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 :
Return all companies

 :
 : @return all companies.
 :)
declare function companies:companies() as object*
{
  entities:entities()
};

(:~
 :
Return the companies with the given identifiers.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return the companies with the given identifiers
 :         the empty sequence if no company was found or if the input is an
 :         empty sequence.
 :)
declare function companies:companies($companies-or-ids as item*) as object*
{
  let $ids as atomic* :=
    for $s in $companies-or-ids
    where $s instance of atomic
    return $s
  let $companies as object* :=
    for $s in $companies-or-ids
    where $s instance of object
    return $s
  return
    (
      $companies,
      if (exists($ids))
      then mw:find($entities:col, { "_id" : [ $ids ! companies:eid($$) ] })
      else ()
    )
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, or sics.

 :
 : @param $ciks a set of CIKs.
 : @param $tags a set of tags (ALL retrieves all companies).
 : @param $tickers a set of tickers.
 : @param $sics a set of SIC codes.
 :
 : @return the companies with the given identifiers, tags, tickers, or sic codes.
 :)
declare function companies:companies(
    $ciks as string*,
    $tags as string*,
    $tickers as string*,
    $sics as string*,
    $eids as string*) as object*
{
    companies:companies($ciks, $tags, $tickers, $sics, $eids, ())
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, sics, or aids.

 :
 : @param $ciks a set of CIKs.
 : @param $tags a set of tags (ALL retrieves all companies).
 : @param $tickers a set of tickers.
 : @param $sics a set of SIC codes.
 : @param $aids a set of archive IDs.
 :
 : @return the companies with the given identifiers, tags, tickers, sic codes, or archive IDs.
 :)
declare function companies:companies(
    $ciks as string*,
    $tags as string*,
    $tickers as string*,
    $sics as string*,
    $eids as string*,
    $aids as string*) as object*
{
    if ($tags = "ALL")
    then companies:companies()
    else
        for $c in (
            companies:companies($ciks),
            companies:companies-for-tags($tags),
            companies:companies-for-tickers($tickers),
            companies:companies-for-SIC($sics),
            entities:entities($eids),
            companies:companies-for-archives($aids)
        )
        group by $c._id
        return $c[1]
};

(:~
 :
Return a distinct set of companies identified by either
 :   CIKs, tags, tickers, or sics.

 :
 : @param $options an object of the form
 :   {
 :     ciks : [ ],
 :     tags : [ ],
 :     tickers : [ ],
 :     sics : [ ]
 :   }
 :
 : @return the companies with the given identifiers, tags, tickers, or sic codes.
 :)
declare function companies:companies-for(
  $options as object) as object*
{
  for $c in (
    companies:companies(flatten($options.ciks)),
    companies:companies-for-tags(flatten($options.tags)),
    companies:companies-for-tickers(flatten($options.tickers)),
    companies:companies-for-SIC(flatten($options.sic))
  )
  group by $c._id
  return $c[1]
};

(:~
 :
Retrieves the type of a company.

 :
 : @param $companies-or-ciks a sequence of companies or their identifiers (CIKs).
 :
 : @return all company types.
 :)
declare function companies:types($companies-or-ciks as item*) as string*
{
  let $companies := companies:companies($companies-or-ciks)
  return $companies.Profiles.SEC.CompanyType
};

(:~
 :
Retrieves all companies for the given archives.

 :
 : @param $archives a sequence of archive objects or ids.
 :
 : @return all companies for the given archives.
 :)
declare function companies:companies-for-archives($aids as string*) as object*
{
    if(empty($aids))
    then ()
    else
        let $entities := mw:find($archives:col, { "_id" : [ $aids ] }, { "Entity" : 1 })
        return entities:entities(distinct-values($entities.Entity))
};

(:~
 :
Retrieves all companies in the given sectors.

 :
 : @deprecated please use companies:companies-for-sectors#1
 : @param $sectors a sequence of sectors as strings.
 :
 : @return all companies in these sectors.
 :)
declare function companies:companies-for-sector($sectors as string*) as object*
{
  companies:companies-for-sectors($sectors)
};

(:~
 :
Retrieves all companies in the given sectors.

 :
 : @param $sectors a sequence of sectors as strings.
 :
 : @return all companies in these sectors.
 :)
declare function companies:companies-for-sectors($sectors as string*) as object*
{
  for $s in $sectors
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Sector" : $s } } })
};

(:~
 :
Retrieves all companies whose type of business
 : matches the SIC (Standard Industrial Classification) code.

 :
 : @param $sic-codes a sequence of SIC codes.
 :
 : @return all companies with one of these SIC codes.
 :)
declare function companies:companies-for-sic($sic-codes as string*) as object*
{
  mw:find($entities:col, { "Profiles" : { "SEC" : { "SIC" : [ $sic-codes ] } } })
};

(:~
 :
Retrieves all companies whose type of business
 : matches the SIC (Standard Industrial Classification) code.

 :
 : @deprecated please use companies:companies-for-sic
 : @param $sic-codes a sequence of SIC codes.
 :
 : @return all companies with one of these SIC codes.
 :)
declare function companies:companies-for-SIC($sic-codes as string*) as object*
{
  for $s in $sic-codes
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "SIC" : $s } } })
};

(:~
 :
Retrieves all companies whose company type matches the passed string(s).

 :
 : @deprecated please use companies:companies-for-types
 : @param $company-type a sequence of strings of "Corporation", "Partnership", or "unknown".
 :
 : @return all companies with matching company type.
 :)
declare function companies:companies-by-types($company-types as string*) as object*
{
  companies:companies-for-types($company-types)
};

(:~
 :
Retrieves all companies whose company type matches the passed string(s).

 :
 : @param $company-type a sequence of strings of "Corporation", "Partnership", or "unknown".
 :
 : @return all companies with matching company type.
 :)
declare function companies:companies-for-types($company-types as string*) as object*
{
  for $t in $company-types
  return
    if ($t = ("Corporation", "Partnership", "unknown"))
    then ();
    else error(QName("companies:UNKNOWN-COMPANY-TYPE"), $t || ": Unknown company type. Allowed values: \"Corporation\", \"Partnership\", or \"unknown\".");

  for $t in $company-types
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "CompanyType" : $t } } })
};

(:~
 :
Return all companies with any of the given tags.

 :
 : @param $tags the tags to filter.
 : @return all companies with the given tags.
 :)
declare function companies:companies-for-tags($tags as string*) as object*
{
  for $tag in $tags
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Tags" : $tag } } })
};

(:~
 :
Return all companies with any of the given ticker symbols.

 :
 :
Tickers are case insensitive

 :
 : @param $tickers the tickers to filter.
 : @return all companies with the given tickers.
 :)
declare function companies:companies-for-tickers(
  $tickers as  string*) as object*
{
  for $ticker in $tickers
  return mw:find($entities:col, { "Profiles" : { "SEC" : { "Tickers" : lower-case($ticker) } } })
};

(:~
 :
Return company type for a given company name. Company type can be one of:

 :

 :

 :
Corporation

 :
Partnership

 :
unknown

 :

 :

 :
 : @deprecated please use companies:types-for-names
 : @param $company-name the name of a company
 :
 : @return the company type string or "unknown" if the type can not be inferred
 :)
declare function companies:company-type($company-name as string) as string
{
  companies:types-for-names($company-name)
};

(:~
 :
Returns a CSV representation of the given companies.

 :
 :
Commas are used as column separators. Abscent values are serialized
 : as empty strings.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return a sequence of strings, each one representing one entity as CSV
 :)
declare function companies:to-csv($companies-or-ids as item*) as string*
{
  csv:serialize(
    for $e in companies:companies($companies-or-ids)
    return {
      ID : $e._id,
      Archives: $e.Archives,
      Profile : $e.Profiles.SEC.Name,
      EntityName : $e.Profiles.SEC.CompanyName,
      CompanyType : $e.Profiles.SEC.CompanyType,
      SIC : $e.Profiles.SEC.SIC,
      SICDescription : $e.Profiles.SEC.SICDescription,
      SICGroup :$e.Profiles.SEC.SICGroup,
      Sector : $e.Profiles.SEC.Sector,
      IsTrust : $e.Profiles.SEC.IsTrust,
      Tickers : string-join($e.Profiles.SEC.Tickers[], " "),
      Tags : string-join($e.Profiles.SEC.Tags[], " ")
    },
    { serialize-null-as : "" }
  )
};

(:~
 :
Returns an XML representation of the given companies.

 :
 : @param $companies-or-ids the ids of the companies or the companies themselves.
 :
 : @return a sequence of elements, each one representing one entity as XML
 :)
declare function companies:to-xml($companies-or-ids as item*) as element()*
{
  for $e in companies:companies($companies-or-ids)
  return
    <Entity>
      <ID>{$e._id}</ID>
      <Profile name="{$e.Profiles.SEC.Name}">
          <EntityRegistrantName>{$e.Profiles.SEC.CompanyName}</EntityRegistrantName>
          <CompanyType>{$e.Profiles.SEC.CompanyType}</CompanyType>
          <SIC>{$e.Profiles.SEC.SIC}</SIC>
          <SICDescription>{$e.Profiles.SEC.SICDescription}</SICDescription>
          <SICGroup>{$e.Profiles.SEC.SICGroup}</SICGroup>
          <Sector>{$e.Profiles.SEC.Sector}</Sector>
          <IsTrust>{$e.Profiles.SEC.IsTrust}</IsTrust>
          <Tickers>{
              for $t in $e.Profiles.SEC.Tickers[]
              return <Ticker>{$t}</Ticker>
          }</Tickers>
          <Tags>
          {
              for $t in $e.Profiles.SEC.Tags[]
              return <Tag>{$t}</Tag>
          }
          </Tags>
      </Profile>
    </Entity>
};

(:~
 :
Return company types for a given sequence of company names. Company type can be one of:

 :

 :

 :
Corporation

 :
Partnership

 :
unknown

 :

 :

 :
 : @param $company-names the sequence of the names of the companies
 :
 : @return the company type string or "unknown" if the type can not be inferred
 :)
declare function companies:types-for-names($company-names as string*) as string*
{
  for $company-name in $company-names
  let $lower-name as string := lower-case($company-name)
  return
    switch (true)
    case contains($lower-name, " corp")
    case contains($lower-name, " inc")
    case contains($lower-name, " co")
    case contains($lower-name, " bancorp")
    case contains($lower-name, " bancshares")
    case contains($lower-name, " group")
    case contains($lower-name, " llc")
    case contains($lower-name, " l.l.c.")
      return "Corporation"
    case contains($lower-name, " plc")
    case contains($lower-name, " lp")
    case contains($lower-name, " l.p.")
    case contains($lower-name, " lllp")
    case contains($lower-name, " ltd")
    case contains($lower-name, " partnership")
      return "Partnership"
    default return "unknown"
};

(:~
 :
 :
Converts the input to a normalized CIK. The input
 : can be either a pure CIK without scheme, or an already
 : normalized CIK, or an entity object which contains a CIK
 : in its id field.

 :
 : @param $cik_or_entity a CIK or an entity.
 :
 : @error sec:INVALID_PARAMETER if the CIK or entity is not valid
 :
 : @return the normalized CIK.
 :)
declare function companies:eid($companies-or-eids-or-ciks as item*) as string*
{
  let $preprocessed := for $c in $companies-or-eids-or-ciks
                       return switch(true)
                              case not $c instance of atomic return $c
                              case $c castable as string return string($c)
                              default return $c
  let $eids := entities:eid($preprocessed)
  for $eid in $eids
  return typeswitch ($eid)
         case $cik as string return
           switch(true)
           case starts-with($cik, $sec:CIK) return $cik
           case contains($cik, " ") return
               (: cik seems to contain a scheme, but not a CIK scheme, i.e. it's invalid :)
               error(QName("sec:INVALID_PARAMETER"), $cik || ": not a valid CIK")
           case not $cik castable as integer return
               (: cik seems to not be an integer :)
               error(QName("sec:INVALID_PARAMETER"), $cik || ": not a valid integer")
           default return let $cik := normalize-space($cik)
                          return
                          $sec:CIK || " " ||
                          format-integer($cik cast as integer, "0000000000") cast as string
         default return error(
             QName("sec:INVALID_PARAMETER"),
             "Invalid entity or CIK (must be an object or a string): "
             || serialize($companies-or-eids-or-ciks))
};


:white_check_mark: added swagger example tests.

import module namespace test = "http://apps.28.io/test";

declare %an:nondeterministic function local:test-facttable($expected as integer, $params as object) as item
{
    let $endpoint := "facts"
    let $request := test:invoke($endpoint, $params)
    let $actual as integer := count($request[2].FactTable[])
    let $status as integer := $request[1]
    return test:assert-eq($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-non-existing-entity() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: [ "tse-ed-t:DividendPerShare" ],
        eid: "http://www.example.or.jp/doesntexist 666",
        format:"csv",
        fiscalYear: 2013
    }
    let $res as item* := test:invoke-raw($endpoint, $params)
    return if($res.status eq 200 and ($res.headers."Content-Length" eq "0" or empty($res.body.content))) then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res,
        expected: ""
    }
};

test:check-all-success({
    entityNotFound: local:test-non-existing-entity(),
    swaggerExample1: test:invoke-and-assert-deep-equal(
          "facts",
          {
              "xbrl:Entity":"http://disclosure.edinet-fsa.go.jp E02529-000",
              "fsa:FiscalYear": 2014,
              "fsa:FiscalPeriod": "Q1",
              concept: [ "jpcrp-cor:TotalAssetsIFRSSummaryOfBusinessResults",
                         "jpcrp-cor:ProfitLossAttributableToOwnersOfParentIFRSSummaryOfBusinessResults"]
          },
          function($res as item*) as item* { count($res.FactTable[]) },
          2
        ),
    swaggerExample2: test:invoke-and-assert-deep-equal(
          "facts",
          {
              "xbrl:Entity": "http://disclosure.edinet-fsa.go.jp E02529-000",
              "fiscalPeriod": "Q2",
              "fiscalYear": 2014,
              "concept": ["jpcrp-cor:NumberOfSharesHeld", "jpcrp-cor:ShareholdingRatio"],
              "jpcrp-cor:MajorShareholdersAxis": "ALL",
              "jpcrp-cor:MajorShareholdersAxis::default": "NONE"
          },
          function($res as item*) as item* { count($res.FactTable[]) },
          22
        )
})

import module namespace test = "http://apps.28.io/test";

declare %an:nondeterministic function local:test-facttable($expected as integer, $params as object) as item
{
    let $endpoint := "facts"
    let $request := test:invoke($endpoint, $params)
    let $actual as integer := count($request[2].FactTable[])
    let $status as integer := $request[1]
    return test:assert-eq($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-non-existing-entity() as item
{
    let $endpoint := "facts"
    let $params := {
        concept: [ "tse-ed-t:DividendPerShare" ],
        eid: "http://www.example.or.jp/doesntexist 666",
        format:"csv",
        fiscalYear: 2013
    }
    let $res as item* := test:invoke-raw($endpoint, $params)
    return if($res.status eq 200 and ($res.headers."Content-Length" eq "0" or empty($res.body.content))) then true else {
        url: test:url($endpoint, $params),
        unexpectedResponse: $res,
        expected: ""
    }
};

test:check-all-success({
    entityNotFound: local:test-non-existing-entity(),
    generic: local:test-facttable(2, {
            "xbrl:Entity":"http://disclosure.edinet-fsa.go.jp E02529-000",
            "fsa:FiscalYear": 2014,
            "fsa:FiscalPeriod": "Q1",
            concept: [ "jpcrp-cor:TotalAssetsIFRSSummaryOfBusinessResults",
                       "jpcrp-cor:ProfitLossAttributableToOwnersOfParentIFRSSummaryOfBusinessResults"]
        })
})