COOPENOMICS  v1
Кооперативная Экономика
marketplace.hpp
См. документацию.
1#pragma once
2
3#include <functional>
4#include <optional>
5#include <string>
6
7#include <eosio/crypto.hpp>
8#include <eosio/eosio.hpp>
9
10#include "../../consts.hpp"
11#include "../../domain/document_core.hpp"
12#include "../../domain/table_ledger2_userwallets.hpp"
13#include "../../domain/table_marketplace_fee_config.hpp"
14#include "../ledger2/ledger2.hpp"
15#include "../branch/branch.hpp"
16#include "memo.hpp"
17#include "dues.hpp"
18#include "../../domain/table_marketplace_orders.hpp"
19#include "../../domain/table_marketplace_payouts.hpp"
20#include "../../domain/table_marketplace_return_requests.hpp"
21#include "../../domain/table_marketplace_writeoff_proposals.hpp"
22
34namespace Marketplace {
35
36using namespace eosio;
37
38// ── Количество как fixed-point asset (Эпик 17, L14) ─────────────────────
39//
40// quantity/actual_quantity — asset с символом единицы измерения (KG/LTR/PCS);
41// дробность веса/объёма выражается младшими единицами (0.500 KG = 500 г).
42// Штука (PCS, precision 0) неделима на уровне типа. Цена задаётся за одну
43// базовую единицу (кг/литр/штуку) money-asset'ом _root_govern_symbol.
44
45inline bool is_valid_unit_symbol(const eosio::symbol& sym) {
46 return sym == _unit_kg || sym == _unit_liter || sym == _unit_piece;
47}
48
50inline void check_quantity(const eosio::asset& quantity) {
51 eosio::check(quantity.is_valid() && is_valid_unit_symbol(quantity.symbol),
52 "Недопустимая единица измерения количества");
53 eosio::check(quantity.amount > 0, "Количество должно быть больше нуля");
54}
55
62inline void check_packaging(const eosio::asset& quantity, const eosio::asset& package_size) {
63 if (package_size.amount == 0) return; // отпуск по мере
64 eosio::check(package_size.is_valid() && package_size.symbol == quantity.symbol,
65 "Единица упаковки не совпадает с единицей количества");
66 eosio::check(package_size.amount > 0, "Размер упаковки должен быть больше нуля");
67 eosio::check(quantity.amount % package_size.amount == 0,
68 "Количество должно быть кратно размеру упаковки");
69}
70
79inline eosio::asset calc_cost(const eosio::asset& quantity, const eosio::asset& unit_price,
80 const eosio::asset& package_size = eosio::asset(0, _unit_piece)) {
81 if (package_size.amount > 0) {
82 const int64_t packages = quantity.amount / package_size.amount; // точно (кратность — check_packaging)
83 const uint128_t total = static_cast<uint128_t>(packages) *
84 static_cast<uint128_t>(unit_price.amount);
85 return eosio::asset(static_cast<int64_t>(total), unit_price.symbol);
86 }
87 int64_t scale = 1;
88 for (uint8_t i = 0; i < quantity.symbol.precision(); ++i) scale *= 10;
89 const uint128_t num = static_cast<uint128_t>(quantity.amount) *
90 static_cast<uint128_t>(unit_price.amount);
91 const int64_t amount = static_cast<int64_t>((num + static_cast<uint128_t>(scale) / 2) / scale);
92 return eosio::asset(amount, unit_price.symbol);
93}
94
100inline eosio::asset pro_rata(const eosio::asset& total, int64_t part, int64_t whole) {
101 eosio::check(whole > 0, "Некорректная база для расчёта пропорциональной доли");
102 const uint128_t num = static_cast<uint128_t>(total.amount) * static_cast<uint128_t>(part);
103 const int64_t amount =
104 static_cast<int64_t>((num + static_cast<uint128_t>(whole) / 2) / static_cast<uint128_t>(whole));
105 return eosio::asset(amount, total.symbol);
106}
107
108// ── Orders ──────────────────────────────────────────────────────────────
109
110inline std::optional<order> get_order_by_hash(eosio::name coopname, const checksum256& order_hash) {
111 orders_index orders(_marketplace, coopname.value);
112 auto idx = orders.get_index<"byhash"_n>();
113 auto it = idx.find(order_hash);
114 if (it == idx.end()) return std::nullopt;
115 return *it;
116}
117
118inline order get_order_by_hash_or_fail(eosio::name coopname, const checksum256& order_hash,
119 const std::string& msg = "Заказ не найден по хэшу") {
120 auto o = get_order_by_hash(coopname, order_hash);
121 eosio::check(o.has_value(), msg);
122 return *o;
123}
124
125inline void update_order(eosio::name coopname, uint64_t order_id, const std::function<void(order&)>& fn) {
126 orders_index orders(_marketplace, coopname.value);
127 auto it = orders.find(order_id);
128 eosio::check(it != orders.end(), "Заказ не найден по id");
129 orders.modify(it, RamPayer::of(orders, coopname), [&](auto& o) { fn(o); });
130}
131
140inline std::optional<eosio::asset> get_asset_extension(const eosio::binary_extension<eosio::asset>& ext) {
141 if (!ext.has_value() || ext.value().symbol.raw() == 0) return std::nullopt;
142 return ext.value();
143}
144
148inline eosio::asset get_accepted_cost(const order& o) {
149 return get_asset_extension(o.accepted_cost).value_or(o.fact_cost);
150}
151
153inline eosio::asset get_payout_withheld(const order& o) {
154 return get_asset_extension(o.payout_withheld).value_or(eosio::asset(0, _root_govern_symbol));
155}
156
158inline checksum256 get_payout_hash(const order& o) {
159 return o.payout_hash.has_value() ? o.payout_hash.value() : checksum256();
160}
161
163inline std::optional<payout> get_payout_by_hash(eosio::name coopname, const checksum256& hash) {
164 payouts_index payouts(_marketplace, coopname.value);
165 auto idx = payouts.get_index<"byhash"_n>();
166 auto it = idx.find(hash);
167 if (it == idx.end()) return std::nullopt;
168 return *it;
169}
170
172inline payout get_payout_by_hash_or_fail(eosio::name coopname, const checksum256& hash) {
173 auto p = get_payout_by_hash(coopname, hash);
174 eosio::check(p.has_value(), "MARKETPLACE_PAYOUT_NOT_FOUND: Пакет выплаты не найден");
175 return *p;
176}
177
178inline void update_payout(eosio::name coopname, uint64_t payout_id, const std::function<void(payout&)>& fn) {
179 payouts_index payouts(_marketplace, coopname.value);
180 auto it = payouts.find(payout_id);
181 eosio::check(it != payouts.end(), "MARKETPLACE_PAYOUT_NOT_FOUND: Пакет выплаты не найден");
182 payouts.modify(it, RamPayer::of(payouts, coopname), [&](auto& p) { fn(p); });
183}
184
187inline void detach_order_from_payout(eosio::name coopname, const payout& p) {
188 payouts_index payouts(_marketplace, coopname.value);
189 auto it = payouts.find(p.id);
190 eosio::check(it != payouts.end(), "MARKETPLACE_PAYOUT_NOT_FOUND: Пакет выплаты не найден");
191 eosio::check(it->orders > 0, "MARKETPLACE_PAYOUT_EMPTY: В пакете выплаты не осталось заказов");
192 if (it->orders == 1) {
193 payouts.erase(it);
194 return;
195 }
196 payouts.modify(it, RamPayer::of(payouts, coopname), [&](auto& upd) { upd.orders -= 1; });
197}
198
202inline bool is_supplier_settlement_open(const order& o) {
204}
205
206// Терминал жизненного цикла: запись стирается из RAM, история процесса
207// остаётся в журнале действий (blockchain_actions парсера).
208inline void erase_order(eosio::name coopname, uint64_t order_id) {
209 orders_index orders(_marketplace, coopname.value);
210 auto it = orders.find(order_id);
211 eosio::check(it != orders.end(), "Заказ не найден по id");
212 orders.erase(it);
213}
214
215// ── Return requests ─────────────────────────────────────────────────────
216
222inline uint64_t next_return_request_id(eosio::name coopname) {
223 return_requests_index requests(_marketplace, coopname.value);
224 const uint64_t id = requests.available_primary_key();
225 return id == 0 ? 1 : id;
226}
227
231inline bool has_open_return_request(eosio::name coopname, const order& o) {
232 if (o.return_request_id == 0) return false;
233 return_requests_index requests(_marketplace, coopname.value);
234 auto it = requests.find(o.return_request_id);
235 return it != requests.end() && it->original_order_hash == o.hash;
236}
237
238inline std::optional<return_request> get_return_request_by_hash(eosio::name coopname,
239 const checksum256& request_hash) {
240 return_requests_index requests(_marketplace, coopname.value);
241 auto idx = requests.get_index<"byhash"_n>();
242 auto it = idx.find(request_hash);
243 if (it == idx.end()) return std::nullopt;
244 return *it;
245}
246
248 const checksum256& request_hash,
249 const std::string& msg = "Заявление на возврат не найдено по хэшу") {
250 auto r = get_return_request_by_hash(coopname, request_hash);
251 eosio::check(r.has_value(), msg);
252 return *r;
253}
254
255inline void update_return_request(eosio::name coopname, uint64_t request_id,
256 const std::function<void(return_request&)>& fn) {
257 return_requests_index requests(_marketplace, coopname.value);
258 auto it = requests.find(request_id);
259 eosio::check(it != requests.end(), "Заявление на возврат не найдено по id");
260 requests.modify(it, RamPayer::of(requests, coopname), [&](auto& r) { fn(r); });
261}
262
263// Терминал жизненного цикла: запись стирается из RAM (история — в журнале
264// действий). order.return_request_id НЕ сбрасывается — повторный возврат по
265// тому же заказу не открывается.
266inline void erase_return_request(eosio::name coopname, uint64_t request_id) {
267 return_requests_index requests(_marketplace, coopname.value);
268 auto it = requests.find(request_id);
269 eosio::check(it != requests.end(), "Заявление на возврат не найдено по id");
270 requests.erase(it);
271}
272
277inline void check_return_request_branch(eosio::name coopname, const return_request& r,
278 eosio::name braname) {
280 eosio::check(o.delivery_braname == braname,
281 "Заявление на возврат рассматривает кооперативный участок выдачи заказа");
282}
283
284// ── Writeoff proposals ──────────────────────────────────────────────────
285
286inline std::optional<writeoff_proposal> get_writeoff_proposal_by_hash(eosio::name coopname,
287 const checksum256& proposal_hash) {
288 writeoff_proposals_index proposals(_marketplace, coopname.value);
289 auto idx = proposals.get_index<"byhash"_n>();
290 auto it = idx.find(proposal_hash);
291 if (it == idx.end()) return std::nullopt;
292 return *it;
293}
294
296 const checksum256& proposal_hash,
297 const std::string& msg = "Проект списания не найден по хэшу") {
298 auto p = get_writeoff_proposal_by_hash(coopname, proposal_hash);
299 eosio::check(p.has_value(), msg);
300 return *p;
301}
302
303inline void update_writeoff_proposal(eosio::name coopname, uint64_t proposal_id,
304 const std::function<void(writeoff_proposal&)>& fn) {
305 writeoff_proposals_index proposals(_marketplace, coopname.value);
306 auto it = proposals.find(proposal_id);
307 eosio::check(it != proposals.end(), "Проект списания не найден по id");
308 proposals.modify(it, RamPayer::of(proposals, coopname), [&](auto& p) { fn(p); });
309}
310
311// Терминал жизненного цикла: запись стирается из RAM, история процесса —
312// в журнале действий (blockchain_actions парсера).
313inline void erase_writeoff_proposal(eosio::name coopname, uint64_t proposal_id) {
314 writeoff_proposals_index proposals(_marketplace, coopname.value);
315 auto it = proposals.find(proposal_id);
316 eosio::check(it != proposals.end(), "Проект списания не найден по id");
317 proposals.erase(it);
318}
319
320// ── Warranty claims (претензии поставщику, p.mkt.claim) ─────────────────
321
322inline std::optional<warranty_claim> get_claim_by_hash(eosio::name coopname,
323 const checksum256& claim_hash) {
324 warranty_claims_index claims(_marketplace, coopname.value);
325 auto idx = claims.get_index<"byhash"_n>();
326 auto it = idx.find(claim_hash);
327 if (it == idx.end()) return std::nullopt;
328 return *it;
329}
330
331inline warranty_claim get_claim_by_hash_or_fail(eosio::name coopname,
332 const checksum256& claim_hash,
333 const std::string& msg = "Гарантийная претензия поставщику не найдена по хэшу") {
334 auto c = get_claim_by_hash(coopname, claim_hash);
335 eosio::check(c.has_value(), msg);
336 return *c;
337}
338
339inline void update_claim(eosio::name coopname, uint64_t claim_id,
340 const std::function<void(warranty_claim&)>& fn) {
341 warranty_claims_index claims(_marketplace, coopname.value);
342 auto it = claims.find(claim_id);
343 eosio::check(it != claims.end(), "Гарантийная претензия не найдена по id");
344 claims.modify(it, RamPayer::of(claims, coopname), [&](auto& c) { fn(c); });
345}
346
347// ── Cross-contract read: ledger2 wallet/userwallet balances ─────────────
348//
349// Используется в createorder для guard'а Locked Decision L6 (без отрицательного
350// баланса) — проверка достаточности свободного паевого «Стола заказов»
351// перед паевым резервом (o.mkt.lockp).
352//
353// ВАЖНО: контракт marketplace не вызывает ledger2::walletop напрямую, а только
354// читает state (RAM-таблицы wallets2 / userwallets через cross-contract scope).
355// Все мутации идут через `Ledger2::apply` (см. lib/core/ledger2/ledger2.hpp).
356
358 eosio::asset available = eosio::asset(0, _root_govern_symbol);
359 eosio::asset blocked = eosio::asset(0, _root_govern_symbol);
360 bool exists = false;
361};
362
364 eosio::name wallet_id,
365 eosio::name username) {
366 // userwallets_index — глобальный typedef в lib/domain/table_ledger2_userwallets.hpp.
367 // Для cross-contract read берём scope = coopname.value, code = _ledger2.
368 userwallets_index user_wallets(_ledger2, coopname.value);
369 auto idx = user_wallets.get_index<"byuserwallet"_n>();
370 auto it = idx.find(combine_ids(wallet_id.value, username.value));
371 if (it == idx.end()) {
372 return UserWalletAvailable{};
373 }
374 return UserWalletAvailable{ it->available, it->blocked, true };
375}
376
377// ── Обеспечительная часть паевого взноса «Стола заказов» (задача 99D-18) ──
378
383constexpr uint64_t DEFAULT_MEMBERSHIP_FEE_PERCENT = 380000;
384
389constexpr uint64_t DEFAULT_INITIATOR_SHARE_PERCENT = 618000;
390
394constexpr uint64_t DEFAULT_RETURN_SHARE_PERCENT = 382000;
395
399inline uint64_t get_membership_fee_percent(eosio::name coopname) {
400 mkt_config_singleton cfg(_marketplace, coopname.value);
401 return cfg.exists() ? cfg.get().membership_fee_percent : DEFAULT_MEMBERSHIP_FEE_PERCENT;
402}
403
407inline uint64_t get_initiator_share_percent(eosio::name coopname) {
408 mkt_config_singleton cfg(_marketplace, coopname.value);
409 if (!cfg.exists()) return DEFAULT_INITIATOR_SHARE_PERCENT;
410 const auto state = cfg.get();
411 return state.initiator_share_percent.has_value()
412 ? state.initiator_share_percent.value()
414}
415
419inline uint64_t get_return_share_percent(eosio::name coopname) {
420 mkt_config_singleton cfg(_marketplace, coopname.value);
421 if (!cfg.exists()) return DEFAULT_RETURN_SHARE_PERCENT;
422 const auto state = cfg.get();
423 return state.return_share_percent.has_value()
424 ? state.return_share_percent.value()
426}
427
430inline const kuperiod& get_period_or_fail(kuperiods_index& periods, eosio::name braname, uint32_t period) {
431 auto idx = periods.get_index<"bybrperiod"_n>();
432 auto it = idx.find(combine_ids(braname.value, period));
433 eosio::check(it != idx.end(),
434 "MARKETPLACE_PERIOD_NOT_CLOSED: Итог участка за период не рассчитан");
435 return periods.get(it->id);
436}
437
440inline eosio::asset calc_membership_fee(const eosio::asset& base, uint64_t fee_percent) {
441 const int64_t amount = static_cast<int64_t>(
442 static_cast<uint128_t>(base.amount) * fee_percent / HUNDR_PERCENTS);
443 return eosio::asset(amount, _root_govern_symbol);
444}
445
447inline eosio::asset get_order_membership_fee(const order& o) {
448 return o.membership_fee;
449}
450
458inline void require_order_funding(eosio::name coopname, eosio::name orderer,
459 const eosio::asset& body, const eosio::asset& secure_part) {
461 if (secure_part.amount > 0) {
462 eosio::check(program.available >= secure_part,
463 std::string{"MARKETPLACE_SECURE_PART_SHORTFALL: Недостаточно свободного паевого Стола заказов на обеспечительную часть: требуется "} +
464 secure_part.to_string() + ", доступно " + program.available.to_string() +
465 ". Сначала подайте заявление о трансляции паевого взноса в программу.");
466 }
467 eosio::check(program.available >= body + secure_part,
468 std::string{"MARKETPLACE_SHARE_SHORTFALL: Недостаточно свободного паевого Стола заказов на заказ: требуется "} +
469 (body + secure_part).to_string() + ", доступно " + program.available.to_string() +
470 ". Сначала подайте заявление о трансляции паевого взноса в программу.");
471}
472
483inline void lock_order_body(eosio::name coopname, eosio::name orderer,
484 const checksum256& order_hash, const eosio::asset& body,
485 const eosio::asset& share_taken, const std::string& memo) {
486 if (body.amount <= 0) return;
488 const eosio::asset share_left = program.available > share_taken
489 ? program.available - share_taken
490 : eosio::asset(0, _root_govern_symbol);
491 eosio::check(share_left >= body,
492 std::string{"MARKETPLACE_SHARE_SHORTFALL: Недостаточно свободного паевого Стола заказов на паевой резерв: требуется "} +
493 body.to_string() + ", доступно " + share_left.to_string() +
494 ". Сначала подайте заявление о трансляции паевого взноса в программу.");
498 body, orderer, order_hash, memo);
499}
500
505inline void lock_secure_part(eosio::name coopname, eosio::name orderer,
506 const checksum256& order_hash,
507 const eosio::asset& amount, const std::string& memo) {
508 if (amount.amount <= 0) return;
512 amount, orderer, order_hash, memo);
513}
514
517inline void refund_secure_part(eosio::name coopname, const order& o, const eosio::asset& amount) {
518 if (amount.amount <= 0) return;
522 amount, o.orderer, o.hash,
524}
525
528inline void move_secure_part_to_due(eosio::name coopname, const order& o, const eosio::asset& amount) {
529 if (amount.amount <= 0) return;
533 amount, o.orderer, o.hash,
535}
536
539inline void refund_secure_part_if_any(eosio::name coopname, const order& o) {
541}
542
546inline void refund_order_full(eosio::name coopname, const order& o) {
550 o.total_cost, o.orderer, o.hash,
552 refund_secure_part_if_any(coopname, o);
553}
554
557inline constexpr uint64_t REFUSAL_PENALTY_PERCENT = 50;
558
562 o.issue_statement.emplace(document2{});
563 o.issue_protocol.emplace(document2{});
564 o.issue_act1 = document2{};
565 o.issue_act2 = document2{};
567 o.fact_cost = o.total_cost;
568}
569
571inline eosio::asset refusal_penalty_share(const eosio::asset& base) {
573}
574
585inline void retain_refusal_penalty(eosio::name coopname, const order& o) {
586 // ── Тело заказа 50/50 ──
587 const eosio::asset penalty_body = refusal_penalty_share(o.total_cost);
588 const eosio::asset refund_body = o.total_cost - penalty_body;
589
590 if (refund_body.amount > 0) {
594 refund_body, o.orderer, o.hash,
596 }
597 if (penalty_body.amount > 0) {
601 penalty_body, o.orderer, o.hash,
603 }
604
605 // ── Обеспечительная часть 50/50 ──
606 const eosio::asset fee = get_order_membership_fee(o);
607 const eosio::asset penalty_fee = refusal_penalty_share(fee);
608 refund_secure_part(coopname, o, fee - penalty_fee);
609 move_secure_part_to_due(coopname, o, penalty_fee);
610 // Удержанное списывается участку целиком по окончании текущего периода
611 // (счётчики списания, задача 99D-33).
612 Dues::note_retained(coopname, o, penalty_body + penalty_fee);
613}
614
615// ── Факты Стола заказов для других контрактов (shared-слой, задача 99D-16) ──
616// Код других контрактов таблиц marketplace напрямую не читает: участок,
617// выход пайщика и прочие проверки спрашивают Стол заказов только этими методами.
618
621inline bool has_orders_at_branch(eosio::name coopname, eosio::name braname) {
622 orders_index orders(_marketplace, coopname.value);
623 auto by_delivery = orders.get_index<"bydelivbra"_n>();
624 if (by_delivery.find(braname.value) != by_delivery.end()) return true;
625 auto by_accept = orders.get_index<"byacceptbra"_n>();
626 return by_accept.find(braname.value) != by_accept.end();
627}
628
636inline bool has_open_return_request(eosio::name coopname, eosio::name username) {
637 return_requests_index requests(_marketplace, coopname.value);
638 auto by_orderer = requests.get_index<"byorderer"_n>();
639 return by_orderer.find(username.value) != by_orderer.end();
640}
641
651inline bool has_open_return_in_due(eosio::name coopname, eosio::name username,
652 eosio::name braname, uint32_t period) {
653 return_requests_index requests(_marketplace, coopname.value);
654 auto by_orderer = requests.get_index<"byorderer"_n>();
655 for (auto it = by_orderer.lower_bound(username.value);
656 it != by_orderer.end() && it->orderer == username; ++it) {
657 const auto o = get_order_by_hash(coopname, it->original_order_hash);
658 if (!o.has_value()) continue;
659 if (o->delivery_braname == braname &&
660 Dues::maturity_period(coopname, o->warranty_until) == period) return true;
661 }
662 return false;
663}
664
665inline void check_member_can_exit(eosio::name coopname, eosio::name username) {
666 eosio::check(!has_open_return_request(coopname, username),
667 "Выход из кооператива невозможен: открыто заявление на гарантийный возврат в Столе заказов — дождитесь его рассмотрения");
668}
669
676inline void settle_due_on_exit(eosio::name actor, eosio::name coopname,
677 eosio::name username, const checksum256& exit_hash) {
678 const eosio::asset balance =
680 if (balance.amount <= 0 && !Dues::has_member_rows(coopname, username)) return;
681 eosio::action(eosio::permission_level{actor, "active"_n}, _marketplace, "exitdue"_n,
682 std::make_tuple(coopname, username, exit_hash)).send();
683}
684
685} // namespace Marketplace
static void apply(eosio::name actor, eosio::name coopname, eosio::name operation_code, eosio::name process_type, eosio::asset amount, eosio::name username, eosio::checksum256 process_hash, std::string memo)
Отправить inline action ledger2::apply.
Definition: ledger2.hpp:43
static constexpr eosio::symbol _unit_piece
Definition: consts.hpp:264
static constexpr eosio::symbol _root_govern_symbol
Definition: consts.hpp:257
#define HUNDR_PERCENTS
Definition: consts.hpp:156
static constexpr eosio::symbol _unit_liter
Definition: consts.hpp:263
static constexpr eosio::symbol _unit_kg
Definition: consts.hpp:262
static constexpr eosio::name _ledger2
Definition: consts.hpp:202
static constexpr eosio::name _marketplace
Definition: consts.hpp:193
permission_level
Definition: eosio.msig_tests.cpp:896
balance
Definition: eosio.token_tests.cpp:226
share_type amount
Definition: eosio.token_tests.cpp:174
Человекочитаемые memo для marketplace ledger2-операций.
void send(name contract, name action_name, name actor, Args &&... args)
Definition: actions.hpp:10
bool has_member_rows(eosio::name coopname, eosio::name username)
Есть ли у пайщика хоть одна строка счётчика (выход пайщика).
Definition: dues.hpp:85
uint32_t maturity_period(eosio::name coopname, eosio::time_point_sec warranty_until)
Период созревания заказа: по концу гарантийного срока; без гарантии — момент выдачи.
Definition: dues.hpp:42
void note_retained(eosio::name coopname, const order &o, const eosio::asset &amount)
Удержание при отказе от получения после акцепта: половина тела и половина обеспечительной части....
Definition: dues.hpp:191
std::string get_refusal_penalty_memo(uint64_t order_id)
Definition: memo.hpp:127
std::string get_secure_part_refund_memo(uint64_t order_id)
Definition: memo.hpp:46
std::string get_cancel_order_memo(uint64_t order_id)
Definition: memo.hpp:123
std::string get_secure_to_due_memo(uint64_t order_id)
Definition: memo.hpp:50
constexpr eosio::name COMPLETED
Definition: table_marketplace_orders.hpp:73
Canonical helpers контракта marketplace (Story 11.1).
Definition: dues.hpp:25
void check_return_request_branch(eosio::name coopname, const return_request &r, eosio::name braname)
Definition: marketplace.hpp:277
std::optional< order > get_order_by_hash(eosio::name coopname, const checksum256 &order_hash)
Definition: marketplace.hpp:110
void refund_secure_part(eosio::name coopname, const order &o, const eosio::asset &amount)
Definition: marketplace.hpp:517
return_request get_return_request_by_hash_or_fail(eosio::name coopname, const checksum256 &request_hash, const std::string &msg="Заявление на возврат не найдено по хэшу")
Definition: marketplace.hpp:247
void erase_order(eosio::name coopname, uint64_t order_id)
Definition: marketplace.hpp:208
eosio::multi_index< "orders"_n, order, eosio::indexed_by<"byhash"_n, eosio::const_mem_fun< order, checksum256, &order::by_hash > >, eosio::indexed_by<"byorderer"_n, eosio::const_mem_fun< order, uint64_t, &order::by_orderer > >, eosio::indexed_by<"byofferer"_n, eosio::const_mem_fun< order, uint64_t, &order::by_offerer > >, eosio::indexed_by<"bystatus"_n, eosio::const_mem_fun< order, uint64_t, &order::by_status > >, eosio::indexed_by<"bybatch"_n, eosio::const_mem_fun< order, checksum256, &order::by_batch > >, eosio::indexed_by<"byoffer"_n, eosio::const_mem_fun< order, checksum256, &order::by_offer > >, eosio::indexed_by<"bydelivbra"_n, eosio::const_mem_fun< order, uint64_t, &order::by_delivery_bra > >, eosio::indexed_by<"byacceptbra"_n, eosio::const_mem_fun< order, uint64_t, &order::by_accept_bra > > > orders_index
Definition: table_marketplace_orders.hpp:260
void clear_issue_documents(order &o)
Definition: marketplace.hpp:561
checksum256 get_payout_hash(const order &o)
Пакет выплаты заказа; заказ не включён в пакет — пустой хэш.
Definition: marketplace.hpp:158
eosio::asset calc_membership_fee(const eosio::asset &base, uint64_t fee_percent)
Definition: marketplace.hpp:440
uint64_t next_return_request_id(eosio::name coopname)
Definition: marketplace.hpp:222
std::optional< writeoff_proposal > get_writeoff_proposal_by_hash(eosio::name coopname, const checksum256 &proposal_hash)
Definition: marketplace.hpp:286
constexpr uint64_t DEFAULT_INITIATOR_SHARE_PERCENT
Definition: marketplace.hpp:389
constexpr uint64_t DEFAULT_MEMBERSHIP_FEE_PERCENT
Definition: marketplace.hpp:383
uint64_t get_initiator_share_percent(eosio::name coopname)
Definition: marketplace.hpp:407
UserWalletAvailable get_user_wallet_balance(eosio::name coopname, eosio::name wallet_id, eosio::name username)
Definition: marketplace.hpp:363
void move_secure_part_to_due(eosio::name coopname, const order &o, const eosio::asset &amount)
Definition: marketplace.hpp:528
payout get_payout_by_hash_or_fail(eosio::name coopname, const checksum256 &hash)
Пакет выплаты по хэшу либо отказ с кодом.
Definition: marketplace.hpp:172
void erase_writeoff_proposal(eosio::name coopname, uint64_t proposal_id)
Definition: marketplace.hpp:313
void check_member_can_exit(eosio::name coopname, eosio::name username)
Definition: marketplace.hpp:665
constexpr uint64_t REFUSAL_PENALTY_PERCENT
Definition: marketplace.hpp:557
void check_quantity(const eosio::asset &quantity)
Валидация количества: корректный asset, известная единица, положительное.
Definition: marketplace.hpp:50
void update_writeoff_proposal(eosio::name coopname, uint64_t proposal_id, const std::function< void(writeoff_proposal &)> &fn)
Definition: marketplace.hpp:303
eosio::asset get_accepted_cost(const order &o)
Definition: marketplace.hpp:148
eosio::asset pro_rata(const eosio::asset &total, int64_t part, int64_t whole)
Definition: marketplace.hpp:100
eosio::multi_index< "wroffprops"_n, writeoff_proposal, eosio::indexed_by<"byhash"_n, eosio::const_mem_fun< writeoff_proposal, checksum256, &writeoff_proposal::by_hash > >, eosio::indexed_by<"bystatus"_n, eosio::const_mem_fun< writeoff_proposal, uint64_t, &writeoff_proposal::by_status > > > writeoff_proposals_index
Definition: table_marketplace_writeoff_proposals.hpp:118
eosio::asset get_order_membership_fee(const order &o)
Обеспечительная часть паевого взноса заказа (ноль — не начислялась).
Definition: marketplace.hpp:447
eosio::asset refusal_penalty_share(const eosio::asset &base)
Удерживаемая часть суммы (округление вниз — остаток в пользу пайщика).
Definition: marketplace.hpp:571
bool has_open_return_in_due(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period)
Definition: marketplace.hpp:651
eosio::asset get_payout_withheld(const order &o)
Долг поставщика, уже удержанный при инициации выплаты; без суммы — ноль.
Definition: marketplace.hpp:153
bool has_open_return_request(eosio::name coopname, const order &o)
Definition: marketplace.hpp:231
void check_packaging(const eosio::asset &quantity, const eosio::asset &package_size)
Definition: marketplace.hpp:62
void lock_order_body(eosio::name coopname, eosio::name orderer, const checksum256 &order_hash, const eosio::asset &body, const eosio::asset &share_taken, const std::string &memo)
Definition: marketplace.hpp:483
void settle_due_on_exit(eosio::name actor, eosio::name coopname, eosio::name username, const checksum256 &exit_hash)
Definition: marketplace.hpp:676
eosio::asset calc_cost(const eosio::asset &quantity, const eosio::asset &unit_price, const eosio::asset &package_size=eosio::asset(0, _unit_piece))
Definition: marketplace.hpp:79
constexpr uint64_t DEFAULT_RETURN_SHARE_PERCENT
Definition: marketplace.hpp:394
void update_claim(eosio::name coopname, uint64_t claim_id, const std::function< void(warranty_claim &)> &fn)
Definition: marketplace.hpp:339
warranty_claim get_claim_by_hash_or_fail(eosio::name coopname, const checksum256 &claim_hash, const std::string &msg="Гарантийная претензия поставщику не найдена по хэшу")
Definition: marketplace.hpp:331
std::optional< payout > get_payout_by_hash(eosio::name coopname, const checksum256 &hash)
Пакет выплаты по хэшу; нет — пусто.
Definition: marketplace.hpp:163
void erase_return_request(eosio::name coopname, uint64_t request_id)
Definition: marketplace.hpp:266
std::optional< eosio::asset > get_asset_extension(const eosio::binary_extension< eosio::asset > &ext)
Definition: marketplace.hpp:140
writeoff_proposal get_writeoff_proposal_by_hash_or_fail(eosio::name coopname, const checksum256 &proposal_hash, const std::string &msg="Проект списания не найден по хэшу")
Definition: marketplace.hpp:295
uint64_t get_return_share_percent(eosio::name coopname)
Definition: marketplace.hpp:419
bool is_supplier_settlement_open(const order &o)
Definition: marketplace.hpp:202
void lock_secure_part(eosio::name coopname, eosio::name orderer, const checksum256 &order_hash, const eosio::asset &amount, const std::string &memo)
Definition: marketplace.hpp:505
void update_return_request(eosio::name coopname, uint64_t request_id, const std::function< void(return_request &)> &fn)
Definition: marketplace.hpp:255
eosio::multi_index< "claims"_n, warranty_claim, eosio::indexed_by<"byhash"_n, eosio::const_mem_fun< warranty_claim, checksum256, &warranty_claim::by_hash > >, eosio::indexed_by<"bysupplier"_n, eosio::const_mem_fun< warranty_claim, uint64_t, &warranty_claim::by_supplier > >, eosio::indexed_by<"bystatus"_n, eosio::const_mem_fun< warranty_claim, uint64_t, &warranty_claim::by_status > >, eosio::indexed_by<"byorigorder"_n, eosio::const_mem_fun< warranty_claim, uint64_t, &warranty_claim::by_original_order > > > warranty_claims_index
Definition: table_marketplace_warranty_claims.hpp:82
std::optional< warranty_claim > get_claim_by_hash(eosio::name coopname, const checksum256 &claim_hash)
Definition: marketplace.hpp:322
order get_order_by_hash_or_fail(eosio::name coopname, const checksum256 &order_hash, const std::string &msg="Заказ не найден по хэшу")
Definition: marketplace.hpp:118
bool has_orders_at_branch(eosio::name coopname, eosio::name braname)
Definition: marketplace.hpp:621
const kuperiod & get_period_or_fail(kuperiods_index &periods, eosio::name braname, uint32_t period)
Definition: marketplace.hpp:430
void detach_order_from_payout(eosio::name coopname, const payout &p)
Definition: marketplace.hpp:187
uint64_t get_membership_fee_percent(eosio::name coopname)
Definition: marketplace.hpp:399
void update_order(eosio::name coopname, uint64_t order_id, const std::function< void(order &)> &fn)
Definition: marketplace.hpp:125
void refund_secure_part_if_any(eosio::name coopname, const order &o)
Definition: marketplace.hpp:539
void refund_order_full(eosio::name coopname, const order &o)
Definition: marketplace.hpp:546
void update_payout(eosio::name coopname, uint64_t payout_id, const std::function< void(payout &)> &fn)
Definition: marketplace.hpp:178
eosio::multi_index< "retrequests"_n, return_request, eosio::indexed_by<"byhash"_n, eosio::const_mem_fun< return_request, checksum256, &return_request::by_hash > >, eosio::indexed_by<"byorderer"_n, eosio::const_mem_fun< return_request, uint64_t, &return_request::by_orderer > >, eosio::indexed_by<"bystatus"_n, eosio::const_mem_fun< return_request, uint64_t, &return_request::by_status > >, eosio::indexed_by<"byorigorder"_n, eosio::const_mem_fun< return_request, uint64_t, &return_request::by_original_order > > > return_requests_index
Definition: table_marketplace_return_requests.hpp:124
void retain_refusal_penalty(eosio::name coopname, const order &o)
Definition: marketplace.hpp:585
void require_order_funding(eosio::name coopname, eosio::name orderer, const eosio::asset &body, const eosio::asset &secure_part)
Definition: marketplace.hpp:458
std::optional< return_request > get_return_request_by_hash(eosio::name coopname, const checksum256 &request_hash)
Definition: marketplace.hpp:238
bool is_valid_unit_symbol(const eosio::symbol &sym)
Definition: marketplace.hpp:45
eosio::name of(const Table &table, eosio::name coopname)
Definition: ram_payer.hpp:78
Definition: eosio.msig.hpp:34
constexpr eosio::name UNLOCK_ORDER
Возврат резерва при отмене Order'а или недовыдаче (TRANSFER w.mkt.order → w.mkt.share,...
Definition: operations.hpp:104
constexpr eosio::name SECURE_TO_DUE
Обеспечительная часть к списанию (TRANSFER w.mkt.fee → w.mkt.due по заказчику, без Dr/Cr — оба на 80)...
Definition: operations.hpp:120
constexpr eosio::name LOCK_FROM_SHARE
Паевой резерв из свободного паевого «Стола заказов» (TRANSFER w.mkt.share → w.mkt....
Definition: operations.hpp:103
constexpr eosio::name SECURE_PART_LOCK
Обеспечительная часть паевого взноса под заказ со свободного паевого «Стола заказов» (TRANSFER w....
Definition: operations.hpp:112
constexpr eosio::name SECURE_PART_REFUND
Возврат неиспользованной обеспечительной части на свободный паевой «Стола заказов» (TRANSFER w....
Definition: operations.hpp:113
constexpr eosio::name REFUSAL_PENALTY
Удержание 50% тела заказа при отказе пайщика от получения после акцепта поставщиком (TRANSFER w....
Definition: operations.hpp:114
constexpr eosio::name SUPPLY
Прямая поставка-приобретение имущества (5 операций: o.mkt.lock + o.mkt.unlock + o....
Definition: processes.hpp:75
action(permission_level{ _gateway, "active"_n}, _gateway, "adduser"_n, std::make_tuple(coopname, deposit->username, to_spread, to_circulation, eosio::current_time_point(), true)).send()
Definition: marketplace.hpp:357
bool exists
Definition: marketplace.hpp:360
eosio::asset blocked
Definition: marketplace.hpp:359
eosio::asset available
Definition: marketplace.hpp:358
On-chain Order — анкер процесса p.mkt.supply.
Definition: table_marketplace_orders.hpp:149
eosio::name orderer
пайщик-заказчик
Definition: table_marketplace_orders.hpp:153
eosio::binary_extension< eosio::asset > payout_withheld
Definition: table_marketplace_orders.hpp:218
checksum256 hash
process_hash для p.mkt.supply
Definition: table_marketplace_orders.hpp:151
eosio::binary_extension< eosio::asset > accepted_cost
Definition: table_marketplace_orders.hpp:225
eosio::asset membership_fee
Definition: table_marketplace_orders.hpp:205
eosio::binary_extension< document2 > issue_statement
Definition: table_marketplace_orders.hpp:210
eosio::asset fact_cost
actual_quantity * unit_price / 10^precision (после issueact2)
Definition: table_marketplace_orders.hpp:166
eosio::binary_extension< document2 > issue_protocol
Definition: table_marketplace_orders.hpp:213
uint64_t id
внутренний ID
Definition: table_marketplace_orders.hpp:150
eosio::asset quantity
заказанное количество (asset с символом единицы KG/LTR/PCS, Эпик 17)
Definition: table_marketplace_orders.hpp:161
eosio::name payout_status
Locked Decision L12 — состояние выплаты поставщику через gateway (см. namespace OrderPayoutStatus)
Definition: table_marketplace_orders.hpp:183
eosio::asset total_cost
quantity * unit_price / 10^precision (заблокированная сумма)
Definition: table_marketplace_orders.hpp:165
document2 issue_act2
Акт приёма-передачи (1115) — закрывающая подпись председателя участка выдачи (issueact2); слот прежне...
Definition: table_marketplace_orders.hpp:181
eosio::asset actual_quantity
фактически выданное (issueact2); до issueact2 == quantity
Definition: table_marketplace_orders.hpp:162
document2 issue_act1
Акт приёма-передачи (1115) — первая подпись заказчика (issueact1); слот прежнего issue_act_signiss1.
Definition: table_marketplace_orders.hpp:180
eosio::binary_extension< checksum256 > payout_hash
Definition: table_marketplace_orders.hpp:231
uint64_t return_request_id
0 если активного гарантийного возврата нет
Definition: table_marketplace_orders.hpp:186
On-chain Заявление на гарантийный возврат — анкер процесса p.mkt.return.
Definition: table_marketplace_return_requests.hpp:69
checksum256 original_order_hash
process_hash оригинального p.mkt.supply
Definition: table_marketplace_return_requests.hpp:76
On-chain гарантийная претензия поставщику — анкер процесса p.mkt.claim (компонент 68,...
Definition: table_marketplace_warranty_claims.hpp:48
On-chain Проект решения совета о списании скоропорта — анкер процесса p.mkt.wroff.
Definition: table_marketplace_writeoff_proposals.hpp:92
Definition: document_core.hpp:27
Итог прогона списания обеспечительной части по кооперативному участку Стола заказов (задача 99D-21,...
Definition: table_marketplace_periods.hpp:33
static constexpr eosio::name MARKETPLACE_SHARE_FUND
ЦПП «Стол Заказов» — свободный паевой пайщика в программе (USER_SHARED, счёт 80). Сюда возвращается о...
Definition: wallets.hpp:87
static constexpr eosio::name MARKETPLACE_SECURE_DUE
ЦПП «Стол Заказов» — обеспечительная часть паевого взноса пайщика к списанию в членский взнос (USER_S...
Definition: wallets.hpp:89
Пакет выплаты поставщику (решение владельца 19.11.2026).
Definition: table_marketplace_payouts.hpp:55
uint64_t id
суррогатный ключ (scope coopname)
Definition: table_marketplace_payouts.hpp:56
Definition: table_soviet_programs.hpp:17
eosio::binary_extension< eosio::asset > available
Definition: table_soviet_programs.hpp:38
eosio::multi_index< "userwallets"_n, userwallet, eosio::indexed_by<"byuserwallet"_n, eosio::const_mem_fun< userwallet, uint128_t, &userwallet::by_userwallet > >, eosio::indexed_by<"byuser"_n, eosio::const_mem_fun< userwallet, uint64_t, &userwallet::by_user > >, eosio::indexed_by<"bywallet"_n, eosio::const_mem_fun< userwallet, uint64_t, &userwallet::by_wallet > > > userwallets_index
Definition: table_ledger2_userwallets.hpp:48
eosio::singleton<"config"_n, mkt_config > mkt_config_singleton
Definition: table_marketplace_fee_config.hpp:46
eosio::multi_index< "payouts"_n, payout, eosio::indexed_by<"byhash"_n, eosio::const_mem_fun< payout, checksum256, &payout::by_hash > >, eosio::indexed_by<"byofferer"_n, eosio::const_mem_fun< payout, uint64_t, &payout::by_offerer > > > payouts_index
Definition: table_marketplace_payouts.hpp:75
eosio::multi_index< "kuperiods"_n, kuperiod, eosio::indexed_by<"bybranch"_n, eosio::const_mem_fun< kuperiod, uint64_t, &kuperiod::by_branch > >, eosio::indexed_by<"bybrperiod"_n, eosio::const_mem_fun< kuperiod, uint128_t, &kuperiod::by_branch_period > > > kuperiods_index
Definition: table_marketplace_periods.hpp:86
static uint128_t combine_ids(const uint64_t &x, const uint64_t &y)
Definition: utils.hpp:7