This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 284
/
cases.go
605 lines (558 loc) · 17.4 KB
/
cases.go
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
597
598
599
600
601
602
603
604
605
package db
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"math/big"
"sync"
"time"
"github.com/OpenBazaar/jsonpb"
"github.com/OpenBazaar/openbazaar-go/pb"
"github.com/OpenBazaar/openbazaar-go/repo"
)
type CasesDB struct {
modelStore
}
func NewCaseStore(db *sql.DB, lock *sync.Mutex) repo.CaseStore {
return &CasesDB{modelStore{db, lock}}
}
func (c *CasesDB) PutRecord(dispute *repo.DisputeCaseRecord) error {
c.lock.Lock()
defer c.lock.Unlock()
if dispute.PaymentCoin.String() == "" {
return errors.New("payment coin field is empty")
}
var readInt, buyerOpenedInt uint
if dispute.IsBuyerInitiated {
buyerOpenedInt = 1
}
stm := `insert or replace into cases(caseID, state, read, timestamp, buyerOpened, claim, buyerPayoutAddress, vendorPayoutAddress, paymentCoin, coinType) values(?,?,?,?,?,?,?,?,?,?)`
stmt, err := c.PrepareQuery(stm)
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(
dispute.CaseID,
int(dispute.OrderState),
readInt,
int(dispute.Timestamp.Unix()),
buyerOpenedInt,
dispute.Claim,
"",
"",
dispute.PaymentCoin.String(),
dispute.CoinType,
)
if err != nil {
return fmt.Errorf("update dispute case: %s", err.Error())
}
return nil
}
func (c *CasesDB) Put(caseID string, state pb.OrderState, buyerOpened bool, claim string, paymentCoin string, coinType string) error {
def, err := repo.AllCurrencies().Lookup(paymentCoin)
if err != nil {
return fmt.Errorf("verifying paymentCoin: %s", err.Error())
}
cc := def.CurrencyCode()
record := &repo.DisputeCaseRecord{
CaseID: caseID,
Claim: claim,
IsBuyerInitiated: buyerOpened,
OrderState: state,
PaymentCoin: &cc,
CoinType: coinType,
Timestamp: time.Now(),
}
return c.PutRecord(record)
}
func (c *CasesDB) UpdateBuyerInfo(caseID string, buyerContract *pb.RicardianContract, buyerValidationErrors []string, buyerPayoutAddress string, buyerOutpoints []*pb.Outpoint) error {
m := jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: true,
Indent: " ",
OrigName: false,
}
var buyerOut string
var err error
if buyerContract != nil {
buyerOut, err = m.MarshalToString(buyerContract)
if err != nil {
return err
}
}
buyerErrorsOut, err := json.Marshal(buyerValidationErrors)
if err != nil {
return err
}
var buyerOutpointsOut []byte
if buyerOutpoints != nil {
buyerOutpointsOut, err = json.Marshal(buyerOutpoints)
if err != nil {
return err
}
}
c.lock.Lock()
defer c.lock.Unlock()
_, err = c.db.Exec("update cases set buyerContract=?, buyerValidationErrors=?, buyerPayoutAddress=?, buyerOutpoints=? where caseID=?", buyerOut, string(buyerErrorsOut), buyerPayoutAddress, string(buyerOutpointsOut), caseID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) UpdateVendorInfo(caseID string, vendorContract *pb.RicardianContract, vendorValidationErrors []string, vendorPayoutAddress string, vendorOutpoints []*pb.Outpoint) error {
m := jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: true,
Indent: " ",
OrigName: false,
}
var vendorOut string
var err error
if vendorContract != nil {
vendorOut, err = m.MarshalToString(vendorContract)
if err != nil {
return err
}
}
vendorErrorsOut, err := json.Marshal(vendorValidationErrors)
if err != nil {
return err
}
var vendorOutpointsOut []byte
if vendorOutpoints != nil {
vendorOutpointsOut, err = json.Marshal(vendorOutpoints)
if err != nil {
return err
}
}
c.lock.Lock()
defer c.lock.Unlock()
_, err = c.db.Exec("update cases set vendorContract=?, vendorValidationErrors=?, vendorPayoutAddress=?, vendorOutpoints=? where caseID=?", vendorOut, string(vendorErrorsOut), vendorPayoutAddress, string(vendorOutpointsOut), caseID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) MarkAsRead(orderID string) error {
c.lock.Lock()
defer c.lock.Unlock()
_, err := c.db.Exec("update cases set read=? where caseID=?", 1, orderID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) MarkAsUnread(orderID string) error {
c.lock.Lock()
defer c.lock.Unlock()
_, err := c.db.Exec("update cases set read=? where caseID=?", 0, orderID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) MarkAsClosed(caseID string, resolution *pb.DisputeResolution) error {
if resolution == nil {
return errors.New("dispute resolution should not be nil")
}
m := jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: true,
Indent: " ",
OrigName: false,
}
var rOut string
var err error
rOut, err = m.MarshalToString(resolution)
if err != nil {
return err
}
c.lock.Lock()
defer c.lock.Unlock()
_, err = c.db.Exec("update cases set disputeResolution=?, state=? where caseID=?", rOut, int(pb.OrderState_RESOLVED), caseID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) Delete(orderID string) error {
c.lock.Lock()
defer c.lock.Unlock()
_, err := c.db.Exec("delete from cases where caseID=?", orderID)
if err != nil {
return err
}
return nil
}
func (c *CasesDB) GetAll(stateFilter []pb.OrderState, searchTerm string, sortByAscending bool, sortByRead bool, limit int, exclude []string) ([]repo.Case, int, error) {
c.lock.Lock()
defer c.lock.Unlock()
q := query{
table: "cases",
columns: []string{"caseID", "timestamp", "buyerContract", "vendorContract", "buyerOpened", "state", "read", "coinType", "paymentCoin"},
stateFilter: stateFilter,
searchTerm: searchTerm,
searchColumns: []string{"caseID", "timestamp", "claim"},
sortByAscending: sortByAscending,
sortByRead: sortByRead,
id: "caseID",
exclude: exclude,
limit: limit,
}
stm, args := filterQuery(q)
rows, err := c.db.Query(stm, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var ret []repo.Case
for rows.Next() {
var caseID, coinType, paymentCoin string
var buyerContract, vendorContract []byte
var timestamp, buyerOpenedInt, stateInt, readInt int
if err := rows.Scan(&caseID, ×tamp, &buyerContract, &vendorContract, &buyerOpenedInt, &stateInt, &readInt, &coinType, &paymentCoin); err != nil {
return ret, 0, err
}
read := false
if readInt > 0 {
read = true
}
buyerOpened := false
if buyerOpenedInt > 0 {
buyerOpened = true
}
total := new(big.Int)
var title, thumbnail, vendorId, vendorHandle, buyerId, buyerHandle string
contract := new(pb.RicardianContract)
err := jsonpb.UnmarshalString(string(buyerContract), contract)
if err != nil {
err = jsonpb.UnmarshalString(string(vendorContract), contract)
if err != nil {
log.Errorf("Error unmarshaling case contract: %s", err)
continue
}
}
var slug string
if len(contract.VendorListings) > 0 {
slug = contract.VendorListings[0].Slug
if contract.VendorListings[0].VendorID != nil {
vendorId = contract.VendorListings[0].VendorID.PeerID
vendorHandle = contract.VendorListings[0].VendorID.Handle
}
if contract.VendorListings[0].Item != nil {
title = contract.VendorListings[0].Item.Title
if len(contract.VendorListings[0].Item.Images) > 0 {
thumbnail = contract.VendorListings[0].Item.Images[0].Tiny
}
}
if contract.VendorListings[0].Metadata != nil && contract.VendorListings[0].Metadata.ContractType != pb.Listing_Metadata_CRYPTOCURRENCY {
coinType = ""
}
}
if contract.BuyerOrder != nil {
slug = contract.VendorListings[0].Slug
if contract.BuyerOrder.BuyerID != nil {
buyerId = contract.BuyerOrder.BuyerID.PeerID
buyerHandle = contract.BuyerOrder.BuyerID.Handle
}
if contract.BuyerOrder.Payment != nil {
if contract.BuyerOrder.Payment.BigAmount != "" {
total0, _ := new(big.Int).SetString(contract.BuyerOrder.Payment.BigAmount, 10)
total = total0
} else {
total1 := new(big.Int).SetUint64(contract.BuyerOrder.Payment.Amount)
total = total1
}
}
}
cv, err := repo.NewCurrencyValueWithLookup(total.String(), paymentCoin)
if err != nil {
return nil, 0, err
}
ret = append(ret, repo.Case{
CaseId: caseID,
Slug: slug,
Timestamp: time.Unix(int64(timestamp), 0),
Title: title,
Thumbnail: thumbnail,
Total: *cv,
VendorId: vendorId,
VendorHandle: vendorHandle,
BuyerId: buyerId,
BuyerHandle: buyerHandle,
BuyerOpened: buyerOpened,
CoinType: coinType,
PaymentCoin: paymentCoin,
State: pb.OrderState(stateInt).String(),
Read: read,
})
}
q.columns = []string{"Count(*)"}
q.limit = -1
q.exclude = []string{}
stm, args = filterQuery(q)
row := c.db.QueryRow(stm, args...)
var count int
err = row.Scan(&count)
if err != nil {
return ret, 0, err
}
return ret, count, nil
}
func (c *CasesDB) GetCaseMetadata(caseID string) (buyerContract, vendorContract *pb.RicardianContract, buyerValidationErrors, vendorValidationErrors []string, state pb.OrderState, read bool, timestamp time.Time, buyerOpened bool, claim string, resolution *pb.DisputeResolution, err error) {
c.lock.Lock()
defer c.lock.Unlock()
stmt, err := c.PrepareQuery("select buyerContract, vendorContract, buyerValidationErrors, vendorValidationErrors, state, read, timestamp, buyerOpened, claim, disputeResolution from cases where caseID=?")
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, err
}
defer stmt.Close()
var (
buyerCon []byte
vendorCon []byte
buyerErrors []byte
vendorErrors []byte
stateInt int
readInt *int
ts int
buyerOpenedInt int
disputeResolution []byte
)
err = stmt.QueryRow(caseID).Scan(&buyerCon, &vendorCon, &buyerErrors, &vendorErrors, &stateInt, &readInt, &ts, &buyerOpenedInt, &claim, &disputeResolution)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, err
}
brc := new(pb.RicardianContract)
if string(buyerCon) != "" {
err = jsonpb.UnmarshalString(string(buyerCon), brc)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, err
}
} else {
brc = nil
}
vrc := new(pb.RicardianContract)
if string(vendorCon) != "" {
err = jsonpb.UnmarshalString(string(vendorCon), vrc)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, err
}
} else {
vrc = nil
}
read = false
if readInt != nil && *readInt == 1 {
read = true
}
if buyerOpenedInt == 1 {
buyerOpened = true
}
var berr []string
if string(buyerErrors) != "" {
err = json.Unmarshal(buyerErrors, &berr)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, fmt.Errorf("unmarshal dispute case: %s", err.Error())
}
}
var verr []string
if string(vendorErrors) != "" {
err = json.Unmarshal(vendorErrors, &verr)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, fmt.Errorf("unmarshal dispute vendor errors: %s", err.Error())
}
}
resolution = new(pb.DisputeResolution)
if string(disputeResolution) != "" {
err = jsonpb.UnmarshalString(string(disputeResolution), resolution)
if err != nil {
return nil, nil, []string{}, []string{}, pb.OrderState(0), false, time.Time{}, false, "", nil, fmt.Errorf("unmarhsal dispute case resolution: %s", err.Error())
}
} else {
resolution = nil
}
return brc, vrc, berr, verr, pb.OrderState(stateInt), read, time.Unix(int64(ts), 0), buyerOpened, claim, resolution, nil
}
func (c *CasesDB) GetByCaseID(caseID string) (*repo.DisputeCaseRecord, error) {
c.lock.Lock()
defer c.lock.Unlock()
var (
buyerAddr string
buyerCon []byte
buyerInitiated bool
buyerOuts []byte
createdAt int64
isBuyerInitiated int
paymentCoin string
stateInt int
vendorAddr string
vendorCon []byte
vendorOuts []byte
)
stmt, err := c.PrepareQuery("select buyerContract, vendorContract, buyerPayoutAddress, vendorPayoutAddress, buyerOutpoints, vendorOutpoints, state, buyerOpened, timestamp, paymentCoin from cases where caseID=?")
if err != nil {
return nil, err
}
defer stmt.Close()
err = stmt.QueryRow(caseID).Scan(&buyerCon, &vendorCon, &buyerAddr, &vendorAddr, &buyerOuts, &vendorOuts, &stateInt, &isBuyerInitiated, &createdAt, &paymentCoin)
if err != nil {
return nil, err
}
def, err := repo.AllCurrencies().Lookup(paymentCoin)
if err != nil {
return nil, fmt.Errorf("validating payment coin: %s", err.Error())
}
if isBuyerInitiated == 1 {
buyerInitiated = true
}
brc := new(pb.RicardianContract)
if string(buyerCon) != "" {
err = jsonpb.UnmarshalString(string(buyerCon), brc)
if err != nil {
return nil, err
}
} else {
brc = nil
}
vrc := new(pb.RicardianContract)
if string(vendorCon) != "" {
err = jsonpb.UnmarshalString(string(vendorCon), vrc)
if err != nil {
return nil, err
}
} else {
vrc = nil
}
var buyerOutpointsOut []pb.Outpoint
if len(buyerOuts) > 0 {
err = json.Unmarshal(buyerOuts, &buyerOutpointsOut)
if err != nil {
return nil, err
}
}
var vendorOutpointsOut []pb.Outpoint
if len(vendorOuts) > 0 {
err = json.Unmarshal(vendorOuts, &vendorOutpointsOut)
if err != nil {
return nil, err
}
}
toPointer := func(op []pb.Outpoint) []*pb.Outpoint {
if len(op) == 0 {
return nil
}
ret := make([]*pb.Outpoint, len(op))
for i, o := range op {
var newOutpoint = o
ret[i] = &newOutpoint
}
return ret
}
cc := def.CurrencyCode()
return &repo.DisputeCaseRecord{
BuyerContract: brc,
BuyerOutpoints: toPointer(buyerOutpointsOut),
BuyerPayoutAddress: buyerAddr,
CaseID: caseID,
IsBuyerInitiated: buyerInitiated,
OrderState: pb.OrderState(stateInt),
PaymentCoin: &cc,
Timestamp: time.Unix(createdAt, 0),
VendorContract: vrc,
VendorOutpoints: toPointer(vendorOutpointsOut),
VendorPayoutAddress: vendorAddr,
}, nil
}
func (c *CasesDB) Count() int {
c.lock.Lock()
defer c.lock.Unlock()
row := c.db.QueryRow("select Count(*) from cases")
var count int
err := row.Scan(&count)
if err != nil {
log.Error(err)
}
return count
}
// GetDisputesForDisputeExpiryNotification returns []*repo.DisputeCaseRecord including
// each record which needs Notifications to be generated. Currently,
// notifications are generated at 0, 15, 30, 44, and 45 days after opening.
func (c *CasesDB) GetDisputesForDisputeExpiryNotification() ([]*repo.DisputeCaseRecord, error) {
c.lock.Lock()
defer c.lock.Unlock()
rows, err := c.db.Query("select caseID, state, buyerContract, vendorContract, timestamp, buyerOpened, lastDisputeExpiryNotifiedAt from cases where (lastDisputeExpiryNotifiedAt - timestamp) < ? and state = ?",
int(repo.ModeratorDisputeExpiry_lastInterval.Seconds()),
int(pb.OrderState_DISPUTED),
)
if err != nil {
return nil, fmt.Errorf("selecting dispute case: %s", err.Error())
}
result := make([]*repo.DisputeCaseRecord, 0)
for rows.Next() {
var (
orderState int
lastDisputeExpiryNotifiedAt int64
isBuyerInitiated int
buyerContract, vendorContract []byte
r = &repo.DisputeCaseRecord{
BuyerContract: &pb.RicardianContract{},
VendorContract: &pb.RicardianContract{},
}
timestamp = sql.NullInt64{}
)
if err := rows.Scan(&r.CaseID, &orderState, &buyerContract, &vendorContract, ×tamp, &isBuyerInitiated, &lastDisputeExpiryNotifiedAt); err != nil {
return nil, fmt.Errorf("scanning dispute case: %s", err.Error())
}
if len(buyerContract) > 0 {
if err := jsonpb.UnmarshalString(string(buyerContract), r.BuyerContract); err != nil {
return nil, fmt.Errorf("unmarshaling buyer contract: %s\n", err.Error())
}
}
if len(vendorContract) > 0 {
if err := jsonpb.UnmarshalString(string(vendorContract), r.VendorContract); err != nil {
return nil, fmt.Errorf("unmarshaling vendor contract: %s\n", err.Error())
}
}
if isBuyerInitiated != 0 {
r.IsBuyerInitiated = true
}
if timestamp.Valid {
r.Timestamp = time.Unix(timestamp.Int64, 0)
} else {
r.Timestamp = time.Now()
}
r.LastDisputeExpiryNotifiedAt = time.Unix(lastDisputeExpiryNotifiedAt, 0)
r.OrderState = pb.OrderState(orderState)
result = append(result, r)
}
return result, nil
}
// UpdateDisputesLastDisputeExpiryNotifiedAt accepts []*repo.DisputeCaseRecord and updates
// each DisputeCaseRecord by their CaseID to the set LastDisputeExpiryNotifiedAt value. The
// update will be attempted atomically with a rollback attempted in the event of
// an error.
func (c *CasesDB) UpdateDisputesLastDisputeExpiryNotifiedAt(disputeCases []*repo.DisputeCaseRecord) error {
c.lock.Lock()
defer c.lock.Unlock()
tx, err := c.BeginTransaction()
if err != nil {
return fmt.Errorf("begin update disputes transaction: %s", err.Error())
}
for _, d := range disputeCases {
_, err = tx.Exec("update cases set lastDisputeExpiryNotifiedAt = ? where caseID = ?", int(d.LastDisputeExpiryNotifiedAt.Unix()), d.CaseID)
if err != nil {
if rErr := tx.Rollback(); rErr != nil {
return fmt.Errorf("update dispute case: (%s) w rollback error: (%s)", err.Error(), rErr.Error())
}
return fmt.Errorf("update dispute case: %s", err.Error())
}
}
if err = tx.Commit(); err != nil {
if rErr := tx.Rollback(); rErr != nil {
return fmt.Errorf("commit dispute case: (%s) w rollback error: (%s)", err.Error(), rErr.Error())
}
return fmt.Errorf("commit disputes case: %s", err.Error())
}
return nil
}