-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
2389 lines (2099 loc) · 73.3 KB
/
main.rs
File metadata and controls
2389 lines (2099 loc) · 73.3 KB
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use actix_files::Files;
use actix_session::{CookieSession, Session};
use actix_web::{http, middleware, web, App, HttpRequest, HttpResponse, HttpServer, Result};
use askama::Template;
use std::collections::HashMap;
use chrono::{DateTime, Duration, NaiveDateTime, TimeZone, Utc};
use data::get_distributor;
use sqlx::mysql::MySqlPool;
use sqlx::Done;
use sqlx::Row;
use std::env;
use std::str::FromStr;
use std::sync::Arc;
use argon2::{self, Config};
extern crate crypto;
extern crate rand;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use rand::Rng;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
#[macro_use]
extern crate lazy_static;
use serde::{Deserialize, Serialize};
use validator::{Validate, ValidationError};
use async_std::sync::Mutex;
use once_cell::sync::Lazy;
// Wrapper for the MySQLPool
#[derive(Clone)]
pub struct MySQL {
conn: MySqlPool,
}
/* FORMS AND POST */
#[derive(Deserialize)]
struct OrderForm {
firstname: String,
lastname: String,
tel: String,
from_email: String,
to_email: String,
to_firstname: String,
to_lastname: String,
voucher: u64,
amount: f64,
}
#[derive(Deserialize)]
struct PaymentHook {
id: String,
}
#[derive(Deserialize)]
struct VoucherUpdateForm {
hash: String,
used: bool,
balance: f64,
}
#[derive(Deserialize)]
struct AdminLoginForm {
admin_username: String,
admin_password: String,
}
#[derive(Deserialize)]
struct MijnZaakUpdateForm {
description: String,
email: String,
tel: String,
address: String,
postalcode: String,
city: String,
}
#[derive(Deserialize)]
struct AdminVouchersUpdateJson {
three_option_vouchers: std::vec::Vec<u64>,
price_range_voucher: PriceRangeJson,
label_vouchers: std::vec::Vec<LabelVoucherJson>,
days_valid: u64,
one_use_only: bool,
}
#[derive(Deserialize)]
struct PriceRangeJson {
min_amount: u64,
max_amount: u64,
auto_amount: u64,
}
#[derive(Deserialize)]
struct LabelVoucherJson {
title: String,
amount: u64,
description: String,
}
/* TEMPLATES */
// Business templates
#[derive(Template)]
#[template(path = "index.html")]
struct Index<'a> {
distributor: &'a Distributor,
distributor_vouchers: &'a std::vec::Vec<DistributorVoucher>,
}
#[derive(Template)]
#[template(path = "bestel.html")]
struct Bestel<'a> {
distributor_vouchers: &'a std::vec::Vec<DistributorVoucher>,
first_distributor_voucher: &'a DistributorVoucher,
}
#[derive(Template)]
#[template(path = "bevestig.html")]
struct Bevestig {
payment_url: String,
voucher_price: String,
total: String,
from_str: String,
to_str: String,
}
#[derive(Template)]
#[template(path = "faq.html")]
struct Faq;
#[derive(Template)]
#[template(path = "bon_mobile.html")]
struct VoucherPageMobile {
number_code: String,
distributor_name: String,
balance: String,
expiration_date: String,
receiver_name: String,
}
#[derive(Template)]
#[template(path = "bon_desktop.html")]
struct VoucherPageDesktop {
number_code: String,
distributor_name: String,
balance: String,
expiration_date: String,
receiver_name: String,
}
#[derive(Template)]
#[template(path = "success.html")]
struct Success {
title: String,
message: String,
}
#[derive(Template)]
#[template(path = "niet-gelukt.html")]
struct Failed;
#[derive(Template)]
#[template(path = "scanner/scanner.html")]
struct Scanner;
#[derive(Template)]
#[template(path = "scanner/login.html")]
struct ScannerLogin;
#[derive(Template)]
#[template(path = "404.html")]
struct Error404;
// Administrator templates
#[derive(Template)]
#[template(path = "admin/login.html")]
struct AdminLogin {
distributor_name: String,
login_status: String,
}
#[derive(Template)]
#[template(path = "admin/mijn-zaak.html")]
struct AdminDashboardMijnZaak {
distributor: Distributor,
}
#[derive(Template)]
#[template(path = "admin/cadeaubonnen.html")]
struct AdminDashboardCadeaubonnen<'a> {
// Three price vouchers
three_price_voucher_a: f64,
three_price_voucher_b: f64,
three_price_voucher_c: f64,
three_price_voucher_max_days: u16,
three_price_voucher_one_use_only: bool,
// Price range vouchers
price_range_voucher_min: f64,
price_range_voucher_max: f64,
price_range_voucher_auto: f64,
price_range_voucher_max_days: u16,
price_range_voucher_one_use_only: bool,
// Label vouchers
label_vouchers: &'a Vec<LabelVoucherData>,
label_voucher_max_days: u16,
// Currently active voucher
currently_active: Option<VoucherType>,
}
struct LabelVoucherData {
title: String,
amount: u64,
description: String,
days_valid: u16,
}
impl Default for LabelVoucherData {
fn default() -> Self {
LabelVoucherData {
title: "".to_string(),
amount: 10 as u64,
description: "".to_string(),
days_valid: 90,
}
}
}
#[derive(Template)]
#[template(path = "admin/bestellingen.html")]
struct AdminDashboardBestellingen;
#[derive(Deserialize, Serialize)]
struct AdminOrderTableData {
id: u64,
purchase_amount: f64,
payment_status: i16,
purchase_date: String,
client_name: String,
}
#[derive(Deserialize, Serialize, Template)]
#[template(path = "admin/bestelling.html")]
struct AdminOrderData {
voucher: Voucher,
}
#[derive(Deserialize, Debug)]
pub struct AdminOrderFilterParams {
amount: u64,
search_query: Option<String>,
min_amount: Option<f64>,
max_amount: Option<f64>,
min_date: Option<String>,
max_date: Option<String>,
statusses: Option<String>,
}
#[derive(Template)]
#[template(path = "admin/wachtwoord.html")]
struct AdminDashboardWachtwoord;
#[derive(Template)]
#[template(path = "admin/help.html")]
struct AdminDashboardHelp;
#[derive(Deserialize, Serialize, PartialEq, Debug, FromPrimitive)]
enum OrderStatus {
Failed = 0,
Paid = 1,
}
/* OBJECTS */
// Business OBJECTS
#[derive(Serialize, Deserialize, Clone)]
pub struct Distributor {
id: u64,
name: String,
email: String,
tel: String,
address: String,
location: Location,
subdomain: String,
description: String,
//#[serde(skip_serializing)]
bankaccountnr: String,
btw_nr: String,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Client {
id: u64,
firstname: String,
lastname: String,
email: String,
tel: String,
saved_account: bool,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct Sale {
id: u64,
client: Client,
amount: f64,
payment_id: String,
paid: bool,
purchase_date: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(Deserialize, Serialize)]
pub struct Voucher {
id: u64,
sale: Sale,
receiver_email: String,
receiver_name: String,
distributorvoucher: DistributorVoucher,
balance: f64,
used: bool,
#[serde(skip_serializing)]
expiration_date: chrono::DateTime<chrono::Utc>,
hash_code: String,
number_code: String,
version: i64,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
enum VoucherType {
ThreeOptionVoucher,
RangeVoucher,
LabelVoucher,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Location {
id: u64,
postalcode: String,
city: String,
}
#[derive(Deserialize, Serialize)]
pub struct DistributorVoucher {
id: u64,
distributor: Distributor,
voucher_type: VoucherType,
amount: f64,
min_amount: f64,
max_amount: f64,
label: String,
description: String,
days_valid: u16,
active: bool,
one_use_only: bool,
create_date: Option<chrono::DateTime<chrono::Utc>>,
}
// Administrator objects
#[derive(Serialize, Deserialize, Clone)]
pub struct DistributorUser {
id: u64,
//#[serde(skip_serializing)]
username: String,
//#[serde(skip_serializing)]
password: String,
distributor: Distributor,
display_name: String,
}
impl DistributorUser {
pub async fn create(user: &mut DistributorUser, mysql: &web::Data<MySQL>) -> u64 {
user.hash_password();
let result = sqlx::query("INSERT INTO distributoruser (username, password, distributor, display_name) VALUES (?,?,?,?)")
.bind(&user.username)
.bind(&user.password)
.bind(&user.distributor.id)
.bind(&user.display_name)
.execute(&mysql.conn).await;
match result {
Err(e) => {
println!("Error: {}", e);
0
}
Ok(r) => r.last_insert_id(),
}
}
pub fn hash_password(&mut self) -> Result<(), argon2::Error> {
let salt: [u8; 32] = rand::thread_rng().gen();
let config = Config::default();
self.password = argon2::hash_encoded(self.password.as_bytes(), &salt, &config)
.map_err(|e| argon2::Error::from(e))
.unwrap();
Ok(())
}
pub fn verify_password(&self, password: &[u8]) -> Result<bool, argon2::Error> {
argon2::verify_encoded(&self.password, password).map_err(|e| argon2::Error::from(e))
}
pub async fn get_by_username(
username: &String,
mysql: &web::Data<MySQL>,
) -> Option<DistributorUser> {
let mut result = sqlx::query("SELECT ID, username, password, distributor, display_name FROM distributoruser WHERE username = ?")
.bind(&username)
.fetch_one(&mysql.conn).await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(DistributorUser {
id: r.try_get("ID").unwrap(),
username: r.try_get("username").unwrap(),
password: r.try_get("password").unwrap(),
distributor: get_distributor(mysql, r.try_get("distributor").unwrap())
.await
.unwrap(),
display_name: r.try_get("display_name").unwrap(),
}),
}
}
}
impl FromStr for VoucherType {
type Err = ();
fn from_str(input: &str) -> Result<VoucherType, Self::Err> {
match &*input.to_lowercase() {
"threeoptionvoucher" => Ok(VoucherType::ThreeOptionVoucher),
"rangevoucher" => Ok(VoucherType::RangeVoucher),
"labelvoucher" => Ok(VoucherType::LabelVoucher),
_ => Err(()),
}
}
}
impl std::fmt::Display for VoucherType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl FromStr for OrderStatus {
type Err = ();
fn from_str(input: &str) -> Result<OrderStatus, Self::Err> {
match &*input.to_lowercase() {
"failed" => Ok(OrderStatus::Failed),
"paid" => Ok(OrderStatus::Paid),
_ => Err(()),
}
}
}
impl std::fmt::Display for OrderStatus {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
fn get_subdomain_part(full_domain: &str) -> &str {
full_domain.split(".").next().unwrap()
}
pub mod data {
use crate::data::Selector::*;
use crate::*;
use futures::TryStreamExt;
pub enum Selector {
ById(u64),
ByPaymentId(String),
ByHash(String),
ByNumberCode(String),
}
pub async fn get_distributor_by_subdomain(
mysql: &web::Data<MySQL>,
subdomain: &str,
) -> Option<Distributor> {
let mut result = sqlx::query("SELECT ID, name, email, tel, address, location, description, bankaccountnr, btw_nr FROM distributor WHERE subdomain = ?")
.bind(&subdomain)
.fetch_one(&mysql.conn).await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Distributor {
id: r.try_get("ID").unwrap(),
name: r.try_get("name").unwrap(),
email: r.try_get("email").unwrap(),
tel: r.try_get("tel").unwrap(),
address: r.try_get("address").unwrap(),
location: get_location(mysql, r.try_get("location").unwrap())
.await
.unwrap(),
subdomain: subdomain.to_string(),
description: r.try_get("description").unwrap(),
bankaccountnr: r.try_get("bankaccountnr").unwrap(),
btw_nr: r.try_get("btw_nr").unwrap(),
}),
}
}
pub async fn get_distributor(mysql: &web::Data<MySQL>, id: u64) -> Option<Distributor> {
let mut result = sqlx::query("SELECT name, email, tel, address, location, subdomain, description, bankaccountnr, btw_nr FROM distributor WHERE ID = ?")
.bind(&id)
.fetch_one(&mysql.conn).await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Distributor {
id: id,
name: r.try_get("name").unwrap(),
email: r.try_get("email").unwrap(),
tel: r.try_get("tel").unwrap(),
address: r.try_get("address").unwrap(),
location: get_location(mysql, r.try_get("location").unwrap())
.await
.unwrap(),
subdomain: r.try_get("subdomain").unwrap(),
description: r.try_get("description").unwrap(),
bankaccountnr: r.try_get("bankaccountnr").unwrap(),
btw_nr: r.try_get("btw_nr").unwrap(),
}),
}
}
pub async fn update_distributor(mysql: &web::Data<MySQL>, distributor: &Distributor) -> bool {
let location = get_id_of_location(mysql, &distributor.location).await;
if location.is_none() {
return false;
}
let result = sqlx::query("UPDATE distributor SET name=?, email=?, tel=?, address=?, location=?, subdomain=?, description=?, bankaccountnr=?, btw_nr=? WHERE ID = ?")
.bind(&distributor.name)
.bind(&distributor.email)
.bind(&distributor.tel)
.bind(&distributor.address)
.bind(&location.unwrap())
.bind(&distributor.subdomain)
.bind(&distributor.description)
.bind(&distributor.bankaccountnr)
.bind(&distributor.btw_nr)
.bind(&distributor.id)
.execute(&mysql.conn).await;
match result {
Err(e) => {
println!("Error: {}", e);
false
}
Ok(r) => r.rows_affected() > 0,
}
}
pub async fn add_client(mysql: &web::Data<MySQL>, client: &Client) -> u64 {
let result =
sqlx::query("INSERT INTO client (firstname, lastname, email, tel) VALUES (?,?,?,?)")
.bind(&client.firstname)
.bind(&client.lastname)
.bind(&client.email)
.bind(&client.tel)
.execute(&mysql.conn)
.await;
match result {
Err(e) => {
println!("Error: {}", e);
0
}
Ok(r) => r.last_insert_id(),
}
}
pub async fn get_client(mysql: &web::Data<MySQL>, id: u64) -> Option<Client> {
let mut result = sqlx::query(
"SELECT firstname, lastname, email, tel, saved_account FROM client WHERE ID = ?",
)
.bind(&id)
.fetch_one(&mysql.conn)
.await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Client {
id: id,
firstname: r.try_get("firstname").unwrap(),
lastname: r.try_get("lastname").unwrap(),
email: r.try_get("email").unwrap(),
tel: r.try_get("tel").unwrap(),
saved_account: r.try_get("saved_account").unwrap(),
}),
}
}
pub async fn add_sale(mysql: &web::Data<MySQL>, sale: &Sale) -> u64 {
let result = sqlx::query("INSERT INTO sale (client, amount, payment_id) VALUES (?,?,?)")
.bind(&sale.client.id)
.bind(&sale.amount)
.bind(&sale.payment_id)
.execute(&mysql.conn)
.await;
match result {
Err(e) => {
println!("Error: {}", e);
0
}
Ok(r) => r.last_insert_id(),
}
}
pub async fn get_sale(mysql: &web::Data<MySQL>, selector: Selector) -> Option<Sale> {
let (where_column, where_value) = match selector {
ById(id) => ("ID", id.to_string()),
ByPaymentId(payment_id) => ("payment_id", payment_id),
_ => ("", "".to_string()),
};
let sql = format!(
"SELECT ID, client, amount, payment_id, paid, purchase_date FROM sale WHERE {} = ?",
where_column
);
let mut result = sqlx::query(&sql)
.bind(&where_value)
.fetch_one(&mysql.conn)
.await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Sale {
id: r.try_get("ID").unwrap(),
client: get_client(&mysql, r.try_get("client").unwrap())
.await
.unwrap(),
amount: r.try_get("amount").unwrap(),
payment_id: r.try_get("payment_id").unwrap(),
paid: r.try_get("paid").unwrap(),
purchase_date: r.try_get("purchase_date").unwrap(),
}),
}
}
pub async fn update_sale(mysql: &web::Data<MySQL>, sale: &Sale, selector: Selector) -> bool {
let (where_column, where_value) = match selector {
ById(id) => ("ID", id.to_string()),
ByPaymentId(payment_id) => ("payment_id", payment_id),
_ => ("", "".to_string()),
};
let sql = format!(
"UPDATE sale SET client=?, amount=?, payment_id=?, paid=? WHERE {} = ?",
where_column
);
let mut result = sqlx::query(&sql)
.bind(&sale.client.id)
.bind(&sale.amount)
.bind(&sale.payment_id)
.bind(&sale.paid)
.bind(&where_value)
.execute(&mysql.conn)
.await;
match result {
Err(e) => {
println!("Error: {}", e);
false
}
Ok(r) => r.rows_affected() > 0,
}
}
pub async fn get_distributor_voucher(
mysql: &web::Data<MySQL>,
id: u64,
) -> Option<DistributorVoucher> {
let mut result = sqlx::query("SELECT distributor, voucher_type, amount, min_amount, max_amount, label, description, days_valid, active, one_use_only, create_date FROM distributorvoucher WHERE ID = ?")
.bind(&id)
.fetch_one(&mysql.conn).await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(DistributorVoucher {
id: id,
distributor: get_distributor(&mysql, r.try_get("distributor").unwrap())
.await
.unwrap(),
voucher_type: VoucherType::from_str(r.try_get("voucher_type").unwrap()).unwrap(),
amount: r.try_get("amount").unwrap(),
min_amount: r.try_get("min_amount").unwrap(),
max_amount: r.try_get("max_amount").unwrap(),
label: match r.try_get("label").unwrap() {
None => "".to_string(),
Some(v) => v,
},
description: match r.try_get("description").unwrap() {
None => "".to_string(),
Some(v) => v,
},
days_valid: r.try_get("days_valid").unwrap(),
active: r.try_get("active").unwrap(),
one_use_only: r.try_get("one_use_only").unwrap(),
create_date: r.try_get("create_date").unwrap(),
}),
}
}
pub async fn get_distributor_vouchers_by_distributor(
mysql: &web::Data<MySQL>,
id: u64,
) -> Option<std::vec::Vec<DistributorVoucher>> {
let mut result = sqlx::query(
"SELECT ID FROM distributorvoucher WHERE distributor = ? AND most_recent_of_Type=1",
)
.bind(&id)
.fetch(&mysql.conn);
let mut distributor_vouchers: std::vec::Vec<DistributorVoucher> = std::vec::Vec::new();
while let Some(row) = result.try_next().await.unwrap() {
distributor_vouchers.push(
get_distributor_voucher(&mysql, row.try_get("ID").unwrap())
.await
.unwrap(),
);
}
Some(distributor_vouchers)
}
pub async fn get_active_distributor_vouchers_by_distributor(
mysql: &web::Data<MySQL>,
id: u64,
) -> Option<std::vec::Vec<DistributorVoucher>> {
let mut result =
sqlx::query("SELECT ID FROM distributorvoucher WHERE distributor = ? AND active=1")
.bind(&id)
.fetch(&mysql.conn);
let mut distributor_vouchers: std::vec::Vec<DistributorVoucher> = std::vec::Vec::new();
while let Some(row) = result.try_next().await.unwrap() {
distributor_vouchers.push(
get_distributor_voucher(&mysql, row.try_get("ID").unwrap())
.await
.unwrap(),
);
}
Some(distributor_vouchers)
}
pub async fn add_active_distributor_vouchers(
mysql: &web::Data<MySQL>,
distributor_vouchers: std::vec::Vec<DistributorVoucher>,
) -> bool {
if distributor_vouchers.len() == 0 {
return false;
}
let mut result = sqlx::query("UPDATE distributorvoucher SET most_recent_of_type=0 WHERE distributor=? AND upper(voucher_type)=upper(?)")
.bind(distributor_vouchers[0].distributor.id)
.bind(distributor_vouchers[0].voucher_type.to_string())
.execute(&mysql.conn).await;
let mut result = sqlx::query("UPDATE distributorvoucher SET active=0 WHERE distributor=?")
.bind(distributor_vouchers[0].distributor.id)
.execute(&mysql.conn)
.await;
for distributor_voucher in distributor_vouchers {
let mut result = sqlx::query("INSERT INTO distributorvoucher (distributor, voucher_type, amount, min_amount, max_amount, label, description, days_valid, active, one_use_only, most_recent_of_type) VALUES (?,?,?,?,?,?,?,?,?,?,1)")
.bind(distributor_voucher.distributor.id)
.bind(distributor_voucher.voucher_type.to_string())
.bind(distributor_voucher.amount)
.bind(distributor_voucher.min_amount)
.bind(distributor_voucher.max_amount)
.bind(distributor_voucher.label.to_string())
.bind(distributor_voucher.description.to_string())
.bind(distributor_voucher.days_valid)
.bind(distributor_voucher.active)
.bind(distributor_voucher.one_use_only)
.execute(&mysql.conn).await;
}
true
}
pub async fn get_distributor_vouchers_by_sale(
mysql: &web::Data<MySQL>,
id: u64,
) -> Option<std::vec::Vec<DistributorVoucher>> {
let sql = format!("SELECT distributorvoucher FROM voucher WHERE sale = ?");
let mut result = sqlx::query(&sql).bind(&id).fetch(&mysql.conn);
let mut distributor_vouchers: std::vec::Vec<DistributorVoucher> = std::vec::Vec::new();
while let Some(row) = result.try_next().await.unwrap() {
distributor_vouchers.push(
get_distributor_voucher(&mysql, row.try_get("distributorvoucher").unwrap())
.await
.unwrap(),
);
}
Some(distributor_vouchers)
}
pub async fn get_voucher(mysql: &web::Data<MySQL>, selector: Selector) -> Option<Voucher> {
let (where_column, where_value) = match selector {
ById(id) => ("ID", id.to_string()),
ByHash(hash) => ("hash_code", hash),
ByNumberCode(number_code) => ("number_code", number_code),
_ => ("", "".to_string()),
};
let sql = format!("SELECT ID, sale, receiver_email, receiver_name, distributorvoucher, balance, used, expiration_date, hash_code, number_code, version FROM voucher WHERE {} = ?", where_column);
let mut result = sqlx::query(&sql)
.bind(&where_value)
.fetch_one(&mysql.conn)
.await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Voucher {
id: r.try_get("ID").unwrap(),
sale: data::get_sale(&mysql, data::Selector::ById(r.try_get("sale").unwrap()))
.await
.unwrap(),
receiver_email: r.try_get("receiver_email").unwrap(),
receiver_name: r.try_get("receiver_name").unwrap(),
distributorvoucher: get_distributor_voucher(
&mysql,
r.try_get("distributorvoucher").unwrap(),
)
.await
.unwrap(),
balance: r.try_get("balance").unwrap(),
used: r.try_get("used").unwrap(),
expiration_date: r.try_get("expiration_date").unwrap(),
hash_code: r.try_get("hash_code").unwrap(),
number_code: r.try_get("number_code").unwrap(),
version: r.try_get("version").unwrap(),
}),
}
}
pub async fn add_voucher(mysql: &web::Data<MySQL>, voucher: &Voucher) -> u64 {
let result = sqlx::query("INSERT INTO voucher (sale, receiver_email, receiver_name, distributorvoucher, balance, used, expiration_date, hash_code, number_code, version) VALUES (?,?,?,?,?,?,?,?,?,?)")
.bind(&voucher.sale.id)
.bind(&voucher.receiver_email)
.bind(&voucher.receiver_name)
.bind(&voucher.distributorvoucher.id)
.bind(&voucher.balance)
.bind(&voucher.used)
.bind(&voucher.expiration_date)
.bind(&voucher.hash_code)
.bind(&voucher.number_code)
.bind(&voucher.version)
.execute(&mysql.conn).await;
match result {
Err(e) => {
println!("Error: {}", e);
0
}
Ok(r) => r.last_insert_id(),
}
}
pub async fn update_voucher(mysql: &web::Data<MySQL>, voucher: &Voucher) -> bool {
let sql = format!("UPDATE voucher SET balance=?, used=? WHERE ID = ?");
let mut result = sqlx::query(&sql)
.bind(&voucher.balance)
.bind(&voucher.used)
.bind(&voucher.id)
.execute(&mysql.conn)
.await;
match result {
Err(e) => {
println!("Error: {}", e);
false
}
Ok(r) => r.rows_affected() > 0,
}
}
pub async fn get_location(mysql: &web::Data<MySQL>, id: u64) -> Option<Location> {
let mut result = sqlx::query("SELECT postalcode, city FROM location WHERE ID = ?")
.bind(&id)
.fetch_one(&mysql.conn)
.await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(Location {
id: id,
postalcode: r.try_get("postalcode").unwrap(),
city: r.try_get("city").unwrap(),
}),
}
}
pub async fn get_id_of_location(mysql: &web::Data<MySQL>, location: &Location) -> Option<u64> {
let mut result = sqlx::query("SELECT ID FROM location WHERE postalcode = ? AND city = ?")
.bind(&location.postalcode)
.bind(&location.city)
.fetch_one(&mysql.conn)
.await;
match result {
Err(e) => {
println!("error: {:?}", e);
None
}
Ok(r) => Some(r.try_get("ID").unwrap()),
}
}
pub async fn get_all_orders(
mysql: &web::Data<MySQL>,
start: u64,
amount: u64,
mut filters: AdminOrderFilterParams,
distributor_id: u64,
) -> Vec<AdminOrderTableData> {
let mut statusses: std::vec::Vec<u16> = std::vec::Vec::new();
let mut where_str: String = "".to_string();
// Needed when filter for date is PREV_HOUR or MOST_RECENT_ACTIVATION
let current_date = chrono::offset::Utc::now();
let mut cmp_min_date: Option<String> = None;
let mut cmp_max_date: Option<String> = None;
if filters.min_amount.is_some() {
where_str = format!("{}{}", where_str, " (sale.amount >= ?) ");
} else {
where_str = format!("{}{}", where_str, " (? IS NULL) ");
}
if filters.max_amount.is_some() {
where_str = format!("{}{}", where_str, " AND (sale.amount < ?) ");
} else {
where_str = format!("{}{}", where_str, " AND (? IS NULL) ");
}
if filters.min_date.is_some() {
where_str = format!("{}{}", where_str, " AND (sale.purchase_date >= ?) ");
match filters.min_date.as_deref() {
Some("PREV_HOUR") => {
cmp_min_date = Some(
(current_date - chrono::Duration::hours(1))
.format("%Y-%m-%d %H:%M")
.to_string(),
);
}
Some("MOST_RECENT_ACTIVATION") => {
cmp_min_date = Some(
get_active_distributor_vouchers_by_distributor(mysql, distributor_id)
.await
.unwrap()[0]
.create_date
.unwrap()
.format("%Y-%m-%d %H:%M:%S")
.to_string(),
);