From 367404f1b4d0177fa4604ac0e22cdb5736ef406e Mon Sep 17 00:00:00 2001 From: Kelvin Date: Tue, 3 Nov 2026 12:43:09 +0530 Subject: [PATCH 01/19] feat: filter mandi-price response to the requested market and price fields [OpenAgriNet/network-adapter#107] Refuse a select whose market.marketCode is absent or empty before Agmarknet is called; without it the query widens to the whole district. Each on_select resource carries market.marketCode, where catalog-ondemand.yaml puts it. Refuse a select whose supportedPriceFields lists a value outside the pack's Minimum/Maximum/Modal enum, which would otherwise return rows with no price. Supersedes the marketCode change in #98. --- .../agmarknet/mandi-price.select.yaml | 34 +++++++++++++------ .../MandiPrice/mappings_test.go | 34 +++++++++++++++++-- 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 841618389..54447a68e 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -80,6 +80,26 @@ required: and $match($ra.market.state, /^[A-Za-z]{2,4}$/) ) message: "this capability needs Agmarknet's codes in market: a numeric district and a short alphabetic state, not their names" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + /* market.marketCode, where the catalog advertises it. Absent or empty, Agmarknet + widens the query to the whole district. $string("") is not "" here, so compare raw. */ + $exists($ra.market.marketCode) and $ra.market.marketCode != "" + ) + message: "this capability needs a market code in market.marketCode, as the catalog lists it; without it the query widens to the whole district" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + /* The pack's enum is Minimum, Maximum, Modal. Absent means all three, so only a + present value is checked: anything outside the enum would otherwise answer with + rows that carry no price. (An empty list reads as absent in JSONata.) */ + $exists($ra.supportedPriceFields) + ? $count($ra.supportedPriceFields[$ in ["Minimum", "Maximum", "Modal"]]) + = $count($ra.supportedPriceFields) + : true + ) + message: "supportedPriceFields must list only Minimum, Maximum or Modal" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -338,18 +358,10 @@ response: | "commodityGroup": $r.Group, "variety": $r.Variety, "grade": $r.Grade, - /* Every member comes from the RECORD, so the answer describes what - the provider reported rather than what was asked for. - - marketCode is absent, and that is not an omission. This upstream - TAKES a market code as a query parameter and reports none back -- - there is no such field anywhere in its response. Restating the - requested code against a returned row would assert something - unverified, and district-wide there is no requested code at all - while the rows come from several markets, so one code would have - been wrong for most of them. The pack requires only marketName - and calls marketCode "when available"; here it is not. */ + /* From the RECORD, except marketCode: the upstream reports none, so it is the + requested one (guarded), placed where catalog-ondemand.yaml puts it. */ "market": { + "marketCode": $ra.market.marketCode, "marketName": $r.Market, "district": $r.District, "state": $r.State diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index dc902b48a..dee569032 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -683,9 +683,11 @@ func TestShippedMappingStatesWhatItKnowsRatherThanEchoing(t *testing.T) { } market, _ := ra["market"].(map[string]any) - // The upstream reports no market code, so the answer must not claim one. - if code, present := market["marketCode"]; present { - t.Errorf("market.marketCode = %#v; this upstream reports no code, so asserting one is unfounded", code) + // The upstream reports no market code, but the select requires one and + // the query is scoped to it, so every row is that market's. The code + // sits where the catalog advertised it: market.marketCode. + if market["marketCode"] != "2056" { + t.Errorf("market.marketCode = %#v, want the requested \"2056\"", market["marketCode"]) } // And what is there comes from the record. if market["marketName"] != "Kasdol APMC" || market["state"] != "Chattisgarh" { @@ -722,6 +724,32 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "codes in market", }, + { + // Without a market code the upstream widens the query to the whole + // district, and the answer can no longer say which market it is for. + name: "no market code", + mutate: func(ra map[string]any) { + delete(ra["market"].(map[string]any), "marketCode") + }, + expect: "market code", + }, + { + // Present but empty names no market either. + name: "an empty market code", + mutate: func(ra map[string]any) { + ra["market"].(map[string]any)["marketCode"] = "" + }, + expect: "market code", + }, + { + // Outside the pack's Minimum/Maximum/Modal enum: no price would be + // selected, so the row would carry no price. + name: "a price field the pack does not define", + mutate: func(ra map[string]any) { + ra["supportedPriceFields"] = []any{"Average"} + }, + expect: "supportedPriceFields", + }, { // Everything downstream reads supportedCommodities[0], so this // used to be queried for Paddy alone and answered confidently. From 3c399dc3f4bcd787b9dfdd97ac1ccc877d889217 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Tue, 3 Nov 2026 14:44:30 +0530 Subject: [PATCH 02/19] feat: make mandi-price marketCode optional, district-wide without it [OpenAgriNet/network-adapter#107] marketCode is used when given and must then be a non-empty string. Without it the query covers the whole district: no marketcode is sent upstream, no single code is echoed, and each row names its own market. marketName is trimmed of the upstream's trailing space. Refs OpenAgriNet/network-adapter#97 --- .../agmarknet/mandi-price.select.yaml | 16 +++--- .../MandiPrice/mappings_test.go | 53 ++++++++++++++----- 2 files changed, 51 insertions(+), 18 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 54447a68e..9042dd1b4 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -83,11 +83,14 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* market.marketCode, where the catalog advertises it. Absent or empty, Agmarknet - widens the query to the whole district. $string("") is not "" here, so compare raw. */ - $exists($ra.market.marketCode) and $ra.market.marketCode != "" + /* market.marketCode is optional. Absent, Agmarknet answers for the whole district. + Present, it is used, so it must be a non-empty string: an empty one would widen + the query silently while the caller believes it named a market. */ + $exists($ra.market.marketCode) + ? ($type($ra.market.marketCode) = "string" and $ra.market.marketCode != "") + : true ) - message: "this capability needs a market code in market.marketCode, as the catalog lists it; without it the query widens to the whole district" + message: "market.marketCode, when given, must be a non-empty string; omit it to search the whole district" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -359,10 +362,11 @@ response: | "variety": $r.Variety, "grade": $r.Grade, /* From the RECORD, except marketCode: the upstream reports none, so it is the - requested one (guarded), placed where catalog-ondemand.yaml puts it. */ + requested one, and only when one was requested. District-wide there is no + single code, the key is omitted and each row names its own market. */ "market": { "marketCode": $ra.market.marketCode, - "marketName": $r.Market, + "marketName": $trim($r.Market), "district": $r.District, "state": $r.State }, diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index dee569032..c6d409322 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -683,9 +683,8 @@ func TestShippedMappingStatesWhatItKnowsRatherThanEchoing(t *testing.T) { } market, _ := ra["market"].(map[string]any) - // The upstream reports no market code, but the select requires one and - // the query is scoped to it, so every row is that market's. The code - // sits where the catalog advertised it: market.marketCode. + // The upstream reports no market code, but this select named one and + // the query is scoped to it, so every row is that market's. if market["marketCode"] != "2056" { t.Errorf("market.marketCode = %#v, want the requested \"2056\"", market["marketCode"]) } @@ -725,21 +724,19 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { expect: "codes in market", }, { - // Without a market code the upstream widens the query to the whole - // district, and the answer can no longer say which market it is for. - name: "no market code", + // Present but empty would widen the query silently. + name: "an empty market code", mutate: func(ra map[string]any) { - delete(ra["market"].(map[string]any), "marketCode") + ra["market"].(map[string]any)["marketCode"] = "" }, - expect: "market code", + expect: "market.marketCode", }, { - // Present but empty names no market either. - name: "an empty market code", + name: "a market code that is not a string", mutate: func(ra map[string]any) { - ra["market"].(map[string]any)["marketCode"] = "" + ra["market"].(map[string]any)["marketCode"] = 2056 }, - expect: "market code", + expect: "market.marketCode", }, { // Outside the pack's Minimum/Maximum/Modal enum: no price would be @@ -907,3 +904,35 @@ func TestShippedMappingHonoursTheRequestedPriceFields(t *testing.T) { } } } + +// Without a market code the query is district-wide: no marketcode goes +// upstream, no single code is claimed, and each row names its own market. +func TestShippedMappingSearchesTheDistrictWithoutAMarketCode(t *testing.T) { + t.Parallel() + + var payload map[string]any + if err := json.Unmarshal([]byte(selectRequest), &payload); err != nil { + t.Fatalf("the fixture is not JSON: %v", err) + } + ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) + delete(ra["market"].(map[string]any), "marketCode") + request, _ := json.Marshal(payload) + + twoMarkets := strings.Replace(providerResponse, `"Market": "Kasdol APMC"`, `"Market": "Other APMC "`, 1) + query, answer := runShippedWith(t, string(request), twoMarkets) + + if query.Has("marketcode") { + t.Errorf("marketcode = %q was sent; district-wide must omit it", query.Get("marketcode")) + } + names := map[string]bool{} + for _, r := range resourcesOf(t, answer) { + market := r["resourceAttributes"].(map[string]any)["market"].(map[string]any) + if code, present := market["marketCode"]; present { + t.Errorf("market.marketCode = %#v; no single code applies district-wide", code) + } + names[market["marketName"].(string)] = true + } + if !names["Other APMC"] || len(names) < 2 { + t.Errorf("market names = %v, want rows from more than one market, trimmed", names) + } +} From e165500e32fa9f163d245cd3c67ebf6f3ed85b13 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 11:22:28 +0530 Subject: [PATCH 03/19] feat: require state, district, commodity and validity dates in mandi-price select [OpenAgriNet/network-adapter#107] State and district are checked in separate guards so the refusal names the missing one. validity.startsAt and validity.endsAt are mapped to the upstream's from_date and to_date, so both must be dates and the start must not be after the end; an empty or free-text value used to be sent upstream as "--" or crash the date reorder. Tests cover each mandatory field, Minimum alone, and all three price fields when none are given. Refs OpenAgriNet/network-adapter#97 --- .../agmarknet/mandi-price.select.yaml | 49 ++++++--- .../MandiPrice/mappings_test.go | 99 +++++++++++++++++++ 2 files changed, 136 insertions(+), 12 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 9042dd1b4..0131d8b32 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -67,19 +67,26 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Shape, not just presence. The pack describes district and state as - "name or governed code", so the names form is pack-legal -- and the - existence-only check passed it, after which it went to Agmarknet - verbatim as codes. Agmarknet answered nothing, and the caller got a - signed, spec-valid "no prices" for a market that had prices. - - Agmarknet wants a numeric district and a short alphabetic state (96, - CG), so a district that is not all digits or a state longer than four - letters is a name and is refused with the reason. */ - $match($ra.market.district, /^[0-9]+$/) - and $match($ra.market.state, /^[A-Za-z]{2,4}$/) + /* Shape, not just presence. The pack describes district as "name or governed + code", so the names form is pack-legal -- and an existence-only check passed it, + after which it went to Agmarknet verbatim as a code. Agmarknet answered nothing, + and the caller got a signed, spec-valid "no prices" for a market that had prices. + + Agmarknet wants a numeric district (96). The district is mandatory, with the + state and the commodity; only marketCode is optional. */ + $type($ra.market.district) = "string" + and $count($match($ra.market.district, /^[0-9]+$/)) > 0 ) - message: "this capability needs Agmarknet's codes in market: a numeric district and a short alphabetic state, not their names" + message: "this capability needs Agmarknet's codes in market: a numeric district, not a name" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + /* Same reasoning as the district: a short alphabetic state (CG), so one longer + than four letters is a name and is refused with the reason. */ + $type($ra.market.state) = "string" + and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 + ) + message: "this capability needs Agmarknet's codes in market: a short alphabetic state, not a name" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -109,6 +116,24 @@ required: $exists($ra.validity.startsAt) and $exists($ra.validity.endsAt) ) message: "this capability needs a validity window; it reports prices over a date range" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + /* Both ends are mandatory -- the upstream takes from_date and to_date -- so they + must also be dates: an empty or free-text value was reordered into "--" or crashed + the reorder. A date-time is accepted; its date part is what is sent. */ + $type($ra.validity.startsAt) = "string" + and $type($ra.validity.endsAt) = "string" + and $contains($ra.validity.startsAt, /^[0-9]{4}-[0-9]{2}-[0-9]{2}/) + and $contains($ra.validity.endsAt, /^[0-9]{4}-[0-9]{2}-[0-9]{2}/) + ) + message: "validity.startsAt and validity.endsAt must be dates (yyyy-MM-dd); the upstream takes them as from_date and to_date" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + $substring($ra.validity.startsAt, 0, 10) <= $substring($ra.validity.endsAt, 0, 10) + ) + message: "validity.startsAt must not be after validity.endsAt" # The upstream is a GET, so this object becomes the query string. The token is # not here and must never be: it comes from the adapter's authScheme query, diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index c6d409322..62e06802d 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -723,6 +723,61 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "codes in market", }, + { + // The upstream takes both ends as from_date and to_date, so each is + // mandatory and must be a date. + name: "no validity start", + mutate: func(ra map[string]any) { + delete(ra["validity"].(map[string]any), "startsAt") + }, + expect: "validity window", + }, + { + name: "no validity end", + mutate: func(ra map[string]any) { + delete(ra["validity"].(map[string]any), "endsAt") + }, + expect: "validity window", + }, + { + // Reordered into "--" and sent upstream before this was refused. + name: "an empty validity start", + mutate: func(ra map[string]any) { + ra["validity"].(map[string]any)["startsAt"] = "" + }, + expect: "must be dates", + }, + { + // Crashed the date reorder rather than being refused. + name: "validity that is not a date", + mutate: func(ra map[string]any) { + ra["validity"] = map[string]any{"startsAt": "abc", "endsAt": "xyz"} + }, + expect: "must be dates", + }, + { + name: "validity that ends before it starts", + mutate: func(ra map[string]any) { + ra["validity"] = map[string]any{"startsAt": "2025-08-21", "endsAt": "2025-08-20"} + }, + expect: "must not be after", + }, + { + // State, district and commodity are each mandatory; each is refused on + // its own, with a message that names it. + name: "no state", + mutate: func(ra map[string]any) { + delete(ra["market"].(map[string]any), "state") + }, + expect: "short alphabetic state", + }, + { + name: "no district", + mutate: func(ra map[string]any) { + delete(ra["market"].(map[string]any), "district") + }, + expect: "numeric district", + }, { // Present but empty would widen the query silently. name: "an empty market code", @@ -936,3 +991,47 @@ func TestShippedMappingSearchesTheDistrictWithoutAMarketCode(t *testing.T) { t.Errorf("market names = %v, want rows from more than one market, trimmed", names) } } + +// Minimum alone gives the minimum alone; nothing passed gives all three. +func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { + t.Parallel() + + minOnly := strings.Replace(selectRequest, + `"supportedPriceFields": ["Minimum", "Maximum", "Modal"]`, + `"supportedPriceFields": ["Minimum"]`, 1) + _, answer := runShippedWith(t, minOnly, providerResponse) + for _, r := range resourcesOf(t, answer) { + prices := r["resourceAttributes"].(map[string]any)["prices"].(map[string]any) + if _, ok := prices["minimum"]; !ok { + t.Error("prices.minimum is missing, and it is the field that was asked for") + } + for _, unasked := range []string{"maximum", "modal"} { + if _, present := prices[unasked]; present { + t.Errorf("prices.%s was returned though only Minimum was asked for", unasked) + } + } + } + + var payload map[string]any + if err := json.Unmarshal([]byte(selectRequest), &payload); err != nil { + t.Fatalf("the fixture is not JSON: %v", err) + } + ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) + delete(ra, "supportedPriceFields") + request, _ := json.Marshal(payload) + // The shared fixture's second row reports no Min or Max, so price it fully. + allPriced := strings.Replace(providerResponse, + `"Price Unit": "Rs./Qtl", + "Modal Price": "2050",`, + `"Max Price": "2100", "Min Price": "1900", "Price Unit": "Rs./Qtl", + "Modal Price": "2050",`, 1) + _, answer = runShippedWith(t, string(request), allPriced) + for _, r := range resourcesOf(t, answer) { + prices := r["resourceAttributes"].(map[string]any)["prices"].(map[string]any) + for _, field := range []string{"minimum", "maximum", "modal"} { + if _, ok := prices[field]; !ok { + t.Errorf("prices.%s is missing; with nothing asked for, all three are returned", field) + } + } + } +} From 238d1db9f8b8c35b7fdfbea1d66d0a8d9592b744 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 11:50:25 +0530 Subject: [PATCH 04/19] feat: match mandi-price marketName against the district's markets [OpenAgriNet/network-adapter#107] Agmarknet takes no market name, so a select with marketName and no marketCode queries the district and keeps only the named market's rows, matched trimmed and case-insensitively. A name that matches none of the markets the district reported is refused with a 400 asking for market.marketCode; a district with no rows at all is an empty answer. jsonmapper: a response-half $error starting with "[refused] " is now a 400 in the mapping's words rather than a 502, for refusals that can only be decided once the provider has answered. Other response failures stay 502. Refs OpenAgriNet/network-adapter#97 --- .../agmarknet/mandi-price.select.yaml | 22 +++- .../MandiPrice/mappings_test.go | 102 +++++++++++++++--- .../implementation/jsonmapper/jsonmapper.go | 10 ++ .../jsonmapper/jsonmapper_test.go | 23 ++++ 4 files changed, 144 insertions(+), 13 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 0131d8b32..a3cf2ac3f 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -306,7 +306,27 @@ response: | or ("Maximum" in $fields and $exists($priced($r.`Max Price`))) or ("Modal" in $fields and $exists($priced($r.`Modal Price`)))) }; - $usable := $filter($records, $conformant); + /* A NAMED MARKET WITHOUT A CODE. Agmarknet takes no market name, so the + query went out district-wide and the answer is that district's markets. + Only the asked market's rows are kept, matched trimmed and + case-insensitively because Agmarknet pads names ("Karjat(Rashin) "). + + No match while the district did report rows means the name could not be + placed -- misspelt against Agmarknet, or a market that reported nothing + for these dates -- so it is refused rather than answered with another + market's prices or a "no prices" that may be untrue. A district with no + rows at all is a genuine empty answer. With a code, nothing is filtered: + the query was already that market's. */ + $askedName := $exists($ra.market.marketCode) ? undefined : $ra.market.marketName; + $sameName := function($a, $b) { $lowercase($trim($a)) = $lowercase($trim($b)) }; + $inMarket := $exists($askedName) + ? $filter($records, function($r) { $sameName($r.Market, $askedName) }) + : $records; + $exists($askedName) and $count($records) > 0 and $count($inMarket) = 0 + ? $error("[refused] marketName \"" & $askedName & "\" matched no market in district " & $ra.market.district + & " for these dates; market name alone is not enough, send market.marketCode to proceed"); + + $usable := $filter($inMarket, $conformant); { "context": { diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 62e06802d..e1be5afd6 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -11,6 +11,7 @@ package MandiPrice_test import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -166,6 +167,25 @@ func runShipped(t *testing.T, request string) (url.Values, map[string]any) { func runShippedWith(t *testing.T, request, providerBody string) (url.Values, map[string]any) { t.Helper() + gotQuery, body, err := runShippedErr(t, request, providerBody) + if err != nil { + t.Fatalf("Run() returned an unexpected error: %v", err) + } + if len(body) == 0 { + t.Fatal("the step produced no answer") + } + var answer map[string]any + if err := json.Unmarshal(body, &answer); err != nil { + t.Fatalf("the answer is not JSON: %v\n%s", err, body) + } + return gotQuery, answer +} + +// runShippedErr is runShippedWith without the failure handling, for refusals +// that can only be decided once the provider has answered. +func runShippedErr(t *testing.T, request, providerBody string) (url.Values, []byte, error) { + t.Helper() + mappings := serveMappings(t) defer mappings.Close() @@ -208,17 +228,8 @@ func runShippedWith(t *testing.T, request, providerBody string) (url.Values, map defer closeStep() stepCtx := &model.StepContext{Context: t.Context(), OwnSubscriberID: "oan.test", Body: []byte(request)} - if err := step.Run(stepCtx); err != nil { - t.Fatalf("Run() returned an unexpected error: %v", err) - } - if len(stepCtx.ResponseBody) == 0 { - t.Fatal("the step produced no answer") - } - var answer map[string]any - if err := json.Unmarshal(stepCtx.ResponseBody, &answer); err != nil { - t.Fatalf("the answer is not JSON: %v\n%s", err, stepCtx.ResponseBody) - } - return gotQuery, answer + err = step.Run(stepCtx) + return gotQuery, stepCtx.ResponseBody, err } func TestShippedMappingServesARealSelect(t *testing.T) { @@ -960,7 +971,7 @@ func TestShippedMappingHonoursTheRequestedPriceFields(t *testing.T) { } } -// Without a market code the query is district-wide: no marketcode goes +// Without a market code or name the query is district-wide: no marketcode goes // upstream, no single code is claimed, and each row names its own market. func TestShippedMappingSearchesTheDistrictWithoutAMarketCode(t *testing.T) { t.Parallel() @@ -970,7 +981,9 @@ func TestShippedMappingSearchesTheDistrictWithoutAMarketCode(t *testing.T) { t.Fatalf("the fixture is not JSON: %v", err) } ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) + // Neither a code nor a name: the whole district is what was asked for. delete(ra["market"].(map[string]any), "marketCode") + delete(ra["market"].(map[string]any), "marketName") request, _ := json.Marshal(payload) twoMarkets := strings.Replace(providerResponse, `"Market": "Kasdol APMC"`, `"Market": "Other APMC "`, 1) @@ -1035,3 +1048,68 @@ func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { } } } + +// withMarketName is the fixture with marketCode removed and marketName set. +func withMarketName(t *testing.T, name string) string { + t.Helper() + var payload map[string]any + if err := json.Unmarshal([]byte(selectRequest), &payload); err != nil { + t.Fatalf("the fixture is not JSON: %v", err) + } + ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) + market := ra["market"].(map[string]any) + delete(market, "marketCode") + market["marketName"] = name + request, _ := json.Marshal(payload) + return string(request) +} + +// A market name without a code: Agmarknet takes no name, so the district's +// markets come back and only the named one's rows are kept -- matched trimmed +// and case-insensitively, because Agmarknet pads its names. +func TestShippedMappingKeepsOnlyTheNamedMarket(t *testing.T) { + t.Parallel() + + twoMarkets := strings.Replace(providerResponse, `"Market": "Kasdol APMC"`, `"Market": "Other APMC"`, 1) + query, answer := runShippedWith(t, withMarketName(t, " kasdol APMC "), twoMarkets) + + if query.Has("marketcode") { + t.Errorf("marketcode = %q was sent; only a name was given", query.Get("marketcode")) + } + rows := resourcesOf(t, answer) + if len(rows) == 0 { + t.Fatal("no rows; the named market reported one") + } + for _, r := range rows { + market := r["resourceAttributes"].(map[string]any)["market"].(map[string]any) + if market["marketName"] != "Kasdol APMC" { + t.Errorf("marketName = %#v; only the named market's rows should be returned", market["marketName"]) + } + } +} + +// A name that matches none of the markets the district reported is refused, +// as a 400 the caller can act on: send the code. +func TestShippedMappingRefusesAMarketNameItCannotPlace(t *testing.T) { + t.Parallel() + + _, _, err := runShippedErr(t, withMarketName(t, "Nowhere APMC"), providerResponse) + var coded *model.CodedErr + if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadRequest { + t.Fatalf("error = %v, want a 400", err) + } + if !strings.Contains(err.Error(), "send market.marketCode to proceed") { + t.Errorf("error = %q, want it to ask for the market code", err) + } +} + +// A district that reported nothing at all is a genuine empty answer; the name +// is not blamed for it. +func TestShippedMappingAnswersEmptyWhenTheDistrictReportsNothing(t *testing.T) { + t.Parallel() + + _, answer := runShippedWith(t, withMarketName(t, "Kasdol APMC"), "[]") + if rows := resourcesOf(t, answer); len(rows) != 0 { + t.Errorf("rows = %d, want none", len(rows)) + } +} diff --git a/pkg/plugin/implementation/jsonmapper/jsonmapper.go b/pkg/plugin/implementation/jsonmapper/jsonmapper.go index c86982de1..8f3273699 100644 --- a/pkg/plugin/implementation/jsonmapper/jsonmapper.go +++ b/pkg/plugin/implementation/jsonmapper/jsonmapper.go @@ -44,6 +44,13 @@ const ( // rather than a fault of this adapter. const codeAdaptationFailed = "SCH_SCHEMA_ADAPTATION_FAILED" +// refusedMarker opens a $error() message by which a response half refuses the +// REQUEST rather than failing on the provider's answer. Some refusals can only +// be decided once the answer is in -- a market name that matches none of the +// district's markets the upstream returned -- and they are the caller's to fix, +// so they are reported as the preconditions are: a 400 in the mapping's words. +const refusedMarker = "[refused] " + // mappingFile is the published form of a mapping: one binding-action, both // directions. // @@ -651,6 +658,9 @@ func (m *Mapper) evaluate(ctx context.Context, mapping *compiledMapping, mapping log.Errorf(ctx, err, "JSON mapping %s %s half failed to evaluate: %v", mappingRef, direction, err) wrapped := fmt.Errorf("mapping %q %s half could not be applied: %w", mappingRef, direction, err) if direction == definition.DirectionResponse { + if at := strings.Index(err.Error(), refusedMarker); at >= 0 { + return nil, model.NewBadReqErr("", errors.New(err.Error()[at+len(refusedMarker):])) + } // The input here is the PROVIDER's answer, not the caller's // request. A provider that changed shape, or a bug in the response // half, is nothing the caller did -- reporting 400 sends them off diff --git a/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go b/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go index 1fea09178..042d3a084 100644 --- a/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go +++ b/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go @@ -849,6 +849,29 @@ func TestTransformBlamesTheRightPartyForEachDirection(t *testing.T) { } } +// A response half that refuses the request with $error("[refused] ...") is +// the caller's to fix, so it is a 400 in the mapping's words, not a 502. +func TestTransformLetsTheResponseHalfRefuseTheRequest(t *testing.T) { + t.Parallel() + + refusing := "request: |\n {}\nresponse: |\n $error(\"[refused] send market.marketCode to proceed\")\n" + srv := newMappingServer(t, refusing, nil) + defer srv.Close() + + _, err := newTestMapper(t).Transform(context.Background(), srv.URL+"/refusing.yaml", + definition.DirectionResponse, map[string]any{"response": []any{}}) + var coded *model.CodedErr + if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadRequest { + t.Fatalf("response refusal gave %v, want a 400", err) + } + if err.Error() != "send market.marketCode to proceed" && !strings.HasSuffix(err.Error(), "send market.marketCode to proceed") { + t.Errorf("error = %q, want the mapping's own message", err) + } + if strings.Contains(err.Error(), refusedMarker) || strings.Contains(err.Error(), "D3137") { + t.Errorf("error = %q leaks the marker or the engine code", err) + } +} + // --- concurrency ------------------------------------------------------------ // Every inbound request shares one mapper, so the cache is read and written From 0306f9bc6891c374759063ec14c497f7c359f4dd Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 12:03:29 +0530 Subject: [PATCH 05/19] revert: keep jsonmapper unchanged; report the unplaceable marketName as the response half's 502 [OpenAgriNet/network-adapter#107] The "[refused]" marker in jsonmapper is removed, so jsonmapper is as on development. A marketName that matches none of the district's markets is still refused with a message asking for market.marketCode; it is raised from the response half and so reported as a 502. Refs OpenAgriNet/network-adapter#97 --- .../agmarknet/mandi-price.select.yaml | 7 ++++-- .../MandiPrice/mappings_test.go | 9 ++++---- .../implementation/jsonmapper/jsonmapper.go | 10 -------- .../jsonmapper/jsonmapper_test.go | 23 ------------------- 4 files changed, 10 insertions(+), 39 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index a3cf2ac3f..d9f8d4306 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -316,14 +316,17 @@ response: | for these dates -- so it is refused rather than answered with another market's prices or a "no prices" that may be untrue. A district with no rows at all is a genuine empty answer. With a code, nothing is filtered: - the query was already that market's. */ + the query was already that market's. + + Raised from the response half, so jsonmapper reports it as a 502; the + message still names the fix. */ $askedName := $exists($ra.market.marketCode) ? undefined : $ra.market.marketName; $sameName := function($a, $b) { $lowercase($trim($a)) = $lowercase($trim($b)) }; $inMarket := $exists($askedName) ? $filter($records, function($r) { $sameName($r.Market, $askedName) }) : $records; $exists($askedName) and $count($records) > 0 and $count($inMarket) = 0 - ? $error("[refused] marketName \"" & $askedName & "\" matched no market in district " & $ra.market.district + ? $error("marketName \"" & $askedName & "\" matched no market in district " & $ra.market.district & " for these dates; market name alone is not enough, send market.marketCode to proceed"); $usable := $filter($inMarket, $conformant); diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index e1be5afd6..07b9427de 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -1088,15 +1088,16 @@ func TestShippedMappingKeepsOnlyTheNamedMarket(t *testing.T) { } } -// A name that matches none of the markets the district reported is refused, -// as a 400 the caller can act on: send the code. +// A name that matches none of the markets the district reported is refused. +// It is decided in the response half, which jsonmapper reports as a 502, but +// the message still tells the caller the fix: send the code. func TestShippedMappingRefusesAMarketNameItCannotPlace(t *testing.T) { t.Parallel() _, _, err := runShippedErr(t, withMarketName(t, "Nowhere APMC"), providerResponse) var coded *model.CodedErr - if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadRequest { - t.Fatalf("error = %v, want a 400", err) + if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadGateway { + t.Fatalf("error = %v, want the response half's 502", err) } if !strings.Contains(err.Error(), "send market.marketCode to proceed") { t.Errorf("error = %q, want it to ask for the market code", err) diff --git a/pkg/plugin/implementation/jsonmapper/jsonmapper.go b/pkg/plugin/implementation/jsonmapper/jsonmapper.go index 8f3273699..c86982de1 100644 --- a/pkg/plugin/implementation/jsonmapper/jsonmapper.go +++ b/pkg/plugin/implementation/jsonmapper/jsonmapper.go @@ -44,13 +44,6 @@ const ( // rather than a fault of this adapter. const codeAdaptationFailed = "SCH_SCHEMA_ADAPTATION_FAILED" -// refusedMarker opens a $error() message by which a response half refuses the -// REQUEST rather than failing on the provider's answer. Some refusals can only -// be decided once the answer is in -- a market name that matches none of the -// district's markets the upstream returned -- and they are the caller's to fix, -// so they are reported as the preconditions are: a 400 in the mapping's words. -const refusedMarker = "[refused] " - // mappingFile is the published form of a mapping: one binding-action, both // directions. // @@ -658,9 +651,6 @@ func (m *Mapper) evaluate(ctx context.Context, mapping *compiledMapping, mapping log.Errorf(ctx, err, "JSON mapping %s %s half failed to evaluate: %v", mappingRef, direction, err) wrapped := fmt.Errorf("mapping %q %s half could not be applied: %w", mappingRef, direction, err) if direction == definition.DirectionResponse { - if at := strings.Index(err.Error(), refusedMarker); at >= 0 { - return nil, model.NewBadReqErr("", errors.New(err.Error()[at+len(refusedMarker):])) - } // The input here is the PROVIDER's answer, not the caller's // request. A provider that changed shape, or a bug in the response // half, is nothing the caller did -- reporting 400 sends them off diff --git a/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go b/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go index 042d3a084..1fea09178 100644 --- a/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go +++ b/pkg/plugin/implementation/jsonmapper/jsonmapper_test.go @@ -849,29 +849,6 @@ func TestTransformBlamesTheRightPartyForEachDirection(t *testing.T) { } } -// A response half that refuses the request with $error("[refused] ...") is -// the caller's to fix, so it is a 400 in the mapping's words, not a 502. -func TestTransformLetsTheResponseHalfRefuseTheRequest(t *testing.T) { - t.Parallel() - - refusing := "request: |\n {}\nresponse: |\n $error(\"[refused] send market.marketCode to proceed\")\n" - srv := newMappingServer(t, refusing, nil) - defer srv.Close() - - _, err := newTestMapper(t).Transform(context.Background(), srv.URL+"/refusing.yaml", - definition.DirectionResponse, map[string]any{"response": []any{}}) - var coded *model.CodedErr - if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadRequest { - t.Fatalf("response refusal gave %v, want a 400", err) - } - if err.Error() != "send market.marketCode to proceed" && !strings.HasSuffix(err.Error(), "send market.marketCode to proceed") { - t.Errorf("error = %q, want the mapping's own message", err) - } - if strings.Contains(err.Error(), refusedMarker) || strings.Contains(err.Error(), "D3137") { - t.Errorf("error = %q leaks the marker or the engine code", err) - } -} - // --- concurrency ------------------------------------------------------------ // Every inbound request shares one mapper, so the cache is read and written From 4efcfe85bfaf692fb2fd2b4ac5d68b3ab54b96a3 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 12:24:58 +0530 Subject: [PATCH 06/19] fix: refuse mandi-price marketName without marketCode; shorten comments [OpenAgriNet/network-adapter#107] Agmarknet takes no market name, so a name without a code would answer for the whole district. It is now refused before Agmarknet is called with a 400 that asks for market.marketCode, replacing the response-side name filter and its 502. Comments added by this change are kept to three lines. Refs OpenAgriNet/network-adapter#97 --- .../agmarknet/mandi-price.select.yaml | 65 ++++------- .../MandiPrice/mappings_test.go | 108 ++++-------------- 2 files changed, 40 insertions(+), 133 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index d9f8d4306..93bbdb5fe 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -67,13 +67,8 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Shape, not just presence. The pack describes district as "name or governed - code", so the names form is pack-legal -- and an existence-only check passed it, - after which it went to Agmarknet verbatim as a code. Agmarknet answered nothing, - and the caller got a signed, spec-valid "no prices" for a market that had prices. - - Agmarknet wants a numeric district (96). The district is mandatory, with the - state and the commodity; only marketCode is optional. */ + /* Mandatory, and a code: Agmarknet wants a numeric district (96). The pack + allows a name, which Agmarknet answers with nothing. */ $type($ra.market.district) = "string" and $count($match($ra.market.district, /^[0-9]+$/)) > 0 ) @@ -81,8 +76,7 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Same reasoning as the district: a short alphabetic state (CG), so one longer - than four letters is a name and is refused with the reason. */ + /* Mandatory, and a code: a short alphabetic state (CG), not a name. */ $type($ra.market.state) = "string" and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 ) @@ -90,9 +84,8 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* market.marketCode is optional. Absent, Agmarknet answers for the whole district. - Present, it is used, so it must be a non-empty string: an empty one would widen - the query silently while the caller believes it named a market. */ + /* Optional; absent means the whole district. When given it must be a + non-empty string, or the query widens silently. */ $exists($ra.market.marketCode) ? ($type($ra.market.marketCode) = "string" and $ra.market.marketCode != "") : true @@ -101,9 +94,16 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* The pack's enum is Minimum, Maximum, Modal. Absent means all three, so only a - present value is checked: anything outside the enum would otherwise answer with - rows that carry no price. (An empty list reads as absent in JSONata.) */ + /* Agmarknet takes no market name, so a name alone would return the whole + district. Refused: send the code, or neither for a district search. */ + $not($exists($ra.market.marketName) and $not($exists($ra.market.marketCode))) + ) + message: "market.marketName alone is not enough: send market.marketCode for that market, or omit marketName to search the whole district" + - check: | + ( + $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; + /* Only the pack's Minimum, Maximum, Modal. Absent (or empty) means all + three; anything else would return rows with no price. */ $exists($ra.supportedPriceFields) ? $count($ra.supportedPriceFields[$ in ["Minimum", "Maximum", "Modal"]]) = $count($ra.supportedPriceFields) @@ -119,9 +119,8 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Both ends are mandatory -- the upstream takes from_date and to_date -- so they - must also be dates: an empty or free-text value was reordered into "--" or crashed - the reorder. A date-time is accepted; its date part is what is sent. */ + /* Sent as from_date and to_date, so both must be dates (a date-time is + fine). Empty or free text used to go upstream as "--" or crash. */ $type($ra.validity.startsAt) = "string" and $type($ra.validity.endsAt) = "string" and $contains($ra.validity.startsAt, /^[0-9]{4}-[0-9]{2}-[0-9]{2}/) @@ -306,30 +305,7 @@ response: | or ("Maximum" in $fields and $exists($priced($r.`Max Price`))) or ("Modal" in $fields and $exists($priced($r.`Modal Price`)))) }; - /* A NAMED MARKET WITHOUT A CODE. Agmarknet takes no market name, so the - query went out district-wide and the answer is that district's markets. - Only the asked market's rows are kept, matched trimmed and - case-insensitively because Agmarknet pads names ("Karjat(Rashin) "). - - No match while the district did report rows means the name could not be - placed -- misspelt against Agmarknet, or a market that reported nothing - for these dates -- so it is refused rather than answered with another - market's prices or a "no prices" that may be untrue. A district with no - rows at all is a genuine empty answer. With a code, nothing is filtered: - the query was already that market's. - - Raised from the response half, so jsonmapper reports it as a 502; the - message still names the fix. */ - $askedName := $exists($ra.market.marketCode) ? undefined : $ra.market.marketName; - $sameName := function($a, $b) { $lowercase($trim($a)) = $lowercase($trim($b)) }; - $inMarket := $exists($askedName) - ? $filter($records, function($r) { $sameName($r.Market, $askedName) }) - : $records; - $exists($askedName) and $count($records) > 0 and $count($inMarket) = 0 - ? $error("marketName \"" & $askedName & "\" matched no market in district " & $ra.market.district - & " for these dates; market name alone is not enough, send market.marketCode to proceed"); - - $usable := $filter($inMarket, $conformant); + $usable := $filter($records, $conformant); { "context": { @@ -409,9 +385,8 @@ response: | "commodityGroup": $r.Group, "variety": $r.Variety, "grade": $r.Grade, - /* From the RECORD, except marketCode: the upstream reports none, so it is the - requested one, and only when one was requested. District-wide there is no - single code, the key is omitted and each row names its own market. */ + /* From the record, except marketCode: Agmarknet reports none, so it is the + requested one, and omitted district-wide. marketName is trimmed. */ "market": { "marketCode": $ra.market.marketCode, "marketName": $trim($r.Market), diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 07b9427de..65a54dd87 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -11,7 +11,6 @@ package MandiPrice_test import ( "context" "encoding/json" - "errors" "fmt" "net/http" "net/http/httptest" @@ -167,25 +166,6 @@ func runShipped(t *testing.T, request string) (url.Values, map[string]any) { func runShippedWith(t *testing.T, request, providerBody string) (url.Values, map[string]any) { t.Helper() - gotQuery, body, err := runShippedErr(t, request, providerBody) - if err != nil { - t.Fatalf("Run() returned an unexpected error: %v", err) - } - if len(body) == 0 { - t.Fatal("the step produced no answer") - } - var answer map[string]any - if err := json.Unmarshal(body, &answer); err != nil { - t.Fatalf("the answer is not JSON: %v\n%s", err, body) - } - return gotQuery, answer -} - -// runShippedErr is runShippedWith without the failure handling, for refusals -// that can only be decided once the provider has answered. -func runShippedErr(t *testing.T, request, providerBody string) (url.Values, []byte, error) { - t.Helper() - mappings := serveMappings(t) defer mappings.Close() @@ -228,8 +208,17 @@ func runShippedErr(t *testing.T, request, providerBody string) (url.Values, []by defer closeStep() stepCtx := &model.StepContext{Context: t.Context(), OwnSubscriberID: "oan.test", Body: []byte(request)} - err = step.Run(stepCtx) - return gotQuery, stepCtx.ResponseBody, err + if err := step.Run(stepCtx); err != nil { + t.Fatalf("Run() returned an unexpected error: %v", err) + } + if len(stepCtx.ResponseBody) == 0 { + t.Fatal("the step produced no answer") + } + var answer map[string]any + if err := json.Unmarshal(stepCtx.ResponseBody, &answer); err != nil { + t.Fatalf("the answer is not JSON: %v\n%s", err, stepCtx.ResponseBody) + } + return gotQuery, answer } func TestShippedMappingServesARealSelect(t *testing.T) { @@ -789,6 +778,15 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "numeric district", }, + { + // Agmarknet takes no name, so a name alone would answer for the + // whole district; refused before the call. + name: "a market name without a code", + mutate: func(ra map[string]any) { + delete(ra["market"].(map[string]any), "marketCode") + }, + expect: "marketName alone is not enough", + }, { // Present but empty would widen the query silently. name: "an empty market code", @@ -1048,69 +1046,3 @@ func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { } } } - -// withMarketName is the fixture with marketCode removed and marketName set. -func withMarketName(t *testing.T, name string) string { - t.Helper() - var payload map[string]any - if err := json.Unmarshal([]byte(selectRequest), &payload); err != nil { - t.Fatalf("the fixture is not JSON: %v", err) - } - ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) - market := ra["market"].(map[string]any) - delete(market, "marketCode") - market["marketName"] = name - request, _ := json.Marshal(payload) - return string(request) -} - -// A market name without a code: Agmarknet takes no name, so the district's -// markets come back and only the named one's rows are kept -- matched trimmed -// and case-insensitively, because Agmarknet pads its names. -func TestShippedMappingKeepsOnlyTheNamedMarket(t *testing.T) { - t.Parallel() - - twoMarkets := strings.Replace(providerResponse, `"Market": "Kasdol APMC"`, `"Market": "Other APMC"`, 1) - query, answer := runShippedWith(t, withMarketName(t, " kasdol APMC "), twoMarkets) - - if query.Has("marketcode") { - t.Errorf("marketcode = %q was sent; only a name was given", query.Get("marketcode")) - } - rows := resourcesOf(t, answer) - if len(rows) == 0 { - t.Fatal("no rows; the named market reported one") - } - for _, r := range rows { - market := r["resourceAttributes"].(map[string]any)["market"].(map[string]any) - if market["marketName"] != "Kasdol APMC" { - t.Errorf("marketName = %#v; only the named market's rows should be returned", market["marketName"]) - } - } -} - -// A name that matches none of the markets the district reported is refused. -// It is decided in the response half, which jsonmapper reports as a 502, but -// the message still tells the caller the fix: send the code. -func TestShippedMappingRefusesAMarketNameItCannotPlace(t *testing.T) { - t.Parallel() - - _, _, err := runShippedErr(t, withMarketName(t, "Nowhere APMC"), providerResponse) - var coded *model.CodedErr - if !errors.As(err, &coded) || coded.HTTPStatus() != http.StatusBadGateway { - t.Fatalf("error = %v, want the response half's 502", err) - } - if !strings.Contains(err.Error(), "send market.marketCode to proceed") { - t.Errorf("error = %q, want it to ask for the market code", err) - } -} - -// A district that reported nothing at all is a genuine empty answer; the name -// is not blamed for it. -func TestShippedMappingAnswersEmptyWhenTheDistrictReportsNothing(t *testing.T) { - t.Parallel() - - _, answer := runShippedWith(t, withMarketName(t, "Kasdol APMC"), "[]") - if rows := resourcesOf(t, answer); len(rows) != 0 { - t.Errorf("rows = %d, want none", len(rows)) - } -} From 71520ec70deb488a0c56d92aaef9736efbd0b56e Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 14:52:41 +0530 Subject: [PATCH 07/19] fix(mandi-price): drop guards the pack's schema already enforces [OpenAgriNet/network-adapter#107] The schema validator already refuses an unknown or empty supportedPriceFields, an empty or non-string marketCode, a validity that is not a date-time, and a commodity without a code. Keep only what the pack does not cover. --- .../agmarknet/mandi-price.select.yaml | 38 ++---------------- .../MandiPrice/mappings_test.go | 40 ------------------- 2 files changed, 4 insertions(+), 74 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 93bbdb5fe..b9841d44f 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -49,6 +49,9 @@ # # Refusing here names what is missing. Sending it anyway earns a 400 from # Agmarknet, or worse an empty result that reads as "no prices". +# Not repeated here, the pack's validator already refuses them: an unknown or empty +# supportedPriceFields, an empty or non-string marketCode, a validity that is not +# a date-time, and no supportedCommodities or code. required: - check: | ( @@ -60,8 +63,7 @@ required: what it asked -- the same failure capabilitybinding refuses at the commitment level, where guessing would silently serve part of a request. */ - $exists($ra.supportedCommodities[0].code) - and $count($ra.supportedCommodities) = 1 + $count($ra.supportedCommodities) = 1 ) message: "this capability needs exactly one commodity code in supportedCommodities; send several requests rather than have all but the first dropped" - check: | @@ -81,16 +83,6 @@ required: and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 ) message: "this capability needs Agmarknet's codes in market: a short alphabetic state, not a name" - - check: | - ( - $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Optional; absent means the whole district. When given it must be a - non-empty string, or the query widens silently. */ - $exists($ra.market.marketCode) - ? ($type($ra.market.marketCode) = "string" and $ra.market.marketCode != "") - : true - ) - message: "market.marketCode, when given, must be a non-empty string; omit it to search the whole district" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -99,34 +91,12 @@ required: $not($exists($ra.market.marketName) and $not($exists($ra.market.marketCode))) ) message: "market.marketName alone is not enough: send market.marketCode for that market, or omit marketName to search the whole district" - - check: | - ( - $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Only the pack's Minimum, Maximum, Modal. Absent (or empty) means all - three; anything else would return rows with no price. */ - $exists($ra.supportedPriceFields) - ? $count($ra.supportedPriceFields[$ in ["Minimum", "Maximum", "Modal"]]) - = $count($ra.supportedPriceFields) - : true - ) - message: "supportedPriceFields must list only Minimum, Maximum or Modal" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; $exists($ra.validity.startsAt) and $exists($ra.validity.endsAt) ) message: "this capability needs a validity window; it reports prices over a date range" - - check: | - ( - $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Sent as from_date and to_date, so both must be dates (a date-time is - fine). Empty or free text used to go upstream as "--" or crash. */ - $type($ra.validity.startsAt) = "string" - and $type($ra.validity.endsAt) = "string" - and $contains($ra.validity.startsAt, /^[0-9]{4}-[0-9]{2}-[0-9]{2}/) - and $contains($ra.validity.endsAt, /^[0-9]{4}-[0-9]{2}-[0-9]{2}/) - ) - message: "validity.startsAt and validity.endsAt must be dates (yyyy-MM-dd); the upstream takes them as from_date and to_date" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 65a54dd87..9cc516c67 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -739,22 +739,6 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "validity window", }, - { - // Reordered into "--" and sent upstream before this was refused. - name: "an empty validity start", - mutate: func(ra map[string]any) { - ra["validity"].(map[string]any)["startsAt"] = "" - }, - expect: "must be dates", - }, - { - // Crashed the date reorder rather than being refused. - name: "validity that is not a date", - mutate: func(ra map[string]any) { - ra["validity"] = map[string]any{"startsAt": "abc", "endsAt": "xyz"} - }, - expect: "must be dates", - }, { name: "validity that ends before it starts", mutate: func(ra map[string]any) { @@ -787,30 +771,6 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "marketName alone is not enough", }, - { - // Present but empty would widen the query silently. - name: "an empty market code", - mutate: func(ra map[string]any) { - ra["market"].(map[string]any)["marketCode"] = "" - }, - expect: "market.marketCode", - }, - { - name: "a market code that is not a string", - mutate: func(ra map[string]any) { - ra["market"].(map[string]any)["marketCode"] = 2056 - }, - expect: "market.marketCode", - }, - { - // Outside the pack's Minimum/Maximum/Modal enum: no price would be - // selected, so the row would carry no price. - name: "a price field the pack does not define", - mutate: func(ra map[string]any) { - ra["supportedPriceFields"] = []any{"Average"} - }, - expect: "supportedPriceFields", - }, { // Everything downstream reads supportedCommodities[0], so this // used to be queried for Paddy alone and answered confidently. From 56c68196b145227f326415321e6ecdb65e05d005 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 15:19:04 +0530 Subject: [PATCH 08/19] refactor(mandi-price): drop redundant logic in the select mapping [OpenAgriNet/network-adapter#107] - state/district guards: $exists instead of a type check the schema covers - request: marketcode set directly; JSONata omits it when absent - response: @context read from $ra rather than the full path again - remove the schema-note comment --- .../agmarknet/mandi-price.select.yaml | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index b9841d44f..b2a27d9dc 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -49,9 +49,6 @@ # # Refusing here names what is missing. Sending it anyway earns a 400 from # Agmarknet, or worse an empty result that reads as "no prices". -# Not repeated here, the pack's validator already refuses them: an unknown or empty -# supportedPriceFields, an empty or non-string marketCode, a validity that is not -# a date-time, and no supportedCommodities or code. required: - check: | ( @@ -71,7 +68,7 @@ required: $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; /* Mandatory, and a code: Agmarknet wants a numeric district (96). The pack allows a name, which Agmarknet answers with nothing. */ - $type($ra.market.district) = "string" + $exists($ra.market.district) and $count($match($ra.market.district, /^[0-9]+$/)) > 0 ) message: "this capability needs Agmarknet's codes in market: a numeric district, not a name" @@ -79,7 +76,7 @@ required: ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; /* Mandatory, and a code: a short alphabetic state (CG), not a name. */ - $type($ra.market.state) = "string" + $exists($ra.market.state) and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 ) message: "this capability needs Agmarknet's codes in market: a short alphabetic state, not a name" @@ -122,17 +119,15 @@ request: | $substring($iso, 8, 2) & "-" & $substring($iso, 5, 2) & "-" & $substring($iso, 0, 4) }; - $base := { + { "statecode": $ra.market.state, "districtcode": $ra.market.district, "commoditycode": $ra.supportedCommodities[0].code, "from_date": $ddmmyyyy($ra.validity.startsAt), - "to_date": $ddmmyyyy($ra.validity.endsAt) - }; - - $exists($ra.market.marketCode) - ? $merge([$base, {"marketcode": $ra.market.marketCode}]) - : $base + "to_date": $ddmmyyyy($ra.validity.endsAt), + /* Dropped when absent: JSONata omits a key whose value is undefined. */ + "marketcode": $ra.market.marketCode + } ) # One resource per price record, in Direct mode. @@ -158,8 +153,8 @@ response: | mapping that hardcodes it has to be reissued whenever the pack URL moves, and it can disagree with what the request actually declared. Backticks because @ is an operator in JSONata. */ - $ctx := beckn.message.contract.commitments[0].resources[0].resourceAttributes.`@context`; $ra := $selected.resources[0].resourceAttributes; + $ctx := $ra.`@context`; /* dd-MM-yyyy back to ISO, so the answer speaks the pack's date format rather than the upstream's. */ From a0f52cea60912aeef09d53116170e2ea1782e4f0 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Wed, 4 Nov 2026 15:39:48 +0530 Subject: [PATCH 09/19] fix(mandi-price): state presence only, clearer market name message [OpenAgriNet/network-adapter#107] - market.state: keep the presence check, drop the code-shape regex - reword the marketName-without-marketCode refusal --- config/mappings/agmarknet/mandi-price.select.yaml | 8 +++----- pkg/plugin/implementation/MandiPrice/mappings_test.go | 4 ++-- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index b2a27d9dc..313ff2358 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -75,11 +75,10 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Mandatory, and a code: a short alphabetic state (CG), not a name. */ + /* Mandatory: Agmarknet refuses a call without statecode. */ $exists($ra.market.state) - and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 ) - message: "this capability needs Agmarknet's codes in market: a short alphabetic state, not a name" + message: "this capability needs market.state, Agmarknet's state code" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -87,7 +86,7 @@ required: district. Refused: send the code, or neither for a district search. */ $not($exists($ra.market.marketName) and $not($exists($ra.market.marketCode))) ) - message: "market.marketName alone is not enough: send market.marketCode for that market, or omit marketName to search the whole district" + message: "market.marketName alone is insufficient; provide market.marketCode or omit market.marketName for district-wide search." - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; @@ -125,7 +124,6 @@ request: | "commoditycode": $ra.supportedCommodities[0].code, "from_date": $ddmmyyyy($ra.validity.startsAt), "to_date": $ddmmyyyy($ra.validity.endsAt), - /* Dropped when absent: JSONata omits a key whose value is undefined. */ "marketcode": $ra.market.marketCode } ) diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 9cc516c67..724d77673 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -753,7 +753,7 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { mutate: func(ra map[string]any) { delete(ra["market"].(map[string]any), "state") }, - expect: "short alphabetic state", + expect: "market.state", }, { name: "no district", @@ -769,7 +769,7 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { mutate: func(ra map[string]any) { delete(ra["market"].(map[string]any), "marketCode") }, - expect: "marketName alone is not enough", + expect: "marketName alone is insufficient", }, { // Everything downstream reads supportedCommodities[0], so this From a44874cd1be68816d68f97eca9c68c1e90ee5fd8 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 11:24:26 +0530 Subject: [PATCH 10/19] revert(mandi-price): keep the request $base and $ctx as on development [OpenAgriNet/network-adapter#107] Not needed for #107 and not broken, so left unchanged. --- config/mappings/agmarknet/mandi-price.select.yaml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 313ff2358..9dee29031 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -118,14 +118,17 @@ request: | $substring($iso, 8, 2) & "-" & $substring($iso, 5, 2) & "-" & $substring($iso, 0, 4) }; - { + $base := { "statecode": $ra.market.state, "districtcode": $ra.market.district, "commoditycode": $ra.supportedCommodities[0].code, "from_date": $ddmmyyyy($ra.validity.startsAt), - "to_date": $ddmmyyyy($ra.validity.endsAt), - "marketcode": $ra.market.marketCode - } + "to_date": $ddmmyyyy($ra.validity.endsAt) + }; + + $exists($ra.market.marketCode) + ? $merge([$base, {"marketcode": $ra.market.marketCode}]) + : $base ) # One resource per price record, in Direct mode. @@ -151,8 +154,8 @@ response: | mapping that hardcodes it has to be reissued whenever the pack URL moves, and it can disagree with what the request actually declared. Backticks because @ is an operator in JSONata. */ + $ctx := beckn.message.contract.commitments[0].resources[0].resourceAttributes.`@context`; $ra := $selected.resources[0].resourceAttributes; - $ctx := $ra.`@context`; /* dd-MM-yyyy back to ISO, so the answer speaks the pack's date format rather than the upstream's. */ From f61ff481640516a8effd41d0290a5b67ad621997 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 12:18:07 +0530 Subject: [PATCH 11/19] feat(mandi-price): use the first commodity and log the rest [OpenAgriNet/network-adapter#107] Team decision: several supportedCommodities are no longer refused with a 400. Only supportedCommodities[0] is sent to Agmarknet, which takes one code per call, and the plugin logs a warning naming the count. --- .../agmarknet/mandi-price.select.yaml | 13 ++-- .../MandiPrice/mappings_test.go | 38 ++++++++---- .../MandiPrice/prerequisites.go | 60 ++++++++++++++----- 3 files changed, 76 insertions(+), 35 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 9dee29031..6a5e084de 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -53,16 +53,11 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Exactly one. Everything downstream reads supportedCommodities[0]: - this guard, the outbound query, and the commodity stamped on each - resource. So a caller sending three commodities passed validation, was - queried for the first, and got a confident signed answer to a third of - what it asked -- the same failure capabilitybinding refuses at the - commitment level, where guessing would silently serve part of a - request. */ - $count($ra.supportedCommodities) = 1 + /* Only supportedCommodities[0] is sent: Agmarknet takes one code per call. + Extra commodities are logged by the plugin, not refused (team decision). */ + $exists($ra.supportedCommodities[0].code) ) - message: "this capability needs exactly one commodity code in supportedCommodities; send several requests rather than have all but the first dropped" + message: "this capability needs a commodity code in supportedCommodities" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 724d77673..f5c981a83 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -771,18 +771,6 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "marketName alone is insufficient", }, - { - // Everything downstream reads supportedCommodities[0], so this - // used to be queried for Paddy alone and answered confidently. - name: "more commodities than one request can serve", - mutate: func(ra map[string]any) { - ra["supportedCommodities"] = []any{ - map[string]any{"code": "2", "name": "Paddy(Common)"}, - map[string]any{"code": "3", "name": "Wheat"}, - } - }, - expect: "exactly one commodity", - }, } { t.Run(tc.name, func(t *testing.T) { var payload map[string]any @@ -1006,3 +994,29 @@ func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { } } } + +// Several commodities are not refused: only the first is sent to Agmarknet, +// which takes one code per call, and the plugin logs the rest as dropped. +func TestShippedMappingSendsOnlyTheFirstCommodity(t *testing.T) { + t.Parallel() + + var payload map[string]any + if err := json.Unmarshal([]byte(selectRequest), &payload); err != nil { + t.Fatalf("the fixture is not JSON: %v", err) + } + ra := firstCommitment(t, payload)["resources"].([]any)[0].(map[string]any)["resourceAttributes"].(map[string]any) + ra["supportedCommodities"] = []any{ + map[string]any{"code": "2", "name": "Paddy(Common)"}, + map[string]any{"code": "3", "name": "Wheat"}, + } + request, _ := json.Marshal(payload) + + query, answer := runShippedWith(t, string(request), providerResponse) + + if got := query.Get("commoditycode"); got != "2" { + t.Errorf("commoditycode = %q, want the first commodity, \"2\"", got) + } + if len(resourcesOf(t, answer)) == 0 { + t.Error("no resources; several commodities must be served for the first, not refused") + } +} diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites.go b/pkg/plugin/implementation/MandiPrice/prerequisites.go index 3c365a394..6618a9780 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -1,20 +1,52 @@ package MandiPrice -import "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" +import ( + "context" + + "github.com/beckn-one/beckn-onix/pkg/log" + "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" +) // prerequisites is what a mandi capability needs that its payload does not // carry, keyed by binding key. // -// Empty, and for a better reason than weather's: a market price select names -// the market it wants. The MandiPrice pack has no top-level location -- only -// market.marketCode, market.district and market.state -- so there is nothing -// to resolve. Agmarknet's Vistaar select takes exactly those codes, and the -// mapping reads them straight off the payload. -// -// An entry would be needed only for real I/O: a commodity name to resolve to a -// code, a token to exchange, a point to turn into a market. Each of those is a -// different upstream than the one this was written against, and each would -// bring the question of where the provider-to-function binding belongs -- see -// the note in WeatherObservation/prerequisites.go and prefer keeping the payload explicit -// over adding an entry here. -var prerequisites = common.Prerequisites{} +// Nothing to resolve: a market price select names the market it wants, and the +// mapping reads Agmarknet's codes straight off the payload. The one entry only +// logs, because a mapping cannot: Agmarknet takes one commodity per call. +var prerequisites = common.Prerequisites{ + "agmarknet|openagrinet:MandiPrice": logExtraCommodities, +} + +// logExtraCommodities warns when a select names several commodities. Only the +// first is sent to Agmarknet, which takes one code per call; the rest are +// dropped, not refused. +func logExtraCommodities(ctx context.Context, beckn any) (map[string]any, error) { + if n := len(commodities(beckn)); n > 1 { + log.Warnf(ctx, "MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n) + } + return nil, nil +} + +// commodities reads message.contract.commitments[0].resources[0] +// .resourceAttributes.supportedCommodities, or nil when any step is missing. +func commodities(beckn any) []any { + node := beckn + for _, step := range []any{"message", "contract", "commitments", 0, "resources", 0, "resourceAttributes", "supportedCommodities"} { + switch key := step.(type) { + case string: + m, ok := node.(map[string]any) + if !ok { + return nil + } + node = m[key] + case int: + list, ok := node.([]any) + if !ok || len(list) <= key { + return nil + } + node = list[key] + } + } + list, _ := node.([]any) + return list +} From 09ed527fa1e64bb9e4a9e0345c35822b84a3cb65 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 12:45:42 +0530 Subject: [PATCH 12/19] fix(mandi-price): answer with the requested market codes; drop the commodity log [OpenAgriNet/network-adapter#107] - market.district and market.state are the requested codes, so an answer's market can be selected again - extra commodities are ignored without a plugin log; prerequisites.go is back to development --- .../agmarknet/mandi-price.select.yaml | 10 ++-- .../MandiPrice/mappings_test.go | 13 ++-- .../MandiPrice/prerequisites.go | 60 +++++-------------- 3 files changed, 26 insertions(+), 57 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 6a5e084de..dcad9b6a3 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -54,7 +54,7 @@ required: ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; /* Only supportedCommodities[0] is sent: Agmarknet takes one code per call. - Extra commodities are logged by the plugin, not refused (team decision). */ + Extra commodities are ignored, not refused. */ $exists($ra.supportedCommodities[0].code) ) message: "this capability needs a commodity code in supportedCommodities" @@ -346,13 +346,13 @@ response: | "commodityGroup": $r.Group, "variety": $r.Variety, "grade": $r.Grade, - /* From the record, except marketCode: Agmarknet reports none, so it is the - requested one, and omitted district-wide. marketName is trimmed. */ + /* Codes from the request, so the market can be asked again; Agmarknet + filters by them and returns names. marketName is the record's, trimmed. */ "market": { "marketCode": $ra.market.marketCode, "marketName": $trim($r.Market), - "district": $r.District, - "state": $r.State + "district": $ra.market.district, + "state": $ra.market.state }, "arrivalDate": $iso($r.`Arrival Date`), "prices": { diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index f5c981a83..ab5ddf0d7 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -384,8 +384,9 @@ func TestShippedMappingServesARealSelect(t *testing.T) { } market, _ := attributes["market"].(map[string]any) - if market["marketName"] != "Kasdol APMC" || market["state"] != "Chattisgarh" { - t.Errorf("market = %v, want the names the provider reported", market) + // Codes from the request, so the answer's market can be selected again. + if market["marketName"] != "Kasdol APMC" || market["district"] != "96" || market["state"] != "CG" { + t.Errorf("market = %v, want the reported name with the requested district and state codes", market) } // --- a record the market reported only partially ------------------------- @@ -688,9 +689,9 @@ func TestShippedMappingStatesWhatItKnowsRatherThanEchoing(t *testing.T) { if market["marketCode"] != "2056" { t.Errorf("market.marketCode = %#v, want the requested \"2056\"", market["marketCode"]) } - // And what is there comes from the record. - if market["marketName"] != "Kasdol APMC" || market["state"] != "Chattisgarh" { - t.Errorf("market = %#v, want the values the provider reported", market) + // The name from the record; district and state as the requested codes. + if market["marketName"] != "Kasdol APMC" || market["district"] != "96" || market["state"] != "CG" { + t.Errorf("market = %#v, want the reported name with the requested district and state codes", market) } // marketName is the one member the pack requires. if _, ok := market["marketName"]; !ok { @@ -996,7 +997,7 @@ func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { } // Several commodities are not refused: only the first is sent to Agmarknet, -// which takes one code per call, and the plugin logs the rest as dropped. +// which takes one code per call, and the rest are ignored. func TestShippedMappingSendsOnlyTheFirstCommodity(t *testing.T) { t.Parallel() diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites.go b/pkg/plugin/implementation/MandiPrice/prerequisites.go index 6618a9780..3c365a394 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -1,52 +1,20 @@ package MandiPrice -import ( - "context" - - "github.com/beckn-one/beckn-onix/pkg/log" - "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" -) +import "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" // prerequisites is what a mandi capability needs that its payload does not // carry, keyed by binding key. // -// Nothing to resolve: a market price select names the market it wants, and the -// mapping reads Agmarknet's codes straight off the payload. The one entry only -// logs, because a mapping cannot: Agmarknet takes one commodity per call. -var prerequisites = common.Prerequisites{ - "agmarknet|openagrinet:MandiPrice": logExtraCommodities, -} - -// logExtraCommodities warns when a select names several commodities. Only the -// first is sent to Agmarknet, which takes one code per call; the rest are -// dropped, not refused. -func logExtraCommodities(ctx context.Context, beckn any) (map[string]any, error) { - if n := len(commodities(beckn)); n > 1 { - log.Warnf(ctx, "MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n) - } - return nil, nil -} - -// commodities reads message.contract.commitments[0].resources[0] -// .resourceAttributes.supportedCommodities, or nil when any step is missing. -func commodities(beckn any) []any { - node := beckn - for _, step := range []any{"message", "contract", "commitments", 0, "resources", 0, "resourceAttributes", "supportedCommodities"} { - switch key := step.(type) { - case string: - m, ok := node.(map[string]any) - if !ok { - return nil - } - node = m[key] - case int: - list, ok := node.([]any) - if !ok || len(list) <= key { - return nil - } - node = list[key] - } - } - list, _ := node.([]any) - return list -} +// Empty, and for a better reason than weather's: a market price select names +// the market it wants. The MandiPrice pack has no top-level location -- only +// market.marketCode, market.district and market.state -- so there is nothing +// to resolve. Agmarknet's Vistaar select takes exactly those codes, and the +// mapping reads them straight off the payload. +// +// An entry would be needed only for real I/O: a commodity name to resolve to a +// code, a token to exchange, a point to turn into a market. Each of those is a +// different upstream than the one this was written against, and each would +// bring the question of where the provider-to-function binding belongs -- see +// the note in WeatherObservation/prerequisites.go and prefer keeping the payload explicit +// over adding an entry here. +var prerequisites = common.Prerequisites{} From f58edcaa224fd1f0d11d6e8c67606dddd98435d5 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 12:57:52 +0530 Subject: [PATCH 13/19] feat(mandi-price): log when a select names more than one commodity [OpenAgriNet/network-adapter#107] Only supportedCommodities[0] is sent to Agmarknet; the plugin now warns with the count so the dropped commodities show in the adapter log. --- .../agmarknet/mandi-price.select.yaml | 2 +- .../MandiPrice/mappings_test.go | 2 +- .../MandiPrice/prerequisites.go | 60 ++++++++++++++----- 3 files changed, 48 insertions(+), 16 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index dcad9b6a3..655c138fc 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -54,7 +54,7 @@ required: ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; /* Only supportedCommodities[0] is sent: Agmarknet takes one code per call. - Extra commodities are ignored, not refused. */ + Extra commodities are logged by the plugin, not refused. */ $exists($ra.supportedCommodities[0].code) ) message: "this capability needs a commodity code in supportedCommodities" diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index ab5ddf0d7..3b4feb7b3 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -997,7 +997,7 @@ func TestShippedMappingPriceFieldsMinimumAloneAndDefaultAll(t *testing.T) { } // Several commodities are not refused: only the first is sent to Agmarknet, -// which takes one code per call, and the rest are ignored. +// which takes one code per call, and the plugin logs the rest as dropped. func TestShippedMappingSendsOnlyTheFirstCommodity(t *testing.T) { t.Parallel() diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites.go b/pkg/plugin/implementation/MandiPrice/prerequisites.go index 3c365a394..6618a9780 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -1,20 +1,52 @@ package MandiPrice -import "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" +import ( + "context" + + "github.com/beckn-one/beckn-onix/pkg/log" + "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" +) // prerequisites is what a mandi capability needs that its payload does not // carry, keyed by binding key. // -// Empty, and for a better reason than weather's: a market price select names -// the market it wants. The MandiPrice pack has no top-level location -- only -// market.marketCode, market.district and market.state -- so there is nothing -// to resolve. Agmarknet's Vistaar select takes exactly those codes, and the -// mapping reads them straight off the payload. -// -// An entry would be needed only for real I/O: a commodity name to resolve to a -// code, a token to exchange, a point to turn into a market. Each of those is a -// different upstream than the one this was written against, and each would -// bring the question of where the provider-to-function binding belongs -- see -// the note in WeatherObservation/prerequisites.go and prefer keeping the payload explicit -// over adding an entry here. -var prerequisites = common.Prerequisites{} +// Nothing to resolve: a market price select names the market it wants, and the +// mapping reads Agmarknet's codes straight off the payload. The one entry only +// logs, because a mapping cannot: Agmarknet takes one commodity per call. +var prerequisites = common.Prerequisites{ + "agmarknet|openagrinet:MandiPrice": logExtraCommodities, +} + +// logExtraCommodities warns when a select names several commodities. Only the +// first is sent to Agmarknet, which takes one code per call; the rest are +// dropped, not refused. +func logExtraCommodities(ctx context.Context, beckn any) (map[string]any, error) { + if n := len(commodities(beckn)); n > 1 { + log.Warnf(ctx, "MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n) + } + return nil, nil +} + +// commodities reads message.contract.commitments[0].resources[0] +// .resourceAttributes.supportedCommodities, or nil when any step is missing. +func commodities(beckn any) []any { + node := beckn + for _, step := range []any{"message", "contract", "commitments", 0, "resources", 0, "resourceAttributes", "supportedCommodities"} { + switch key := step.(type) { + case string: + m, ok := node.(map[string]any) + if !ok { + return nil + } + node = m[key] + case int: + list, ok := node.([]any) + if !ok || len(list) <= key { + return nil + } + node = list[key] + } + } + list, _ := node.([]any) + return list +} From 465d7c588d7930471cf726f5f2badd1135555954 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 13:02:32 +0530 Subject: [PATCH 14/19] fix(mandi-price): drop the commodity check the schema already enforces [OpenAgriNet/network-adapter#107] The pack requires supportedCommodities with minItems 1 and a code on each item, and schemav2validator refuses those before the mapping runs. --- config/mappings/agmarknet/mandi-price.select.yaml | 8 -------- pkg/plugin/implementation/MandiPrice/mappings_test.go | 1 - 2 files changed, 9 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 655c138fc..a1acf8ca2 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -50,14 +50,6 @@ # Refusing here names what is missing. Sending it anyway earns a 400 from # Agmarknet, or worse an empty result that reads as "no prices". required: - - check: | - ( - $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Only supportedCommodities[0] is sent: Agmarknet takes one code per call. - Extra commodities are logged by the plugin, not refused. */ - $exists($ra.supportedCommodities[0].code) - ) - message: "this capability needs a commodity code in supportedCommodities" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 3b4feb7b3..4f142cb88 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -409,7 +409,6 @@ func TestShippedMappingServesARealSelect(t *testing.T) { // provider is called, with its own message. func TestShippedMappingRefusesWhatItCannotServe(t *testing.T) { for _, tc := range []struct{ name, drop, expect string }{ - {"no commodity code", "supportedCommodities", "commodity code"}, {"no market codes", "market", "codes in market"}, {"no validity window", "validity", "validity window"}, } { From e93f2cf08bc2d8da8d512e9e40d30c2b8d5fb645 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 13:07:54 +0530 Subject: [PATCH 15/19] refactor(mandi-price): count commodities with common.LeavesAt [OpenAgriNet/network-adapter#107] Replaces the hand-written payload walk with the shared path walker. --- .../MandiPrice/prerequisites.go | 27 ++----------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites.go b/pkg/plugin/implementation/MandiPrice/prerequisites.go index 6618a9780..e6e3dfd5d 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -21,32 +21,9 @@ var prerequisites = common.Prerequisites{ // first is sent to Agmarknet, which takes one code per call; the rest are // dropped, not refused. func logExtraCommodities(ctx context.Context, beckn any) (map[string]any, error) { - if n := len(commodities(beckn)); n > 1 { + path := "message.contract.commitments[].resources[].resourceAttributes.supportedCommodities[]" + if n := len(common.LeavesAt(beckn, path)); n > 1 { log.Warnf(ctx, "MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n) } return nil, nil } - -// commodities reads message.contract.commitments[0].resources[0] -// .resourceAttributes.supportedCommodities, or nil when any step is missing. -func commodities(beckn any) []any { - node := beckn - for _, step := range []any{"message", "contract", "commitments", 0, "resources", 0, "resourceAttributes", "supportedCommodities"} { - switch key := step.(type) { - case string: - m, ok := node.(map[string]any) - if !ok { - return nil - } - node = m[key] - case int: - list, ok := node.([]any) - if !ok || len(list) <= key { - return nil - } - node = list[key] - } - } - list, _ := node.([]any) - return list -} From f8b587e179addd614f75f1ba937239be26745e1b Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 13:12:42 +0530 Subject: [PATCH 16/19] docs(mandi-price): drop the mapping header's wrong pack claims [OpenAgriNet/network-adapter#107] The pack's OnDemand branch only adds required: [supportedPriceFields]; it excludes neither market nor validity. --- .../agmarknet/mandi-price.select.yaml | 36 ++----------------- 1 file changed, 2 insertions(+), 34 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index a1acf8ca2..cb9b8fc53 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -7,48 +7,16 @@ # The upstream is Agmarknet's Vistaar select. It takes governed codes -- state, # district, market, commodity -- plus a date range, and every one of them is in # the payload, so nothing here needs resolving before the call. That is why the -# mandi plugin has no prerequisites: a MandiPrice select names the market it +# mandi plugin resolves nothing: a MandiPrice select names the market it # wants rather than a point to search from. # -# THE ANSWER IS WITHIN THE PACK; THE REQUEST IS NOT, AND CANNOT BE YET. +# THE ANSWER IS WITHIN THE PACK. # # Every field the response sets is declared by openagrinet:MandiPrice v0.1 and # correctly placed, inside the closed market and prices property sets. Where # the upstream reports something the pack has no home for, it is dropped rather # than invented. -# -# The REQUEST half is a different matter, and an earlier version of this note -# claimed otherwise. It reads market and validity, and the pack's OnDemand -# branch EXCLUDES both -- see the note on the guards below. That is a gap in -# the pack rather than a mistake here: OnDemand describes what a provider can -# obtain and Direct describes an obtained reading, and a request is neither. -# What this capability cannot serve, refused before the provider is called. -# -# THE PACK AND THESE GUARDS DISAGREE TODAY, and an earlier version of this note -# said the pack leaves market and validity OPTIONAL. It does not: the OnDemand -# branch EXCLUDES them, alongside source, commodity, commodityGroup, grade, -# variety, arrivalDate, prices and generatedAt. So a payload that satisfies -# these guards cannot validate against the pack, and one that validates cannot -# satisfy them. -# -# Nothing breaks in practice: the exclusion sits under if/then, which the -# validator parses and never evaluates. That is an accident to rely on rather -# than a design, and it is written down here so it is not mistaken for one. -# -# Resolving it is a pack change. For the market, coverageAreas is the likely -# home -- inherited from AgricultureResource, not excluded in OnDemand, and it -# accepts an AdministrativeAreaReference. For the date range there is no -# candidate at all: historyPeriod and updateFrequency are durations describing -# provider capability, not a window a caller asks for. -# -# What IS true, and is the reason this block exists: the pack defines -# market.district and market.state as "name or governed code", so a payload can -# be perfectly valid and still be unanswerable by this upstream, which wants -# codes and a date range. -# -# Refusing here names what is missing. Sending it anyway earns a 400 from -# Agmarknet, or worse an empty result that reads as "no prices". required: - check: | ( From 91ca538b281f52b4ad5572d2ed61f570962d4dfc Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 6 Nov 2026 13:16:22 +0530 Subject: [PATCH 17/19] docs(mandi-price): trim the mapping header [OpenAgriNet/network-adapter#107] --- config/mappings/agmarknet/mandi-price.select.yaml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index cb9b8fc53..3b01bcb9e 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -6,11 +6,7 @@ # # The upstream is Agmarknet's Vistaar select. It takes governed codes -- state, # district, market, commodity -- plus a date range, and every one of them is in -# the payload, so nothing here needs resolving before the call. That is why the -# mandi plugin resolves nothing: a MandiPrice select names the market it -# wants rather than a point to search from. -# -# THE ANSWER IS WITHIN THE PACK. +# the payload, so nothing here needs resolving before the call. # # Every field the response sets is declared by openagrinet:MandiPrice v0.1 and # correctly placed, inside the closed market and prices property sets. Where From 62f3d2bb8e1ef43ad8fc9b4a2d3a164e5dc81b7a Mon Sep 17 00:00:00 2001 From: Kelvin Date: Mon, 9 Nov 2026 12:52:10 +0530 Subject: [PATCH 18/19] fix(mandi-price): refuse a state name where Agmarknet wants a code [OpenAgriNet/network-adapter#107] Refs OpenAgriNet/helmcharts#123 (review comment r4509945972) --- config/mappings/agmarknet/mandi-price.select.yaml | 6 ++++-- pkg/plugin/implementation/MandiPrice/mappings_test.go | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 3b01bcb9e..44100788d 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -26,10 +26,12 @@ required: - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; - /* Mandatory: Agmarknet refuses a call without statecode. */ + /* Mandatory, and a code: Agmarknet wants a short alphabetic state (CG). + The pack allows a name, which Agmarknet answers with nothing. */ $exists($ra.market.state) + and $count($match($ra.market.state, /^[A-Za-z]{2,4}$/)) > 0 ) - message: "this capability needs market.state, Agmarknet's state code" + message: "this capability needs market.state, Agmarknet's state code: a short alphabetic code, not a name" - check: | ( $ra := beckn.message.contract.commitments[0].resources[0].resourceAttributes; diff --git a/pkg/plugin/implementation/MandiPrice/mappings_test.go b/pkg/plugin/implementation/MandiPrice/mappings_test.go index 4f142cb88..6de314e4b 100644 --- a/pkg/plugin/implementation/MandiPrice/mappings_test.go +++ b/pkg/plugin/implementation/MandiPrice/mappings_test.go @@ -755,6 +755,15 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { }, expect: "market.state", }, + { + // A numeric district with a state name: the name would go upstream + // as statecode and come back as "no prices". + name: "a state name where the upstream wants a code", + mutate: func(ra map[string]any) { + ra["market"].(map[string]any)["state"] = "Chattisgarh" + }, + expect: "short alphabetic code", + }, { name: "no district", mutate: func(ra map[string]any) { From d3e43ad6e5eb3212a621c6abd6181d47c2a4ad77 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Mon, 9 Nov 2026 12:59:12 +0530 Subject: [PATCH 19/19] fix(mandi-price): warn about what the mapping drops, not every commodity [OpenAgriNet/network-adapter#107] Refs OpenAgriNet/network-adapter#119 (review comment r4490298102) --- .../MandiPrice/prerequisites.go | 56 +++++++++++++++--- .../MandiPrice/prerequisites_test.go | 59 +++++++++++++++++++ 2 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 pkg/plugin/implementation/MandiPrice/prerequisites_test.go diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites.go b/pkg/plugin/implementation/MandiPrice/prerequisites.go index e6e3dfd5d..5b5e91755 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -2,6 +2,7 @@ package MandiPrice import ( "context" + "fmt" "github.com/beckn-one/beckn-onix/pkg/log" "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" @@ -12,18 +13,55 @@ import ( // // Nothing to resolve: a market price select names the market it wants, and the // mapping reads Agmarknet's codes straight off the payload. The one entry only -// logs, because a mapping cannot: Agmarknet takes one commodity per call. +// logs, because a mapping cannot: it reads one commitment, one resource and one +// commodity per call. var prerequisites = common.Prerequisites{ - "agmarknet|openagrinet:MandiPrice": logExtraCommodities, + "agmarknet|openagrinet:MandiPrice": logDroppedSelections, } -// logExtraCommodities warns when a select names several commodities. Only the -// first is sent to Agmarknet, which takes one code per call; the rest are -// dropped, not refused. -func logExtraCommodities(ctx context.Context, beckn any) (map[string]any, error) { - path := "message.contract.commitments[].resources[].resourceAttributes.supportedCommodities[]" - if n := len(common.LeavesAt(beckn, path)); n > 1 { - log.Warnf(ctx, "MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n) +// logDroppedSelections warns about what the mapping leaves out of the call; +// see droppedSelections. +func logDroppedSelections(ctx context.Context, beckn any) (map[string]any, error) { + for _, warning := range droppedSelections(beckn) { + log.Warn(ctx, warning) } return nil, nil } + +// droppedSelections names what the mapping drops. It reads +// commitments[0].resources[0] and its supportedCommodities[0] only; the rest +// are dropped, not refused. +func droppedSelections(beckn any) []string { + var warnings []string + commitments := listAt(beckn, "message", "contract", "commitments") + if n := len(commitments); n > 1 { + warnings = append(warnings, fmt.Sprintf("MandiPrice select has %d commitments; only commitments[0] is requested", n)) + } + if len(commitments) == 0 { + return warnings + } + resources := listAt(commitments[0], "resources") + if n := len(resources); n > 1 { + warnings = append(warnings, fmt.Sprintf("MandiPrice select has %d resources in commitments[0]; only resources[0] is requested", n)) + } + if len(resources) == 0 { + return warnings + } + if n := len(listAt(resources[0], "resourceAttributes", "supportedCommodities")); n > 1 { + warnings = append(warnings, fmt.Sprintf("MandiPrice select names %d commodities; Agmarknet takes one per call, so only supportedCommodities[0] is requested", n)) + } + return warnings +} + +// listAt follows plain object keys and returns the array at the end, or nil. +func listAt(node any, keys ...string) []any { + for _, key := range keys { + fields, ok := node.(map[string]any) + if !ok { + return nil + } + node = fields[key] + } + list, _ := node.([]any) + return list +} diff --git a/pkg/plugin/implementation/MandiPrice/prerequisites_test.go b/pkg/plugin/implementation/MandiPrice/prerequisites_test.go new file mode 100644 index 000000000..4b085394e --- /dev/null +++ b/pkg/plugin/implementation/MandiPrice/prerequisites_test.go @@ -0,0 +1,59 @@ +package MandiPrice + +import ( + "encoding/json" + "strings" + "testing" +) + +// The warnings count what the mapping reads, commitments[0].resources[0], not +// every commodity in the payload. +func TestDroppedSelectionsCountsWhatTheMappingReads(t *testing.T) { + for _, tc := range []struct { + name string + payload string + want []string + }{ + { + name: "one of each", + payload: `{"message":{"contract":{"commitments":[{"resources":[{"resourceAttributes":{"supportedCommodities":[{"code":"1"}]}}]}]}}}`, + }, + { + // One commodity each in two commitments: the second commitment is + // dropped whole, and no commodity is lost from the first. + name: "two commitments, one commodity each", + payload: `{"message":{"contract":{"commitments":[{"resources":[{"resourceAttributes":{"supportedCommodities":[{"code":"1"}]}}]},{"resources":[{"resourceAttributes":{"supportedCommodities":[{"code":"2"}]}}]}]}}}`, + want: []string{"2 commitments"}, + }, + { + name: "two resources", + payload: `{"message":{"contract":{"commitments":[{"resources":[{"resourceAttributes":{"supportedCommodities":[{"code":"1"}]}},{"resourceAttributes":{"supportedCommodities":[{"code":"2"}]}}]}]}}}`, + want: []string{"2 resources"}, + }, + { + name: "two commodities in the first resource", + payload: `{"message":{"contract":{"commitments":[{"resources":[{"resourceAttributes":{"supportedCommodities":[{"code":"1"},{"code":"2"}]}}]}]}}}`, + want: []string{"2 commodities"}, + }, + { + name: "no commitments", + payload: `{"message":{"contract":{}}}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var beckn any + if err := json.Unmarshal([]byte(tc.payload), &beckn); err != nil { + t.Fatalf("the fixture is not JSON: %v", err) + } + got := droppedSelections(beckn) + if len(got) != len(tc.want) { + t.Fatalf("warnings = %q, want %d matching %q", got, len(tc.want), tc.want) + } + for i, want := range tc.want { + if !strings.Contains(got[i], want) { + t.Errorf("warning %d = %q, want it to mention %q", i, got[i], want) + } + } + }) + } +}