index.js (17966B)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | "use strict"; const { Contract } = require("fabric-contract-api"); class ProduceContract extends Contract { // Utilities async _getState(ctx, id) { const data = await ctx.stub.getState(id); if (!data || data.length === 0) { throw new Error(`Asset ${id} does not exist`); } return JSON.parse(data.toString()); } async _putState(ctx, id, obj) { await ctx.stub.putState(id, Buffer.from(JSON.stringify(obj))); } // Deterministic timestamp from tx context _txTimestampISO(ctx) { const ts = ctx.stub.getTxTimestamp(); // ts.seconds may be a Long object in some environments const seconds = typeof ts.seconds === "object" && typeof ts.seconds.toNumber === "function" ? ts.seconds.toNumber() : Number(ts.seconds); const millis = seconds * 1000 + Math.floor((ts.nanos || 0) / 1e6); return new Date(millis).toISOString(); } // Deterministic action item _actionItem(ctx, action, location, owner, meta) { return { timestamp: this._txTimestampISO(ctx), action, currentLocation: location || "", currentOwner: owner || "", meta: meta || {}, }; } // Find user state by ID async _findUserKeyById(ctx, id) { if (!id) return null; const roles = ["FARMER", "DISTRIBUTOR", "RETAILER", "INSPECTOR"]; for (const r of roles) { const key = `${r}-${id}`; const data = await ctx.stub.getState(key); if (data && data.length > 0) return key; } return null; } async _getUserById(ctx, id) { const key = await this._findUserKeyById(ctx, id); if (!key) return null; const data = await ctx.stub.getState(key); if (!data || data.length === 0) return null; return { key, user: JSON.parse(data.toString()) }; } async _addOwnedProduceToUser(ctx, userKey, userObj, produceId) { userObj.ownedProduce = userObj.ownedProduce || []; if (!userObj.ownedProduce.includes(produceId)) { userObj.ownedProduce.push(produceId); await this._putState(ctx, userKey, userObj); } } async _removeOwnedProduceFromUser(ctx, userKey, userObj, produceId) { userObj.ownedProduce = userObj.ownedProduce || []; const idx = userObj.ownedProduce.indexOf(produceId); if (idx >= 0) { userObj.ownedProduce.splice(idx, 1); await this._putState(ctx, userKey, userObj); } } _validateInput(data, requiredFields) { for (const field of requiredFields) { if ( data[field] === undefined || data[field] === null || data[field] === "" ) { throw new Error(`Validation Error: Field '${field}' is required`); } } if (data.qty && (typeof data.qty !== "number" || data.qty <= 0)) throw new Error("Validation Error: 'qty' must be a positive number"); if ( data.pricePerUnit && (typeof data.pricePerUnit !== "number" || data.pricePerUnit < 0) ) { throw new Error( "Validation Error: 'pricePerUnit' must be a non-negative number" ); } } // Initialize ledger async initLedger(ctx) { console.info("Ledger initialized"); } // Functions // Produce Registration async registerProduce(ctx, farmerId, detailsStr) { const clientMspId = ctx.clientIdentity.getMSPID(); if (clientMspId !== "Org1MSP") throw new Error( `Client from ${clientMspId} is not authorized to register produce. Only Org1MSP is allowed.` ); const farmerKey = `FARMER-${farmerId}`; const farmerState = await ctx.stub.getState(farmerKey); if (!farmerState || farmerState.length === 0) throw new Error(`Farmer ${farmerId} is not registered`); const farmer = JSON.parse(farmerState.toString()); const details = JSON.parse(detailsStr || "{}"); this._validateInput(details, [ "cropType", "qty", "qtyUnit", "pricePerUnit", "harvestDate", ]); const txId = ctx.stub.getTxID(); const now = this._txTimestampISO(ctx); const id = `PRODUCE-${txId}`; const produce = { id, parentId: null, children: [], qty: details.qty, qtyUnit: details.qtyUnit, pricePerUnit: details.pricePerUnit, totalPrice: details.pricePerUnit * details.qty, currentOwner: farmerId, currentLocation: details.location || "", actionHistory: [], saleHistory: [], cropType: details.cropType, harvestDate: details.harvestDate || now, quality: details.quality || null, expiryDate: details.expiryDate || null, storageConditions: details.storageConditions || [], imageUrl: details.imageUrl || null, certification: details.certification || farmer.certification || [], status: "Harvested", isAvailable: true, notAvailableReason: null, }; produce.actionHistory.push( this._actionItem(ctx, "REGISTER", produce.currentLocation, farmerId, { note: details.note || "", }) ); await this._putState(ctx, id, produce); const farmerObj = farmer; farmerObj.registeredProduce = farmerObj.registeredProduce || []; if (!farmerObj.registeredProduce.includes(id)) farmerObj.registeredProduce.push(id); farmerObj.ownedProduce = farmerObj.ownedProduce || []; if (!farmerObj.ownedProduce.includes(id)) farmerObj.ownedProduce.push(id); await this._putState(ctx, farmerKey, farmerObj); return produce; } // Update location async updateLocation(ctx, produceId, actorId, newLocation) { const produce = await this._getState(ctx, produceId); if (newLocation === "In Transit") produce.status = "In Transit"; else { produce.currentLocation = newLocation; if (produce.status === "Harvested") produce.status = "In Transit"; } produce.actionHistory.push( this._actionItem(ctx, "MOVE", produce.currentLocation, actorId, {}) ); await this._putState(ctx, produceId, produce); return produce; } // Mark as unavailable due to some reason async markAsUnavailable(ctx, produceId, actorId, reason, newStatus) { const produce = await this._getState(ctx, produceId); produce.isAvailable = false; produce.notAvailableReason = reason || ""; produce.status = newStatus || "Removed"; produce.actionHistory.push( this._actionItem(ctx, "REMOVED", produce.currentLocation, actorId, { reason, }) ); await this._putState(ctx, produceId, produce); return produce; } // Produce Inspection async inspectProduce(ctx, produceId, inspectorId, qualityUpdateStr) { const clientMspId = ctx.clientIdentity.getMSPID(); if (clientMspId !== "Org4MSP") throw new Error( `Client from ${clientMspId} is not authorized to inspect produce. Only Org4MSP is allowed.` ); const qualityUpdate = JSON.parse(qualityUpdateStr || "{}"); const produce = await this._getState(ctx, produceId); if (qualityUpdate.quality !== undefined) produce.quality = qualityUpdate.quality; if (qualityUpdate.expiryDate !== undefined) produce.expiryDate = qualityUpdate.expiryDate; if (qualityUpdate.storageConditions !== undefined) produce.storageConditions = qualityUpdate.storageConditions; produce.actionHistory.push( this._actionItem( ctx, "INSPECT", produce.currentLocation, inspectorId, qualityUpdate ) ); if (qualityUpdate.failed === true) { produce.isAvailable = false; produce.notAvailableReason = qualityUpdate.reason || "Failed Inspection"; produce.status = "Failed Inspection"; produce.actionHistory.push( this._actionItem(ctx, "REMOVED", produce.currentLocation, inspectorId, { reason: produce.notAvailableReason, }) ); } await this._putState(ctx, produceId, produce); const inspectorKey = `INSPECTOR-${inspectorId}`; const inspectorState = await ctx.stub.getState(inspectorKey); if (inspectorState && inspectorState.length > 0) { const inspectorObj = JSON.parse(inspectorState.toString()); inspectorObj.inspectedProduce = inspectorObj.inspectedProduce || []; if (!inspectorObj.inspectedProduce.includes(produceId)) { inspectorObj.inspectedProduce.push(produceId); await this._putState(ctx, inspectorKey, inspectorObj); } } return produce; } // Update added details async updateDetails(ctx, produceId, actorId, detailsStr) { const details = JSON.parse(detailsStr || "{}"); const produce = await this._getState(ctx, produceId); if (produce.currentOwner !== actorId) throw new Error("Only current owner can update details"); if (details.pricePerUnit !== undefined) produce.pricePerUnit = details.pricePerUnit; if (details.storageConditions !== undefined) produce.storageConditions = details.storageConditions; if (details.imageUrl !== undefined) produce.imageUrl = details.imageUrl; if (details.certification !== undefined) produce.certification = details.certification; produce.totalPrice = (produce.pricePerUnit || 0) * (produce.qty || 0); produce.actionHistory.push( this._actionItem( ctx, "UPDATED", produce.currentLocation, actorId, details ) ); await this._putState(ctx, produceId, produce); return produce; } // Split into smaller batches async splitProduce(ctx, produceId, qtyStr, ownerId) { const qty = parseFloat(qtyStr); const produce = await this._getState(ctx, produceId); if (produce.currentOwner !== ownerId) throw new Error("Only current owner can split produce"); if (qty <= 0 || qty > produce.qty) throw new Error("Invalid quantity to split"); produce.qty -= qty; produce.totalPrice = (produce.pricePerUnit || 0) * produce.qty; const childId = `${produce.id}-${ctx.stub.getTxID()}-CHILD`; const child = JSON.parse(JSON.stringify(produce)); child.id = childId; child.parentId = produce.id; child.children = []; child.qty = qty; child.totalPrice = (child.pricePerUnit || 0) * qty; child.actionHistory = []; child.saleHistory = []; child.actionHistory.push( this._actionItem(ctx, "SPLIT", produce.currentLocation, ownerId, { qty }) ); produce.children = produce.children || []; produce.children.push(childId); produce.actionHistory.push( this._actionItem(ctx, "SPLIT", produce.currentLocation, ownerId, { createdChild: childId, qty, }) ); await this._putState(ctx, produce.id, produce); await this._putState(ctx, childId, child); const ownerRes = await this._getUserById(ctx, ownerId); if (ownerRes) { await this._addOwnedProduceToUser( ctx, ownerRes.key, ownerRes.user, childId ); } return { parent: produce, child }; } // Transfer ownership async transferOwnership(ctx, produceId, newOwnerId, qtyStr, salePriceStr) { const qty = parseFloat(qtyStr); const salePrice = parseFloat(salePriceStr); const produce = await this._getState(ctx, produceId); const now = this._txTimestampISO(ctx); const currentOwner = produce.currentOwner; if (!produce.isAvailable) throw new Error("Asset not available"); if (qty <= 0 || qty > produce.qty) throw new Error("Invalid qty"); let resultAssetId = produceId; if (qty < produce.qty) { // Partial Transfer const splitRes = await this.splitProduce( ctx, produceId, "" + qty, produce.currentOwner ); const child = splitRes.child; child.currentOwner = newOwnerId; child.actionHistory.push( this._actionItem(ctx, "SALE", child.currentLocation, newOwnerId, { qty, salePrice, }) ); child.saleHistory = child.saleHistory || []; child.saleHistory.push({ timestamp: now, prevOwner: currentOwner, newOwner: newOwnerId, salePrice, qtyBought: qty, paymentStatus: "PENDING", }); await this._putState(ctx, child.id, child); resultAssetId = child.id; const prevOwnerRes = await this._getUserById(ctx, currentOwner); if (prevOwnerRes) { await this._removeOwnedProduceFromUser( ctx, prevOwnerRes.key, prevOwnerRes.user, child.id ); } const newOwnerRes = await this._getUserById(ctx, newOwnerId); if (newOwnerRes) { await this._addOwnedProduceToUser( ctx, newOwnerRes.key, newOwnerRes.user, child.id ); } } else { // Full Transfer produce.currentOwner = newOwnerId; produce.actionHistory.push( this._actionItem(ctx, "SALE", produce.currentLocation, newOwnerId, { qty, salePrice, }) ); produce.saleHistory = produce.saleHistory || []; produce.saleHistory.push({ timestamp: now, prevOwner: currentOwner, newOwner: newOwnerId, salePrice, qtyBought: qty, paymentStatus: "PENDING", }); await this._putState(ctx, produceId, produce); resultAssetId = produceId; const prevOwnerRes = await this._getUserById(ctx, currentOwner); if (prevOwnerRes) { await this._removeOwnedProduceFromUser( ctx, prevOwnerRes.key, prevOwnerRes.user, produceId ); } const newOwnerRes = await this._getUserById(ctx, newOwnerId); if (newOwnerRes) { await this._addOwnedProduceToUser( ctx, newOwnerRes.key, newOwnerRes.user, produceId ); } } return { newAssetId: resultAssetId }; } // Record payment for transfer async recordPayment( ctx, produceId, transactionId, paymentStatus, paymentMethod, paymentRef ) { const produce = await this._getState(ctx, produceId); const now = this._txTimestampISO(ctx); produce.saleHistory = produce.saleHistory || []; if (produce.saleHistory.length === 0) { produce.saleHistory.push({ timestamp: now, prevOwner: null, newOwner: produce.currentOwner, salePrice: produce.totalPrice, qtyBought: produce.qty, paymentStatus, }); } else { const last = produce.saleHistory[produce.saleHistory.length - 1]; last.paymentStatus = paymentStatus; last.paymentMethod = paymentMethod; last.paymentRef = paymentRef || transactionId; } produce.paymentStatus = paymentStatus; produce.paymentMethod = paymentMethod; produce.paymentRef = paymentRef || transactionId; produce.actionHistory.push( this._actionItem( ctx, "PAYMENT", produce.currentLocation, produce.currentOwner, { transactionId, paymentStatus, paymentMethod, paymentRef, } ) ); await this._putState(ctx, produceId, produce); return produce; } // Queries async getProduceById(ctx, produceId) { return await this._getState(ctx, produceId); } async getProduceByOwner(ctx, ownerId) { const iterator = await ctx.stub.getStateByRange("", ""); const results = []; while (true) { const res = await iterator.next(); if (res.value && res.value.key) { if (res.value.key.startsWith("PRODUCE-")) { const obj = JSON.parse(res.value.value.toString("utf8")); if (obj.currentOwner === ownerId) results.push(obj); } } if (res.done) { await iterator.close(); break; } } return results; } // Governance async registerUser(ctx, role, detailsStr) { const clientMspId = ctx.clientIdentity.getMSPID(); const details = JSON.parse(detailsStr || "{}"); const roleUpper = role.toUpperCase(); const roleToOrgMap = { FARMER: "Org1MSP", DISTRIBUTOR: "Org2MSP", RETAILER: "Org3MSP", INSPECTOR: "Org4MSP", }; const expectedMspId = roleToOrgMap[roleUpper]; if (!expectedMspId || clientMspId !== expectedMspId) throw new Error( `Client from ${clientMspId} cannot register a ${role}. Expected admin from ${expectedMspId}.` ); const id = details.id || `USER-${ctx.stub.getTxID()}`; const key = `${roleUpper}-${id}`; const base = { role, id, name: details.name || "", location: details.location || "", walletId: details.walletId || "", }; let user = null; if (roleUpper === "FARMER") { user = { ...base, registeredProduce: details.registeredProduce || [], ownedProduce: details.ownedProduce || [], certification: details.certification || [], }; } else if (roleUpper === "DISTRIBUTOR" || roleUpper === "RETAILER") { user = { ...base, ownedProduce: details.ownedProduce || [], }; } else if (roleUpper === "INSPECTOR") { user = { ...base, inspectedProduce: details.inspectedProduce || [], }; } await this._putState(ctx, key, user); return user; } async getUserDetails(ctx, userKey) { const data = await ctx.stub.getState(userKey); if (!data || data.length === 0) throw new Error(`User ${userKey} not found`); return JSON.parse(data.toString()); } async updateUser(ctx, userKey, detailsStr) { const data = await ctx.stub.getState(userKey); if (!data || data.length === 0) throw new Error(`User ${userKey} not found`); const user = JSON.parse(data.toString()); const details = JSON.parse(detailsStr || "{}"); Object.assign(user, details); await this._putState(ctx, userKey, user); return user; } } module.exports.contracts = [ProduceContract]; |