diff --git a/config/mappings/agmarknet/mandi-price.select.yaml b/config/mappings/agmarknet/mandi-price.select.yaml index 841618389..44100788d 100644 --- a/config/mappings/agmarknet/mandi-price.select.yaml +++ b/config/mappings/agmarknet/mandi-price.select.yaml @@ -6,86 +6,52 @@ # # 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 -# wants rather than a point to search from. -# -# THE ANSWER IS WITHIN THE PACK; THE REQUEST IS NOT, AND CANNOT BE YET. +# 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 # 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: | ( $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. */ - $exists($ra.supportedCommodities[0].code) - and $count($ra.supportedCommodities) = 1 + /* Mandatory, and a code: Agmarknet wants a numeric district (96). The pack + allows a name, which Agmarknet answers with nothing. */ + $exists($ra.market.district) + and $count($match($ra.market.district, /^[0-9]+$/)) > 0 ) - 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 Agmarknet's codes in market: a numeric district, not a name" - 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}$/) + /* 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 Agmarknet's codes in market: a numeric district and a short alphabetic state, not their names" + 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; + /* 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 insufficient; provide market.marketCode or omit market.marketName for district-wide search." - 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; + $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, @@ -338,21 +304,13 @@ 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. */ + /* 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": { - "marketName": $r.Market, - "district": $r.District, - "state": $r.State + "marketCode": $ra.market.marketCode, + "marketName": $trim($r.Market), + "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 dc902b48a..6de314e4b 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 ------------------------- @@ -408,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"}, } { @@ -683,13 +683,14 @@ 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 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"]) } - // 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 { @@ -723,16 +724,61 @@ func TestShippedMappingRefusesPayloadsItCannotAnswer(t *testing.T) { expect: "codes in market", }, { - // 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", + // 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) { - ra["supportedCommodities"] = []any{ - map[string]any{"code": "2", "name": "Paddy(Common)"}, - map[string]any{"code": "3", "name": "Wheat"}, - } + 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", + }, + { + 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: "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) { + delete(ra["market"].(map[string]any), "district") + }, + 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: "exactly one commodity", + expect: "marketName alone is insufficient", }, } { t.Run(tc.name, func(t *testing.T) { @@ -879,3 +925,107 @@ func TestShippedMappingHonoursTheRequestedPriceFields(t *testing.T) { } } } + +// 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() + + 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) + // 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) + 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) + } +} + +// 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) + } + } + } +} + +// 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..5b5e91755 100644 --- a/pkg/plugin/implementation/MandiPrice/prerequisites.go +++ b/pkg/plugin/implementation/MandiPrice/prerequisites.go @@ -1,20 +1,67 @@ package MandiPrice -import "github.com/beckn-one/beckn-onix/pkg/plugin/implementation/internal/common" +import ( + "context" + "fmt" + + "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: it reads one commitment, one resource and one +// commodity per call. +var prerequisites = common.Prerequisites{ + "agmarknet|openagrinet:MandiPrice": logDroppedSelections, +} + +// 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) + } + } + }) + } +}