Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
367404f
feat: filter mandi-price response to the requested market and price f…
kelvinprabhu Nov 3, 2026
3c399dc
feat: make mandi-price marketCode optional, district-wide without it …
kelvinprabhu Nov 3, 2026
e165500
feat: require state, district, commodity and validity dates in mandi-…
kelvinprabhu Nov 4, 2026
238d1db
feat: match mandi-price marketName against the district's markets [Op…
kelvinprabhu Nov 4, 2026
0306f9b
revert: keep jsonmapper unchanged; report the unplaceable marketName …
kelvinprabhu Nov 4, 2026
4efcfe8
fix: refuse mandi-price marketName without marketCode; shorten commen…
kelvinprabhu Nov 4, 2026
71520ec
fix(mandi-price): drop guards the pack's schema already enforces [Ope…
kelvinprabhu Nov 4, 2026
56c6819
refactor(mandi-price): drop redundant logic in the select mapping [Op…
kelvinprabhu Nov 4, 2026
a0f52ce
fix(mandi-price): state presence only, clearer market name message [O…
kelvinprabhu Nov 4, 2026
a44874c
revert(mandi-price): keep the request $base and $ctx as on developmen…
kelvinprabhu Nov 6, 2026
f61ff48
feat(mandi-price): use the first commodity and log the rest [OpenAgri…
kelvinprabhu Nov 6, 2026
09ed527
fix(mandi-price): answer with the requested market codes; drop the co…
kelvinprabhu Nov 6, 2026
f58edca
feat(mandi-price): log when a select names more than one commodity [O…
kelvinprabhu Nov 6, 2026
465d7c5
fix(mandi-price): drop the commodity check the schema already enforce…
kelvinprabhu Nov 6, 2026
e93f2cf
refactor(mandi-price): count commodities with common.LeavesAt [OpenAg…
kelvinprabhu Nov 6, 2026
f8b587e
docs(mandi-price): drop the mapping header's wrong pack claims [OpenA…
kelvinprabhu Nov 6, 2026
91ca538
docs(mandi-price): trim the mapping header [OpenAgriNet/network-adapt…
kelvinprabhu Nov 6, 2026
62f3d2b
fix(mandi-price): refuse a state name where Agmarknet wants a code [O…
kelvinprabhu Nov 9, 2026
d3e43ad
fix(mandi-price): warn about what the mapping drops, not every commod…
kelvinprabhu Nov 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 31 additions & 73 deletions config/mappings/agmarknet/mandi-price.select.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
kelvinprabhu marked this conversation as resolved.
Resolved
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)
Comment thread
kelvinprabhu marked this conversation as resolved.
Resolved
)
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,
Expand Down Expand Up @@ -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,
Comment thread
kelvinprabhu marked this conversation as resolved.
Resolved
"marketName": $trim($r.Market),
"district": $ra.market.district,
"state": $ra.market.state
},
"arrivalDate": $iso($r.`Arrival Date`),
"prices": {
Expand Down
184 changes: 167 additions & 17 deletions pkg/plugin/implementation/MandiPrice/mappings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 -------------------------
Expand All @@ -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"},
} {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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")
}
}
Loading
Loading