Skip to main content

br_fields/
str.rs

1use crate::datetime::Datetime;
2use crate::Field;
3use chrono::Local;
4use json::{object, JsonValue};
5use lazy_static::lazy_static;
6use rand::Rng;
7use regex::Regex;
8use std::sync::atomic::{AtomicU16, Ordering};
9
10/// 全局自增序列(每毫秒重置)
11static SEQ: AtomicU16 = AtomicU16::new(0);
12/// 字符串
13///
14/// * require 是否必填
15/// * field 字段名
16/// * mode 模式 string
17/// * title 字段描述
18/// * length 字段总长度(含小数位)
19/// * def 默认值
20/// * dec 后缀内容
21#[derive(Debug, Clone)]
22pub struct Str {
23    pub require: bool,
24    pub field: String,
25    pub mode: String,
26    pub title: String,
27    pub def: String,
28    pub length: usize,
29    pub show: bool,
30    pub describe: String,
31    pub example: JsonValue,
32}
33
34impl Str {
35    pub fn new(require: bool, field: &str, title: &str, length: usize, default: &str) -> Str {
36        Self {
37            require,
38            field: field.to_string(),
39            mode: "string".to_string(),
40            title: title.to_string(),
41            def: default.to_string(),
42            length,
43            show: true,
44            describe: "".to_string(),
45            example: JsonValue::Null,
46        }
47    }
48}
49
50impl Field for Str {
51    fn require(&mut self, require: bool) -> &mut Self {
52        self.require = require;
53        self
54    }
55
56    fn sql(&mut self, model: &str) -> String {
57        let not_null = if self.require { " not null" } else { "" };
58        match model {
59            "sqlite" => format!(
60                "`{}` varchar({}){} default '{}'",
61                self.field, self.length, not_null, self.def
62            ),
63            "pgsql" => {
64                let sql = format!(
65                    r#""{}" varchar({}) default '{}'"#,
66                    self.field, self.length, self.def
67                );
68                format!(
69                    "{} --{}|{}|{}|{}|{}",
70                    sql, self.mode, self.require, self.title, self.length, self.def
71                )
72            }
73            _ => {
74                let sql = format!(
75                    "`{}` varchar({}){} default '{}'",
76                    self.field, self.length, not_null, self.def
77                );
78                format!(
79                    "{} comment '{}|{}|{}|{}|{}'",
80                    sql, self.mode, self.require, self.title, self.length, self.def
81                )
82            }
83        }
84    }
85    fn hide(&mut self) -> &mut Self {
86        self.show = false;
87        self
88    }
89    fn describe(&mut self, text: &str) -> &mut Self {
90        self.describe = text.to_string();
91        self
92    }
93    fn field(&mut self) -> JsonValue {
94        let mut field = object! {};
95        field
96            .insert("require", JsonValue::from(self.require))
97            .unwrap();
98        field
99            .insert("field", JsonValue::from(self.field.clone()))
100            .unwrap();
101        field
102            .insert("mode", JsonValue::from(self.mode.clone()))
103            .unwrap();
104        field
105            .insert("title", JsonValue::from(self.title.clone()))
106            .unwrap();
107        field
108            .insert("length", JsonValue::from(self.length))
109            .unwrap();
110        field
111            .insert("def", JsonValue::from(self.def.clone()))
112            .unwrap();
113
114        field.insert("show", JsonValue::from(self.show)).unwrap();
115        field
116            .insert("describe", JsonValue::from(self.describe.clone()))
117            .unwrap();
118        field.insert("example", self.example.clone()).unwrap();
119
120        field
121    }
122
123    fn swagger(&mut self) -> JsonValue {
124        object! {
125            "type": self.mode.clone(),
126            "example": self.example.clone(),
127        }
128    }
129    fn example(&mut self, data: JsonValue) -> &mut Self {
130        self.example = data;
131        self
132    }
133}
134
135/// 密码
136///
137/// * field 字段名
138/// * mode 模式 pass
139/// * title 字段描述
140/// * length 字段总长度(含小数位)
141/// * default 默认值
142/// * empty 是否可空
143pub struct Pass {
144    pub require: bool,
145    pub field: String,
146    pub mode: String,
147    pub title: String,
148    pub def: String,
149    pub length: usize,
150    pub show: bool,
151    pub describe: String,
152    pub example: JsonValue,
153}
154
155impl Pass {
156    pub fn new(require: bool, field: &str, title: &str, length: usize, default: &str) -> Self {
157        Self {
158            require,
159            field: field.to_string(),
160            mode: "pass".to_string(),
161            title: title.to_string(),
162            def: default.to_string(),
163            length,
164            show: true,
165            describe: "".to_string(),
166            example: json::Null,
167        }
168    }
169    /// 从一组字母+数字的字符,创建随机密码
170    pub fn random_pass(len: usize) -> String {
171        let text = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
172        let mut code = "".to_string();
173        for _ in 0..len {
174            let index = rand::rng().random_range(0..=text.len() - 1);
175            let t = &text[index..=index];
176            code = format!("{}{}", code, t);
177        }
178        code
179    }
180}
181
182impl Field for Pass {
183    fn require(&mut self, require: bool) -> &mut Self {
184        self.require = require;
185        self
186    }
187
188    fn sql(&mut self, model: &str) -> String {
189        let not_null = if self.require { " not null" } else { "" };
190        match model {
191            "sqlite" => format!(
192                "`{}` varchar({}){} default '{}'",
193                self.field, self.length, not_null, self.def
194            ),
195            "pgsql" => {
196                let sql = format!(
197                    r#""{}" varchar({}) default '{}'"#,
198                    self.field, self.length, self.def
199                );
200                format!(
201                    "{} --{}|{}|{}|{}|{}",
202                    sql, self.mode, self.require, self.title, self.length, self.def
203                )
204            }
205            _ => {
206                let sql = format!(
207                    "`{}` varchar({}){} default '{}'",
208                    self.field, self.length, not_null, self.def
209                );
210                format!(
211                    "{} comment '{}|{}|{}|{}|{}'",
212                    sql, self.mode, self.require, self.title, self.length, self.def
213                )
214            }
215        }
216    }
217    fn hide(&mut self) -> &mut Self {
218        self.show = false;
219        self
220    }
221    fn describe(&mut self, text: &str) -> &mut Self {
222        self.describe = text.to_string();
223        self
224    }
225    fn field(&mut self) -> JsonValue {
226        let mut field = object! {};
227        field
228            .insert("require", JsonValue::from(self.require))
229            .unwrap();
230        field
231            .insert("field", JsonValue::from(self.field.clone()))
232            .unwrap();
233        field
234            .insert("mode", JsonValue::from(self.mode.clone()))
235            .unwrap();
236        field
237            .insert("title", JsonValue::from(self.title.clone()))
238            .unwrap();
239        field
240            .insert("length", JsonValue::from(self.length))
241            .unwrap();
242        field
243            .insert("def", JsonValue::from(self.def.clone()))
244            .unwrap();
245
246        field.insert("show", JsonValue::from(self.show)).unwrap();
247        field
248            .insert("describe", JsonValue::from(self.describe.clone()))
249            .unwrap();
250        field.insert("example", self.example.clone()).unwrap();
251
252        field
253    }
254
255    fn swagger(&mut self) -> JsonValue {
256        object! {
257            "type": self.mode.clone(),
258            "example": self.example.clone(),
259        }
260    }
261
262    fn example(&mut self, data: JsonValue) -> &mut Self {
263        self.example = data;
264        self
265    }
266}
267
268/// 自定义主键
269///
270/// * field 字段名
271/// * mode 模式
272/// * title 字段描述
273/// * length 字段总长度(含小数位)
274/// * def 默认值
275#[derive(Clone, Debug)]
276pub struct Key {
277    pub require: bool,
278    pub field: String,
279    pub mode: String,
280    pub title: String,
281    pub length: usize,
282
283    pub def: String,
284
285    pub auto: bool,
286    pub show: bool,
287    pub describe: String,
288    pub example: JsonValue,
289}
290
291impl Key {
292    pub fn new(require: bool, field: &str, title: &str, length: usize) -> Self {
293        Self {
294            require,
295            field: field.to_string(),
296            mode: "key".to_string(),
297            title: title.to_string(),
298            length,
299            auto: false,
300            show: true,
301            def: "".to_string(),
302            describe: "".to_string(),
303            example: JsonValue::Null,
304        }
305    }
306    pub fn auto(mut self, auto: bool) -> Self {
307        if auto {
308            self.length = 0;
309        }
310        self.auto = auto;
311        self
312    }
313}
314
315impl Field for Key {
316    fn require(&mut self, require: bool) -> &mut Self {
317        self.require = require;
318        self
319    }
320    fn sql(&mut self, model: &str) -> String {
321        let not_null = if self.require { " not null" } else { "" };
322        match model {
323            "sqlite" => match self.auto {
324                true => {
325                    format!("`{}` INTEGER PRIMARY KEY AUTOINCREMENT", self.field)
326                }
327                false => {
328                    format!(
329                        "`{}` varchar({}){} default ''",
330                        self.field, self.length, not_null
331                    )
332                }
333            },
334            "pgsql" => match self.auto {
335                true => {
336                    format!(
337                        r#""{}" SERIAL PRIMARY KEY --{}|{}|{}"#,
338                        self.field, self.mode, self.title, self.length
339                    )
340                }
341                false => {
342                    format!(
343                        r#""{}" varchar({}) default '' --{}|{}|{}"#,
344                        self.field, self.length, self.mode, self.title, self.length
345                    )
346                }
347            },
348            _ => match self.auto {
349                true => {
350                    let sql = format!("`{}` int{} AUTO_INCREMENT", self.field, not_null);
351                    format!(
352                        "{} comment '{}|{}|{}'",
353                        sql, self.mode, self.title, self.length
354                    )
355                }
356                false => {
357                    let sql = format!(
358                        "`{}` varchar({}){} default ''",
359                        self.field, self.length, not_null
360                    );
361                    format!(
362                        "{} comment '{}|{}|{}'",
363                        sql, self.mode, self.title, self.length
364                    )
365                }
366            },
367        }
368    }
369    fn hide(&mut self) -> &mut Self {
370        self.show = false;
371        self
372    }
373
374    fn describe(&mut self, text: &str) -> &mut Self {
375        self.describe = text.to_string();
376        self
377    }
378    fn field(&mut self) -> JsonValue {
379        let mut field = object! {};
380        field
381            .insert("require", JsonValue::from(self.require))
382            .unwrap();
383        field
384            .insert("field", JsonValue::from(self.field.clone()))
385            .unwrap();
386        field
387            .insert("mode", JsonValue::from(self.mode.clone()))
388            .unwrap();
389        field
390            .insert("title", JsonValue::from(self.title.clone()))
391            .unwrap();
392        field
393            .insert("length", JsonValue::from(self.length))
394            .unwrap();
395        field
396            .insert("def", JsonValue::from(self.def.clone()))
397            .unwrap();
398        field.insert("auto", JsonValue::from(self.auto)).unwrap();
399
400        field.insert("show", JsonValue::from(self.show)).unwrap();
401        field
402            .insert("describe", JsonValue::from(self.describe.clone()))
403            .unwrap();
404        field.insert("example", self.example.clone()).unwrap();
405
406        field
407    }
408    fn swagger(&mut self) -> JsonValue {
409        object! {
410            "type": self.mode.clone(),
411            "example": self.example.clone(),
412        }
413    }
414
415    fn example(&mut self, data: JsonValue) -> &mut Self {
416        self.example = data;
417        self
418    }
419}
420
421/// 电话
422///
423/// * field 字段名
424/// * mode 模式 pass
425/// * title 字段描述
426/// * length 字段总长度(含小数位)
427/// * default 默认值
428/// * empty 是否可空
429pub struct Tel {
430    pub require: bool,
431    pub field: String,
432    pub mode: String,
433    pub title: String,
434    pub def: String,
435    pub length: i32,
436
437    pub show: bool,
438    pub describe: String,
439    pub example: JsonValue,
440}
441
442impl Tel {
443    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
444        Self {
445            require,
446            field: field.to_string(),
447            mode: "tel".to_string(),
448            title: title.to_string(),
449            def: default.to_string(),
450            length: 15,
451
452            show: true,
453            describe: "".to_string(),
454            example: JsonValue::Null,
455        }
456    }
457    pub fn is_phone(input: &str) -> bool {
458        // 统一手机号校验规则,并使用 lazy_static 避免每次调用都重新编译正则
459        lazy_static! {
460            // 中国大陆手机号
461            static ref CN_RE: Regex = Regex::new(r"^1[3-9]\d{9}$").unwrap();
462            // E.164 国际手机号(+开头可选)
463            static ref INTL_RE: Regex = Regex::new(r"^\+?[1-9]\d{1,14}$").unwrap();
464            // 国际手机号的 00 前缀写法
465            static ref INTL_00_RE: Regex = Regex::new(r"^00[1-9]\d{1,14}$").unwrap();
466        }
467        CN_RE.is_match(input) || INTL_RE.is_match(input) || INTL_00_RE.is_match(input)
468    }
469}
470
471impl Field for Tel {
472    fn require(&mut self, require: bool) -> &mut Self {
473        self.require = require;
474        self
475    }
476    fn sql(&mut self, model: &str) -> String {
477        let not_null = if self.require { " not null" } else { "" };
478        match model {
479            "sqlite" => format!(
480                "`{}` varchar({}){} default '{}'",
481                self.field, self.length, not_null, self.def
482            ),
483            "pgsql" => {
484                let sql = format!(
485                    r#""{}" varchar({}) default '{}'"#,
486                    self.field, self.length, self.def
487                );
488                format!(
489                    "{} --{}|{}|{}|{}|{}",
490                    sql, self.mode, self.require, self.title, self.length, self.def
491                )
492            }
493            _ => {
494                let sql = format!(
495                    "`{}` varchar({}){} default '{}'",
496                    self.field, self.length, not_null, self.def
497                );
498                format!(
499                    "{} comment '{}|{}|{}|{}|{}'",
500                    sql, self.mode, self.require, self.title, self.length, self.def
501                )
502            }
503        }
504    }
505    fn hide(&mut self) -> &mut Self {
506        self.show = false;
507        self
508    }
509    fn describe(&mut self, text: &str) -> &mut Self {
510        self.describe = text.to_string();
511        self
512    }
513
514    fn field(&mut self) -> JsonValue {
515        let mut field = object! {};
516        field
517            .insert("require", JsonValue::from(self.require))
518            .unwrap();
519        field
520            .insert("field", JsonValue::from(self.field.clone()))
521            .unwrap();
522        field
523            .insert("mode", JsonValue::from(self.mode.clone()))
524            .unwrap();
525        field
526            .insert("title", JsonValue::from(self.title.clone()))
527            .unwrap();
528        field
529            .insert("length", JsonValue::from(self.length))
530            .unwrap();
531        field
532            .insert("def", JsonValue::from(self.def.clone()))
533            .unwrap();
534
535        field.insert("show", JsonValue::from(self.show)).unwrap();
536        field
537            .insert("describe", JsonValue::from(self.describe.clone()))
538            .unwrap();
539        field.insert("example", self.example.clone()).unwrap();
540
541        field
542    }
543
544    fn swagger(&mut self) -> JsonValue {
545        object! {
546            "type": self.mode.clone(),
547            "example": self.example.clone(),
548        }
549    }
550    fn example(&mut self, data: JsonValue) -> &mut Self {
551        self.example = data;
552        self
553    }
554}
555
556/// 身份证
557///
558/// * field 字段名
559/// * mode 模式 ident
560/// * title 字段描述
561/// * length 字段总长度(含小数位)
562/// * default 默认值
563/// * empty 是否可空
564pub struct Ident {
565    pub require: bool,
566    pub field: String,
567    pub mode: String,
568    pub title: String,
569    pub def: String,
570    pub length: i32,
571
572    pub show: bool,
573    pub describe: String,
574    pub example: JsonValue,
575}
576
577impl Ident {
578    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
579        Self {
580            require,
581            field: field.to_string(),
582            mode: "ident".to_string(),
583            title: title.to_string(),
584            def: default.to_string(),
585            length: 18,
586
587            show: true,
588            describe: "".to_string(),
589            example: JsonValue::Null,
590        }
591    }
592}
593
594impl Field for Ident {
595    fn require(&mut self, require: bool) -> &mut Self {
596        self.require = require;
597        self
598    }
599    fn sql(&mut self, model: &str) -> String {
600        let not_null = if self.require { " not null" } else { "" };
601        match model {
602            "sqlite" => format!(
603                "`{}` varchar({}){} default '{}'",
604                self.field, self.length, not_null, self.def
605            ),
606            "pgsql" => {
607                let sql = format!(
608                    r#""{}" varchar({}) default '{}'"#,
609                    self.field, self.length, self.def
610                );
611                format!(
612                    "{} --{}|{}|{}|{}|{}",
613                    sql, self.mode, self.require, self.title, self.length, self.def
614                )
615            }
616            _ => {
617                let sql = format!(
618                    "`{}` varchar({}){} default '{}'",
619                    self.field, self.length, not_null, self.def
620                );
621                format!(
622                    "{} comment '{}|{}|{}|{}|{}'",
623                    sql, self.mode, self.require, self.title, self.length, self.def
624                )
625            }
626        }
627    }
628    fn hide(&mut self) -> &mut Self {
629        self.show = false;
630        self
631    }
632    fn describe(&mut self, text: &str) -> &mut Self {
633        self.describe = text.to_string();
634        self
635    }
636
637    fn field(&mut self) -> JsonValue {
638        let mut field = object! {};
639        field
640            .insert("require", JsonValue::from(self.require))
641            .unwrap();
642        field
643            .insert("field", JsonValue::from(self.field.clone()))
644            .unwrap();
645        field
646            .insert("mode", JsonValue::from(self.mode.clone()))
647            .unwrap();
648        field
649            .insert("title", JsonValue::from(self.title.clone()))
650            .unwrap();
651        field
652            .insert("length", JsonValue::from(self.length))
653            .unwrap();
654        field
655            .insert("def", JsonValue::from(self.def.clone()))
656            .unwrap();
657
658        field.insert("show", JsonValue::from(self.show)).unwrap();
659        field
660            .insert("describe", JsonValue::from(self.describe.clone()))
661            .unwrap();
662        field.insert("example", self.example.clone()).unwrap();
663
664        field
665    }
666
667    fn swagger(&mut self) -> JsonValue {
668        object! {
669            "type": self.mode.clone(),
670            "example": self.example.clone(),
671        }
672    }
673    fn example(&mut self, data: JsonValue) -> &mut Self {
674        self.example = data;
675        self
676    }
677}
678/// 电子邮件
679///
680/// * field 字段名
681/// * mode 模式 pass
682/// * title 字段描述
683/// * length 字段总长度(含小数位)
684/// * default 默认值
685/// * empty 是否可空
686pub struct Email {
687    pub require: bool,
688    pub field: String,
689    pub mode: String,
690    pub title: String,
691    pub def: String,
692    pub length: i32,
693
694    pub show: bool,
695    pub describe: String,
696    pub example: JsonValue,
697}
698
699impl Email {
700    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
701        Self {
702            require,
703            field: field.to_string(),
704            mode: "email".to_string(),
705            title: title.to_string(),
706            def: default.to_string(),
707            length: 100,
708
709            show: true,
710            describe: "".to_string(),
711            example: JsonValue::Null,
712        }
713    }
714    pub fn is_email(email: &str) -> bool {
715        // 统一邮箱校验规则,并使用 lazy_static 避免每次调用都重新编译正则
716        lazy_static! {
717            static ref EMAIL_RE: Regex =
718                Regex::new(r"(?i)^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$").unwrap();
719        }
720        EMAIL_RE.is_match(email)
721    }
722}
723
724impl Field for Email {
725    fn require(&mut self, require: bool) -> &mut Self {
726        self.require = require;
727        self
728    }
729    fn sql(&mut self, model: &str) -> String {
730        let not_null = if self.require { " not null" } else { "" };
731        match model {
732            "sqlite" => format!(
733                "`{}` varchar({}){} default '{}'",
734                self.field, self.length, not_null, self.def
735            ),
736            "pgsql" => {
737                let sql = format!(
738                    r#""{}" varchar({}) default '{}'"#,
739                    self.field, self.length, self.def
740                );
741                format!(
742                    "{} --{}|{}|{}|{}|{}",
743                    sql, self.mode, self.require, self.title, self.length, self.def
744                )
745            }
746            _ => {
747                let sql = format!(
748                    "`{}` varchar({}){} default '{}'",
749                    self.field, self.length, not_null, self.def
750                );
751                format!(
752                    "{} comment '{}|{}|{}|{}|{}'",
753                    sql, self.mode, self.require, self.title, self.length, self.def
754                )
755            }
756        }
757    }
758    fn hide(&mut self) -> &mut Self {
759        self.show = false;
760        self
761    }
762    fn describe(&mut self, text: &str) -> &mut Self {
763        self.describe = text.to_string();
764        self
765    }
766    fn field(&mut self) -> JsonValue {
767        let mut field = object! {};
768        field
769            .insert("require", JsonValue::from(self.require))
770            .unwrap();
771        field
772            .insert("field", JsonValue::from(self.field.clone()))
773            .unwrap();
774        field
775            .insert("mode", JsonValue::from(self.mode.clone()))
776            .unwrap();
777        field
778            .insert("title", JsonValue::from(self.title.clone()))
779            .unwrap();
780        field
781            .insert("length", JsonValue::from(self.length))
782            .unwrap();
783        field
784            .insert("def", JsonValue::from(self.def.clone()))
785            .unwrap();
786
787        field.insert("show", JsonValue::from(self.show)).unwrap();
788        field
789            .insert("describe", JsonValue::from(self.describe.clone()))
790            .unwrap();
791        field.insert("example", self.example.clone()).unwrap();
792        field
793    }
794
795    fn verify(&mut self, data: JsonValue) -> JsonValue {
796        data
797    }
798
799    fn swagger(&mut self) -> JsonValue {
800        object! {
801            "type": self.mode.clone(),
802            "example": self.example.clone(),
803        }
804    }
805    fn example(&mut self, data: JsonValue) -> &mut Self {
806        self.example = data.clone();
807        self
808    }
809}
810
811/// 颜色
812///
813/// * field 字段名
814/// * mode 模式 pass
815/// * title 字段描述
816/// * length 字段总长度(含小数位)
817pub struct Color {
818    pub require: bool,
819    pub field: String,
820    pub mode: String,
821    pub title: String,
822    pub def: String,
823    pub length: i32,
824
825    pub show: bool,
826    pub describe: String,
827    pub example: JsonValue,
828}
829
830impl Color {
831    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
832        Self {
833            require,
834            field: field.to_string(),
835            mode: "color".to_string(),
836            title: title.to_string(),
837            def: default.to_string(),
838            length: 9,
839
840            show: true,
841            describe: "".to_string(),
842            example: JsonValue::Null,
843        }
844    }
845}
846
847impl Field for Color {
848    fn require(&mut self, require: bool) -> &mut Self {
849        self.require = require;
850        self
851    }
852    fn sql(&mut self, model: &str) -> String {
853        let not_null = if self.require { " not null" } else { "" };
854        match model {
855            "sqlite" => format!(
856                "`{}` varchar({}){} default '{}'",
857                self.field, self.length, not_null, self.def
858            ),
859            "pgsql" => {
860                let sql = format!(
861                    r#""{}" varchar({}) default '{}'"#,
862                    self.field, self.length, self.def
863                );
864                format!(
865                    "{} --{}|{}|{}|{}|{}",
866                    sql, self.mode, self.require, self.title, self.length, self.def
867                )
868            }
869            _ => {
870                let sql = format!(
871                    "`{}` varchar({}){} default '{}'",
872                    self.field, self.length, not_null, self.def
873                );
874                format!(
875                    "{} comment '{}|{}|{}|{}|{}'",
876                    sql, self.mode, self.require, self.title, self.length, self.def
877                )
878            }
879        }
880    }
881    fn hide(&mut self) -> &mut Self {
882        self.show = false;
883        self
884    }
885    fn describe(&mut self, text: &str) -> &mut Self {
886        self.describe = text.to_string();
887        self
888    }
889    fn field(&mut self) -> JsonValue {
890        let mut field = object! {};
891        field
892            .insert("require", JsonValue::from(self.require))
893            .unwrap();
894        field
895            .insert("field", JsonValue::from(self.field.clone()))
896            .unwrap();
897        field
898            .insert("mode", JsonValue::from(self.mode.clone()))
899            .unwrap();
900        field
901            .insert("title", JsonValue::from(self.title.clone()))
902            .unwrap();
903        field
904            .insert("length", JsonValue::from(self.length))
905            .unwrap();
906        field
907            .insert("def", JsonValue::from(self.def.clone()))
908            .unwrap();
909
910        field.insert("show", JsonValue::from(self.show)).unwrap();
911        field
912            .insert("describe", JsonValue::from(self.describe.clone()))
913            .unwrap();
914        field.insert("example", self.example.clone()).unwrap();
915
916        field
917    }
918
919    fn verify(&mut self, data: JsonValue) -> JsonValue {
920        data
921    }
922
923    fn swagger(&mut self) -> JsonValue {
924        object! {
925            "type": self.mode.clone(),
926            "example": self.example.clone(),
927        }
928    }
929    fn example(&mut self, data: JsonValue) -> &mut Self {
930        self.example = data.clone();
931        self
932    }
933}
934
935/// 编号
936///
937/// * field 字段名
938/// * mode 模式 pass
939/// * title 字段描述
940/// * length 字段总长度(含小数位)
941/// * default 默认值
942/// * empty 是否可空
943/// * dec 编号前缀
944pub struct Code {
945    pub require: bool,
946    pub field: String,
947    pub mode: String,
948    pub title: String,
949    pub def: String,
950    pub length: usize,
951
952    pub show: bool,
953    pub describe: String,
954
955    /// 编号前缀
956    pub dec: String,
957    pub example: JsonValue,
958}
959
960impl Code {
961    pub fn new(
962        require: bool,
963        field: &str,
964        title: &str,
965        length: usize,
966        dec: &str,
967        default: &str,
968    ) -> Self {
969        Self {
970            require,
971            field: field.to_string(),
972            mode: "code".to_string(),
973            title: title.to_string(),
974            def: default.to_string(),
975            length: length + dec.len(),
976            show: true,
977            describe: "".to_string(),
978            dec: dec.to_string(),
979            example: JsonValue::Null,
980        }
981    }
982
983    /// 生成全球唯一的X+20位订单号
984    pub fn order_code(prefix: &str, machine_id: u16) -> String {
985        let now = Local::now();
986        let time_str = now.format("%Y%m%d%H%M%S");
987        let millis = now.timestamp_subsec_millis();
988        // 每毫秒内自增
989        let seq = SEQ.fetch_add(1, Ordering::SeqCst) % 1000;
990        // 三位随机数
991        let rand_part: u16 = rand::rng().random_range(0..1000);
992        format!(
993            "{}{}{:02}{:03}{:03}{:03}",
994            prefix,
995            time_str,
996            machine_id % 100,
997            millis,
998            rand_part,
999            seq
1000        )
1001    }
1002    /// 生成X+13位编号
1003    pub fn code_no_13(prefix: &str) -> String {
1004        let data = Datetime::datetime_format("%Y%m%d%H%f");
1005        let data = data.trim_end_matches("00");
1006        format!("{prefix}{data}")
1007    }
1008    /// 生成批次号X+10位编号
1009    pub fn batch_no(prefix: &str) -> String {
1010        let data = Datetime::datetime_format("%Y%m%d%H");
1011        format!("{prefix}{data}")
1012    }
1013    /// 随机生成数字
1014    pub fn random_number_f64(begin: f64, finish: f64) -> f64 {
1015        rand::rng().random_range(begin..=finish)
1016    }
1017    /// 生成验证码
1018    pub fn verification_code(len: usize) -> String {
1019        let text = "0123456789";
1020        let mut code = "".to_string();
1021        for _ in 0..len {
1022            let index = rand::rng().random_range(0..=text.len() - 1);
1023            let t = &text[index..=index];
1024            code = format!("{}{}", code, t);
1025        }
1026        code
1027    }
1028}
1029
1030impl Field for Code {
1031    fn require(&mut self, require: bool) -> &mut Self {
1032        self.require = require;
1033        self
1034    }
1035    fn sql(&mut self, model: &str) -> String {
1036        let not_null = if self.require { " not null" } else { "" };
1037        match model {
1038            "sqlite" => format!(
1039                "`{}` varchar({}){} default '{}'",
1040                self.field, self.length, not_null, self.def
1041            ),
1042            "pgsql" => {
1043                let sql = format!(
1044                    r#""{}" varchar({}) default '{}'"#,
1045                    self.field, self.length, self.def
1046                );
1047                format!(
1048                    "{} --{}|{}|{}|{}|{}",
1049                    sql, self.mode, self.require, self.title, self.length, self.def
1050                )
1051            }
1052            _ => {
1053                let sql = format!(
1054                    "`{}` varchar({}){} default '{}'",
1055                    self.field, self.length, not_null, self.def
1056                );
1057                format!(
1058                    "{} comment '{}|{}|{}|{}|{}|{}'",
1059                    sql, self.mode, self.require, self.title, self.length, self.dec, self.def
1060                )
1061            }
1062        }
1063    }
1064    fn hide(&mut self) -> &mut Self {
1065        self.show = false;
1066        self
1067    }
1068    fn describe(&mut self, text: &str) -> &mut Self {
1069        self.describe = text.to_string();
1070        self
1071    }
1072
1073    fn field(&mut self) -> JsonValue {
1074        let mut field = object! {};
1075        field
1076            .insert("require", JsonValue::from(self.require))
1077            .unwrap();
1078        field
1079            .insert("field", JsonValue::from(self.field.clone()))
1080            .unwrap();
1081        field
1082            .insert("mode", JsonValue::from(self.mode.clone()))
1083            .unwrap();
1084        field
1085            .insert("title", JsonValue::from(self.title.clone()))
1086            .unwrap();
1087        field
1088            .insert("length", JsonValue::from(self.length))
1089            .unwrap();
1090        field
1091            .insert("def", JsonValue::from(self.def.clone()))
1092            .unwrap();
1093
1094        field.insert("show", JsonValue::from(self.show)).unwrap();
1095        field
1096            .insert("describe", JsonValue::from(self.describe.clone()))
1097            .unwrap();
1098        field
1099            .insert("dec", JsonValue::from(self.dec.clone()))
1100            .unwrap();
1101        field.insert("example", self.example.clone()).unwrap();
1102
1103        field
1104    }
1105
1106    fn swagger(&mut self) -> JsonValue {
1107        object! {
1108            "type": self.mode.clone(),
1109            "example": self.example.clone(),
1110        }
1111    }
1112    fn example(&mut self, data: JsonValue) -> &mut Self {
1113        self.example = data.clone();
1114        self
1115    }
1116}
1117
1118/// 条码
1119pub struct BarCode {
1120    /// 必填
1121    pub require: bool,
1122    /// 字段名
1123    pub field: String,
1124    /// 模式
1125    pub mode: String,
1126    /// 字段描述
1127    pub title: String,
1128    /// 默认值
1129    pub def: String,
1130    /// 字段总长度
1131    pub length: usize,
1132    /// 是否显示
1133    pub show: bool,
1134    /// 功能描述
1135    pub describe: String,
1136    pub example: JsonValue,
1137}
1138
1139impl BarCode {
1140    pub fn new(require: bool, field: &str, title: &str, default: &str) -> Self {
1141        Self {
1142            require,
1143            field: field.to_string(),
1144            mode: "barcode".to_string(),
1145            title: title.to_string(),
1146            def: default.to_string(),
1147            length: 20,
1148            show: true,
1149            describe: "".to_string(),
1150            example: JsonValue::Null,
1151        }
1152    }
1153    /// 生成条码
1154    pub fn create_barcode(prefix: &str) -> String {
1155        let data = Datetime::datetime_format("%Y%m%d%H");
1156        format!("{prefix}{data}")
1157    }
1158}
1159
1160impl Field for BarCode {
1161    fn require(&mut self, require: bool) -> &mut Self {
1162        self.require = require;
1163        self
1164    }
1165    fn sql(&mut self, model: &str) -> String {
1166        let not_null = if self.require { " not null" } else { "" };
1167        match model {
1168            "sqlite" => format!(
1169                "`{}` varchar({}){} default '{}'",
1170                self.field, self.length, not_null, self.def
1171            ),
1172            "pgsql" => {
1173                let sql = format!(
1174                    r#""{}" varchar({}) default '{}'"#,
1175                    self.field, self.length, self.def
1176                );
1177                format!(
1178                    "{} --{}|{}|{}|{}|{}",
1179                    sql, self.mode, self.require, self.title, self.length, self.def
1180                )
1181            }
1182            _ => {
1183                let sql = format!(
1184                    "`{}` varchar({}){} default '{}'",
1185                    self.field, self.length, not_null, self.def
1186                );
1187                format!(
1188                    "{} comment '{}|{}|{}|{}|{}'",
1189                    sql, self.mode, self.require, self.title, self.length, self.def
1190                )
1191            }
1192        }
1193    }
1194    fn hide(&mut self) -> &mut Self {
1195        self.show = false;
1196        self
1197    }
1198    fn describe(&mut self, text: &str) -> &mut Self {
1199        self.describe = text.to_string();
1200        self
1201    }
1202
1203    fn field(&mut self) -> JsonValue {
1204        let mut field = object! {};
1205        field
1206            .insert("require", JsonValue::from(self.require))
1207            .unwrap();
1208        field
1209            .insert("field", JsonValue::from(self.field.clone()))
1210            .unwrap();
1211        field
1212            .insert("mode", JsonValue::from(self.mode.clone()))
1213            .unwrap();
1214        field
1215            .insert("title", JsonValue::from(self.title.clone()))
1216            .unwrap();
1217        field
1218            .insert("length", JsonValue::from(self.length))
1219            .unwrap();
1220        field
1221            .insert("def", JsonValue::from(self.def.clone()))
1222            .unwrap();
1223
1224        field.insert("show", JsonValue::from(self.show)).unwrap();
1225        field
1226            .insert("describe", JsonValue::from(self.describe.clone()))
1227            .unwrap();
1228        field.insert("example", self.example.clone()).unwrap();
1229        field
1230    }
1231
1232    fn swagger(&mut self) -> JsonValue {
1233        object! {
1234            "type": self.mode.clone(),
1235            "example": self.example.clone(),
1236        }
1237    }
1238
1239    fn example(&mut self, data: JsonValue) -> &mut Self {
1240        self.example = data.clone();
1241        self
1242    }
1243}
1244
1245/// QrCode 二维码
1246pub struct QrCode {
1247    /// 必填
1248    pub require: bool,
1249    /// 字段名
1250    pub field: String,
1251    /// 模式
1252    pub mode: String,
1253    /// 字段描述
1254    pub title: String,
1255    /// 默认值
1256    pub def: String,
1257    /// 字段总长度
1258    pub length: usize,
1259    /// 是否显示
1260    pub show: bool,
1261    /// 功能描述
1262    pub describe: String,
1263    pub example: JsonValue,
1264}
1265
1266impl QrCode {
1267    pub fn new(require: bool, field: &str, title: &str, length: usize, default: &str) -> Self {
1268        Self {
1269            require,
1270            field: field.to_string(),
1271            mode: "qrcode".to_string(),
1272            title: title.to_string(),
1273            def: default.to_string(),
1274            length,
1275            show: true,
1276            describe: "".to_string(),
1277            example: JsonValue::Null,
1278        }
1279    }
1280}
1281
1282impl Field for QrCode {
1283    fn require(&mut self, require: bool) -> &mut Self {
1284        self.require = require;
1285        self
1286    }
1287    fn sql(&mut self, model: &str) -> String {
1288        let not_null = if self.require { " not null" } else { "" };
1289        match model {
1290            "sqlite" => format!(
1291                "`{}` varchar({}){} default '{}'",
1292                self.field, self.length, not_null, self.def
1293            ),
1294            "pgsql" => {
1295                let sql = format!(
1296                    r#""{}" varchar({}) default '{}'"#,
1297                    self.field, self.length, self.def
1298                );
1299                format!(
1300                    "{} --{}|{}|{}|{}|{}",
1301                    sql, self.mode, self.require, self.title, self.length, self.def
1302                )
1303            }
1304            _ => {
1305                let sql = format!(
1306                    "`{}` varchar({}){} default '{}'",
1307                    self.field, self.length, not_null, self.def
1308                );
1309                format!(
1310                    "{} comment '{}|{}|{}|{}|{}'",
1311                    sql, self.mode, self.require, self.title, self.length, self.def
1312                )
1313            }
1314        }
1315    }
1316    fn hide(&mut self) -> &mut Self {
1317        self.show = false;
1318        self
1319    }
1320    fn describe(&mut self, text: &str) -> &mut Self {
1321        self.describe = text.to_string();
1322        self
1323    }
1324
1325    fn field(&mut self) -> JsonValue {
1326        let mut field = object! {};
1327        field
1328            .insert("require", JsonValue::from(self.require))
1329            .unwrap();
1330        field
1331            .insert("field", JsonValue::from(self.field.clone()))
1332            .unwrap();
1333        field
1334            .insert("mode", JsonValue::from(self.mode.clone()))
1335            .unwrap();
1336        field
1337            .insert("title", JsonValue::from(self.title.clone()))
1338            .unwrap();
1339        field
1340            .insert("length", JsonValue::from(self.length))
1341            .unwrap();
1342        field
1343            .insert("def", JsonValue::from(self.def.clone()))
1344            .unwrap();
1345
1346        field.insert("show", JsonValue::from(self.show)).unwrap();
1347        field
1348            .insert("describe", JsonValue::from(self.describe.clone()))
1349            .unwrap();
1350        field.insert("example", self.example.clone()).unwrap();
1351
1352        field
1353    }
1354
1355    fn swagger(&mut self) -> JsonValue {
1356        object! {
1357            "type": self.mode.clone(),
1358            "example": self.example.clone(),
1359        }
1360    }
1361
1362    fn example(&mut self, data: JsonValue) -> &mut Self {
1363        self.example = data.clone();
1364        self
1365    }
1366}
1367#[cfg(test)]
1368mod tests {
1369    #[test]
1370    fn code() {
1371        let data = crate::str::Code::order_code("Y", 1);
1372        println!("code: {} {}", data, data.len());
1373        let data = crate::str::Code::order_code("Y", 1);
1374        println!("code: {} {}", data, data.len());
1375        let data = crate::str::Code::order_code("Y", 2);
1376        println!("code: {} {}", data, data.len());
1377        let data = crate::str::Code::order_code("Y", 2);
1378        println!("code: {} {}", data, data.len());
1379        let data = crate::str::Code::order_code("Y", 3);
1380        println!("code: {} {}", data, data.len());
1381        let data = crate::str::Code::order_code("Y", 3);
1382        println!("code: {} {}", data, data.len());
1383    }
1384}