Skip to main content

br_fields/
str.rs

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