COOPENOMICS  v1
Кооперативная Экономика
dues.hpp
См. документацию.
1#pragma once
2
3#include <optional>
4#include <string>
5
6#include <eosio/crypto.hpp>
7#include <eosio/eosio.hpp>
8#include <eosio/time.hpp>
9
10#include "../../consts.hpp"
11#include "../../domain/table_marketplace_dues.hpp"
12#include "../../domain/table_marketplace_orders.hpp"
13#include "../branch/branch.hpp"
14
26
27using namespace eosio;
28
32inline uint32_t period_of(eosio::name coopname, eosio::time_point_sec at) {
33 return Branch::aid_period(coopname, at);
34}
35
37inline uint32_t current_period(eosio::name coopname) {
38 return period_of(coopname, eosio::time_point_sec(eosio::current_time_point().sec_since_epoch()));
39}
40
42inline uint32_t maturity_period(eosio::name coopname, eosio::time_point_sec warranty_until) {
43 if (warranty_until.sec_since_epoch() > 0) return period_of(coopname, warranty_until);
44 return current_period(coopname);
45}
46
55inline checksum256 charge_hash(eosio::name coopname, eosio::name username,
56 eosio::name braname, uint32_t period) {
57 const std::string seed = "p.mkt.due:" + coopname.to_string() + ":" + username.to_string() + ":" +
58 braname.to_string() + ":" + std::to_string(period);
59 return eosio::sha256(seed.data(), seed.size());
60}
61
65inline std::optional<uint64_t> find_member_id(eosio::name coopname, eosio::name username,
66 eosio::name braname, uint32_t period) {
67 kudues_index dues(_marketplace, coopname.value);
68 auto by_user = dues.get_index<"byuser"_n>();
69 for (auto it = by_user.lower_bound(username.value);
70 it != by_user.end() && it->username == username; ++it) {
71 if (it->braname == braname && it->period == period) return it->id;
72 }
73 return std::nullopt;
74}
75
76inline std::optional<kudue> find_member(eosio::name coopname, eosio::name username,
77 eosio::name braname, uint32_t period) {
78 const auto id = find_member_id(coopname, username, braname, period);
79 if (!id.has_value()) return std::nullopt;
80 kudues_index dues(_marketplace, coopname.value);
81 return dues.get(*id);
82}
83
85inline bool has_member_rows(eosio::name coopname, eosio::name username) {
86 kudues_index dues(_marketplace, coopname.value);
87 auto by_user = dues.get_index<"byuser"_n>();
88 return by_user.find(username.value) != by_user.end();
89}
90
91inline std::optional<uint64_t> find_counter_id(eosio::name coopname, eosio::name braname, uint32_t period) {
92 kucounters_index counters(_marketplace, coopname.value);
93 auto idx = counters.get_index<"bybrperiod"_n>();
94 auto it = idx.find(combine_ids(braname.value, period));
95 if (it == idx.end()) return std::nullopt;
96 return it->id;
97}
98
99inline std::optional<kucounter> find_counter(eosio::name coopname, eosio::name braname, uint32_t period) {
100 const auto id = find_counter_id(coopname, braname, period);
101 if (!id.has_value()) return std::nullopt;
102 kucounters_index counters(_marketplace, coopname.value);
103 return counters.get(*id);
104}
105
107inline uint64_t ensure_counter(eosio::name coopname, eosio::name braname, uint32_t period) {
108 const auto found = find_counter_id(coopname, braname, period);
109 if (found.has_value()) return *found;
110 kucounters_index counters(_marketplace, coopname.value);
111 const uint64_t id = counters.available_primary_key();
112 counters.emplace(RamPayer::of(counters), [&](auto& c) {
113 c.id = id;
114 c.braname = braname;
115 c.period = period;
116 c.turnover = eosio::asset(0, _root_govern_symbol);
117 c.secured = eosio::asset(0, _root_govern_symbol);
118 c.retained = eosio::asset(0, _root_govern_symbol);
119 c.orders = 0;
120 c.members = 0;
121 });
122 return id;
123}
124
126inline void take(eosio::asset& from, const eosio::asset& amount) {
127 from.amount = from.amount > amount.amount ? from.amount - amount.amount : 0;
128}
129
131template <typename Fn>
132inline void modify_counter_if_open(eosio::name coopname, eosio::name braname, uint32_t period, Fn&& fn) {
133 const auto id = find_counter_id(coopname, braname, period);
134 if (!id.has_value()) return;
135 kucounters_index counters(_marketplace, coopname.value);
136 counters.modify(counters.get(*id), RamPayer::of(counters), std::forward<Fn>(fn));
137}
138
142inline uint64_t ensure_member(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period) {
143 const auto found = find_member_id(coopname, username, braname, period);
144 if (found.has_value()) return *found;
145 kudues_index dues(_marketplace, coopname.value);
146 const uint64_t id = dues.available_primary_key();
147 dues.emplace(RamPayer::of(dues), [&](auto& d) {
148 d.id = id;
149 d.username = username;
150 d.braname = braname;
151 d.period = period;
152 d.turnover = eosio::asset(0, _root_govern_symbol);
153 d.due = eosio::asset(0, _root_govern_symbol);
154 d.retained = eosio::asset(0, _root_govern_symbol);
155 d.orders = 0;
156 });
157 modify_counter_if_open(coopname, braname, period, [&](auto& c) { c.members += 1; });
158 return id;
159}
160
167inline void note_issue(eosio::name coopname, const order& o, const eosio::asset& cost,
168 const eosio::asset& fee, eosio::time_point_sec warranty_until) {
169 if (fee.amount <= 0) return;
170 const uint32_t period = maturity_period(coopname, warranty_until);
171 const uint64_t counter_id = ensure_counter(coopname, o.delivery_braname, period);
172 kudues_index dues(_marketplace, coopname.value);
173 dues.modify(dues.get(ensure_member(coopname, o.orderer, o.delivery_braname, period)), RamPayer::of(dues), [&](auto& d) {
174 d.turnover += cost;
175 d.due += fee;
176 d.orders += 1;
177 });
178 kucounters_index counters(_marketplace, coopname.value);
179 counters.modify(counters.get(counter_id), RamPayer::of(counters), [&](auto& c) {
180 c.turnover += cost;
181 c.secured += fee;
182 c.orders += 1;
183 });
184}
185
191inline void note_retained(eosio::name coopname, const order& o, const eosio::asset& amount) {
192 if (amount.amount <= 0) return;
193 const uint32_t period = current_period(coopname);
194 const uint64_t counter_id = ensure_counter(coopname, o.delivery_braname, period);
195 kudues_index dues(_marketplace, coopname.value);
196 dues.modify(dues.get(ensure_member(coopname, o.orderer, o.delivery_braname, period)), RamPayer::of(dues),
197 [&](auto& d) { d.retained += amount; });
198 kucounters_index counters(_marketplace, coopname.value);
199 counters.modify(counters.get(counter_id), RamPayer::of(counters), [&](auto& c) { c.retained += amount; });
200}
201
210inline void note_return(eosio::name coopname, const order& o, const eosio::asset& cost, const eosio::asset& fee) {
211 if (fee.amount <= 0) return;
212 const uint32_t period = maturity_period(coopname, o.warranty_until);
213 const auto id = find_member_id(coopname, o.orderer, o.delivery_braname, period);
214 eosio::check(id.has_value(),
215 "MARKETPLACE_DUE_CHARGED: Обеспечительная часть по заказу уже списана по итогу периода — возврат с кошелька к списанию невозможен");
216 kudues_index dues(_marketplace, coopname.value);
217 const kudue row = dues.get(*id);
218 eosio::check(row.due >= fee,
219 std::string{"MARKETPLACE_DUE_EXCEEDS: К возврату заявлено больше, чем учтено к списанию: заявлено "} +
220 fee.to_string() + ", учтено " + row.due.to_string());
221 dues.modify(dues.get(*id), RamPayer::of(dues), [&](auto& d) {
222 take(d.turnover, cost);
223 d.due -= fee;
224 });
225 modify_counter_if_open(coopname, o.delivery_braname, period, [&](auto& c) {
226 take(c.turnover, cost);
227 take(c.secured, fee);
228 });
229}
230
237inline void release_member(eosio::name coopname, eosio::name username) {
238 kudues_index dues(_marketplace, coopname.value);
239 auto by_user = dues.get_index<"byuser"_n>();
240 for (auto it = by_user.lower_bound(username.value);
241 it != by_user.end() && it->username == username;
242 it = by_user.lower_bound(username.value)) {
243 const kudue row = *it;
244 modify_counter_if_open(coopname, row.braname, row.period, [&](auto& c) {
245 take(c.turnover, row.turnover);
246 take(c.secured, row.due);
247 take(c.retained, row.retained);
248 c.orders = c.orders > row.orders ? c.orders - row.orders : 0;
249 c.members = c.members > 0 ? c.members - 1 : 0;
250 });
251 by_user.erase(it);
252 }
253}
254
257inline eosio::asset member_total(eosio::name coopname, eosio::name username) {
258 eosio::asset total(0, _root_govern_symbol);
259 kudues_index dues(_marketplace, coopname.value);
260 auto by_user = dues.get_index<"byuser"_n>();
261 for (auto it = by_user.lower_bound(username.value);
262 it != by_user.end() && it->username == username; ++it) {
263 total += it->due;
264 total += it->retained;
265 }
266 return total;
267}
268
269} // namespace Marketplace::Dues
static constexpr eosio::symbol _root_govern_symbol
Definition: consts.hpp:257
static constexpr eosio::name _marketplace
Definition: consts.hpp:193
share_type amount
Definition: eosio.token_tests.cpp:174
uint32_t aid_period(eosio::name coopname, eosio::time_point_sec at)
Номер периода, за который считается предел материальной помощи.
Definition: branch.hpp:139
Счётчики обеспечительной части к списанию (задача 99D-33).
Definition: dues.hpp:25
bool has_member_rows(eosio::name coopname, eosio::name username)
Есть ли у пайщика хоть одна строка счётчика (выход пайщика).
Definition: dues.hpp:85
void note_return(eosio::name coopname, const order &o, const eosio::asset &cost, const eosio::asset &fee)
Гарантийный возврат принят: стоимость возвращённого и его обеспечительная часть снимаются со счётчико...
Definition: dues.hpp:210
std::optional< uint64_t > find_member_id(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period)
Definition: dues.hpp:65
uint32_t period_of(eosio::name coopname, eosio::time_point_sec at)
Definition: dues.hpp:32
std::optional< kucounter > find_counter(eosio::name coopname, eosio::name braname, uint32_t period)
Definition: dues.hpp:99
std::optional< kudue > find_member(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period)
Definition: dues.hpp:76
void take(eosio::asset &from, const eosio::asset &amount)
Вычитание не ниже нуля: возврат после округлений не делает счётчик отрицательным.
Definition: dues.hpp:126
eosio::asset member_total(eosio::name coopname, eosio::name username)
Definition: dues.hpp:257
void modify_counter_if_open(eosio::name coopname, eosio::name braname, uint32_t period, Fn &&fn)
Счётчик участка открыт (итог ещё не рассчитан) — поправить его суммы.
Definition: dues.hpp:132
void release_member(eosio::name coopname, eosio::name username)
Выход пайщика состоялся: его строки счётчиков стираются — остаток кошелька к списанию целиком списан ...
Definition: dues.hpp:237
uint32_t maturity_period(eosio::name coopname, eosio::time_point_sec warranty_until)
Период созревания заказа: по концу гарантийного срока; без гарантии — момент выдачи.
Definition: dues.hpp:42
std::optional< uint64_t > find_counter_id(eosio::name coopname, eosio::name braname, uint32_t period)
Definition: dues.hpp:91
checksum256 charge_hash(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period)
Хэш процесса списания строки счётчика — нитка p.mkt.due.
Definition: dues.hpp:55
void note_issue(eosio::name coopname, const order &o, const eosio::asset &cost, const eosio::asset &fee, eosio::time_point_sec warranty_until)
Выдача закрыта: стоимость выданного и обеспечительная часть по факту встают в счётчики периода,...
Definition: dues.hpp:167
uint32_t current_period(eosio::name coopname)
Период списания, идущий сейчас: его строки ещё копятся и не списываются.
Definition: dues.hpp:37
uint64_t ensure_counter(eosio::name coopname, eosio::name braname, uint32_t period)
Строка счётчика участка: найти либо завести пустую.
Definition: dues.hpp:107
uint64_t ensure_member(eosio::name coopname, eosio::name username, eosio::name braname, uint32_t period)
Definition: dues.hpp:142
void note_retained(eosio::name coopname, const order &o, const eosio::asset &amount)
Удержание при отказе от получения после акцепта: половина тела и половина обеспечительной части....
Definition: dues.hpp:191
eosio::name of(const Table &table, eosio::name coopname)
Definition: ram_payer.hpp:78
Definition: eosio.msig.hpp:34
On-chain Order — анкер процесса p.mkt.supply.
Definition: table_marketplace_orders.hpp:149
eosio::name orderer
пайщик-заказчик
Definition: table_marketplace_orders.hpp:153
time_point_sec warranty_until
now() + warranty_period_secs (заполняется в issueact2)
Definition: table_marketplace_orders.hpp:169
eosio::name delivery_braname
КУ выдачи (выбран пайщиком на createorder); проверка readyissue/issueact2/p.mkt.return через Branch::...
Definition: table_marketplace_orders.hpp:157
Счётчики обеспечительной части к списанию (задача 99D-33).
Definition: table_marketplace_dues.hpp:42
eosio::name braname
кооперативный участок выдачи — получатель членского взноса
Definition: table_marketplace_dues.hpp:45
uint32_t period
период списания (Branch::aid_period по концу гарантийного срока)
Definition: table_marketplace_dues.hpp:46
eosio::asset due
обеспечительная часть к списанию по ставкам итога (o.mkt.todue выдачи) за вычетом возвращённого
Definition: table_marketplace_dues.hpp:49
eosio::multi_index< "kucounters"_n, kucounter, eosio::indexed_by<"bybranch"_n, eosio::const_mem_fun< kucounter, uint64_t, &kucounter::by_branch > >, eosio::indexed_by<"bybrperiod"_n, eosio::const_mem_fun< kucounter, uint128_t, &kucounter::by_branch_period > > > kucounters_index
Definition: table_marketplace_dues.hpp:99
eosio::multi_index< "kudues"_n, kudue, eosio::indexed_by<"byuser"_n, eosio::const_mem_fun< kudue, uint64_t, &kudue::by_user > >, eosio::indexed_by<"bybranch"_n, eosio::const_mem_fun< kudue, uint64_t, &kudue::by_branch > >, eosio::indexed_by<"bybrperiod"_n, eosio::const_mem_fun< kudue, uint128_t, &kudue::by_branch_period > > > kudues_index
Definition: table_marketplace_dues.hpp:64
static uint128_t combine_ids(const uint64_t &x, const uint64_t &y)
Definition: utils.hpp:7