Fields.php
18.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
<?php
namespace app\admin\model\facrm;
use addons\facrm\library\Alter;
use app\common\model\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Model;
class Fields extends Model
{
// 表名
protected $name = 'facrm_fields';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
'status_text',
'content_list',
];
protected $type = [
'setting' => 'json',
];
protected static $listField = ['select', 'selects', 'checkbox', 'radio', 'array'];
public function setError($error)
{
$this->error = $error;
}
protected static function init()
{
$beforeUpdateCallback = function ($row) {
if (!preg_match("/^([a-zA-Z0-9_]+)$/i", $row['name'])) {
throw new Exception("字段只支持字母数字下划线");
}
if (is_numeric(substr($row['name'], 0, 1))) {
throw new Exception("字段不能以数字开始");
}
if (isset($row['oldname']) && $row['oldname'] != $row['name']) {
$table = "facrm_" . $row['source'];
$tableFields = \think\Db::name($table)->getTableFields();
if (in_array(strtolower($row['name']), $tableFields)) {
throw new Exception("字段已经存在了");
}
}
};
$beforeInsertCallback = function ($row) {
if (!preg_match("/^([a-zA-Z0-9_]+)$/i", $row['name'])) {
throw new Exception("字段只支持字母数字下划线");
}
if (is_numeric(substr($row['name'], 0, 1))) {
throw new Exception("字段不能以数字开始");
}
$table = "facrm_" . $row['source'];
$tableFields = \think\Db::name($table)->getTableFields();
if (in_array(strtolower($row['name']), $tableFields)) {
throw new Exception("字段已经存在了");
}
};
$afterInsertCallback = function ($row) {
//为了避免引起更新的事件回调,这里采用直接执行SQL的写法
Db::name('facrm_fields')->update(['id' => $row['id'], 'weigh' => $row['id']]);
Fields::refreshTable($row, 'insert');
};
$afterUpdateCallback = function ($row) {
Fields::refreshTable($row, 'update');
};
self::beforeInsert($beforeInsertCallback);
self::beforeUpdate($beforeUpdateCallback);
self::afterInsert($afterInsertCallback);
self::afterUpdate($afterUpdateCallback);
self::afterDelete(function ($row) {
Fields::refreshTable($row, 'delete');
});
}
public function getContentListAttr($value, $data)
{
return in_array($data['type'], self::$listField) ? Config::decode($data['content']) : $data['content'];
}
public static function refreshTable($row, $action = 'insert')
{
$model = null;
$table = "facrm_" . $row['source'];
$alter = Alter::instance();
if (isset($row['oldname']) && $row['oldname'] != $row['name']) {
$alter->setOldname($row['oldname']);
}
$alter
->setTable($table)
->setName($row['name'])
->setLength($row['length'])
->setContent($row['content'])
->setDecimals($row['decimals'])
->setDefaultvalue($row['defaultvalue'])
->setComment($row['title'])
->setType($row['type']);
if ($action == 'insert') {
$sql = $alter->getAddSql();
} elseif ($action == 'update') {
$sql = $alter->getModifySql();
} elseif ($action == 'delete') {
$sql = $alter->getDropSql();
} else {
throw new Exception("操作类型错误");
}
try {
db()->execute($sql);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
public function getStatusList()
{
return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
}
public function getStatusTextAttr($value, $data)
{
$value = $value ? $value : $data['status'];
$list = $this->getStatusList();
return isset($list[$value]) ? $list[$value] : '';
}
/**
* 获取指定类型的自定义字段列表
*/
public static function getCustomFields($source, $values = [], $conditions = [])
{
$fields = Fields::where('source', $source)
->where($conditions)
->where('status', 'normal')
->order('weigh desc,id desc')
->select();
foreach ($fields as $k => $v) {
//优先取编辑的值,再次取默认值
$v->value = isset($values[$v['name']]) ? $values[$v['name']] : (is_null($v['defaultvalue']) ? '' : $v['defaultvalue']);
$v->rule = str_replace(',', '; ', $v->rule);
if (in_array($v['type'], ['checkbox', 'lists', 'images'])) {
$checked = '';
if ($v['minimum'] && $v['maximum']) {
$checked = "{$v['minimum']}~{$v['maximum']}";
} elseif ($v['minimum']) {
$checked = "{$v['minimum']}~";
} elseif ($v['maximum']) {
$checked = "~{$v['maximum']}";
}
if ($checked) {
$v->rule .= (';checked(' . $checked . ')');
}
}
if (in_array($v['type'], ['checkbox', 'radio']) && stripos($v->rule, 'required') !== false) {
$v->rule = str_replace('required', 'checked', $v->rule);
}
if (in_array($v['type'], ['selects'])) {
$v->extend .= (' ' . 'data-max-options="' . $v['maximum'] . '"');
}
}
return $fields;
}
/**
* 获取自定义字段【在table上用的】
* @param $source
* @param array $values
* @param array $conditions
* @return array
*/
public static function getCustomFieldsTable($source, $values = [], $conditions = [])
{
$temp = array();
$fields = self::getCustomFields($source, $values, $conditions);
if ($fields) {
foreach ($fields as $key => $row) {
$temp[$key]['field'] = $row['name'];
$temp[$key]['title'] = $row['title'];
$temp[$key]['operate'] = $row['isfilter'] ? 'LIKE' : false;
$temp[$key]['search'] = $row['isfilter'] ? true : false;
$temp[$key]['visible'] = $row['islist'] ? true : false;
switch ($row['type']) {
case 'radio':
case 'select':
$temp[$key]['operate'] = $row['isfilter'] ? '=' : false;
$temp[$key]['searchList'] = $row['content_list'];
$temp[$key]["formatter"] = 'Table.api.formatter.status';
break;
case 'checkbox':
case 'selects':
$temp[$key]['searchList'] = $row['content_list'];
$temp[$key]["formatter"] = 'Table.api.formatter.flag';
$temp[$key]['operate'] = $row['isfilter'] ? 'find_in_set' : false;
break;
case 'datetime':
$temp[$key]["formatter"] = 'Table.api.formatter.datetime';
$temp[$key]['operate'] = $row['isfilter'] ? 'RANGE' : false;
$temp[$key]['addclass'] = 'datetimerange';
break;
case 'image':
case 'images':
$temp[$key]["formatter"] = 'Table.api.formatter.images';
$temp[$key]["events"] = 'Table.api.events.image';
break;
case 'file':
case 'files':
$temp[$key]["formatter"] = 'Controller.api.formatter.thumb';
break;
case 'switch':
$temp[$key]["formatter"] = 'Table.api.formatter.toggle';
break;
case 'selectpages':
case 'selectpage':
/**
* $js = <<<eof
* gree=function (value, row, index) {
* var that=$(this);
* $.ajax({
* type: "POST",
* url: "facrm/fields/selectpage?admin=1&id={$row->id}",
* data: {keyValue: value, 'searchKey': value},
* dataType: "json",
* success: function(data){
* console.log(index);
* table.bootstrapTable('updateRow', {
* index: index,
* row: {
* mobile: 1,
* }
* });
* }
* });
* }
* eof;**/
$temp[$key]["extend"] = "data-source='facrm/fields/selectpage?admin=1&id={$row->id}'
data-primary-key='{$row->setting['primarykey']}' data-field='{$row->setting['field']}' ";
$temp[$key]['addclass'] = 'selectpage';
$temp[$key]['operate'] = '=';
$temp[$key]['visible'] = false;//不让在列表显示,未解决性能问题
break;
default:
}
}
}
return $temp;
}
public function getExtendHtmlAttr($value, $data)
{
$result = preg_replace_callback("/\{([a-zA-Z]+)\}/", function ($matches) use ($data) {
if (isset($data[$matches[1]])) {
return $data[$matches[1]];
}
}, $data['extend']);
return $result;
}
/**
* 表单验证
* @param $source
* @param $param
* @param string $type 验证类型 system系统字段,其它自定义字段
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function validateByForm($source, &$param,$type='')
{
if ($type=='system'){
$values =(new \app\admin\model\facrm\Setting())->where('key', 'validate_tpl_'.$source)->value('values');
$fields=$values?json_decode($values,true):[];
}else{
$fields = self::where('source', $source)->where('status','normal')->order('weigh desc,id desc')->select();
}
$rules = [];
$msg = [];
foreach ($fields as $item) {
$rule = explode(',', $item['rule']);
foreach ($rule as $res) {
//处理null问题
if (isset($param[$item['name']])&&!is_array($param[$item['name']])&&trim($param[$item['name']])=='null'){
$param[$item['name']]=NULL;
}
if (isset($param[$item['name']])&&$param[$item['name']]==''&&isset($item['type'])&&in_array($item['type'],
['time','datetime','date'])){
$param[$item['name']]=NULL;
}
//解决时间日期、select为空报错问题
if (isset($param[$item['name']])&&$param[$item['name']]==''&&isset($item['type'])&&in_array($item['type'],
['select','selects','radio','radio']))
unset($param[$item['name']]);
switch ($res) {
case 'required':
$rules["{$item['name']}"][] = 'require';
$msg["{$item['name']}.require"] = $item['title'] . '不能为空!';
break;
case 'digits':
$rules["{$item['name']}"][] = 'number';
$msg["{$item['name']}.number"] = $item['title'] . '必须是数字!';
break;
case 'letters':
$rules["{$item['name']}"][] = 'alpha';
$msg["{$item['name']}.alpha"] = $item['title'] . '必须是字母!';
break;
case 'date':
$rules[$item['name']][] = 'date';
$msg["{$item['name']}.date"] = $item['title'] . '格式错误!';
break;
case 'time':
$rules["{$item['name']}"][] = 'regex:/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'email':
$rules[$item['name']][] = 'email';
$msg["{$item['name']}.email"] = $item['title'] . '格式错误!';
break;
case 'url':
$rules[$item['name']] = 'url';
$msg["{$item['name']}.url"] = $item['title'] . '格式错误!';
break;
case 'qq':
$rules["{$item['name']}"][] = 'regex:/^[1-9][0-9]{4,10}$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'IDcard':
$rules["{$item['name']}"][] = 'regex:/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'tel':
$rules["{$item['name']}"][] = 'regex:/^\d{3}-\d{8}$|^\d{4}-\d{7,8}$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'mobile':
$rules["{$item['name']}"][] = 'regex:/^1\d{10}$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'zipcode':
$rules["{$item['name']}"][] = 'regex:/^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\d{4}$/';
$msg["{$item['name']}"] = $item['title'] . '格式错误!';
break;
case 'chinese':
$rules[$item['name']][] = 'chs';
$msg["{$item['name']}.chs"] = $item['title'] . '只能填写中文!';
break;
case 'username':
$rules["{$item['name']}"][] = 'regex:/^[a-zA-Z0-9_]{3,12}$/';
$msg["{$item['name']}"] = $item['title'] . '请填写3-12位数字、字母、下划线!';
break;
case 'password':
$rules["{$item['name']}"][] = 'regex:/^[0-9a-zA-Z!@#$%^&*?]{6,16}$/';
$msg["{$item['name']}"] = $item['title'] . '请填写6-16位字符,不能包含空格!';
break;
}
}
}
$validate = new \think\Validate($rules, $msg);
$return['status'] = $validate->check($param);
$return['msg'] = $return['status'] ? '' : $validate->getError();
return $return;
}
/**
* 自定义排序
*/
public static function diyorder($admin_id, $type = "customer")
{
$cache_key=("diy".$type."_".$admin_id);
if (!extension_loaded('redis')) {
$order=\app\admin\model\facrm\Setting::where('key',$cache_key)->value("values");
$order=$order?json_decode($order):[];
} else {
$queue_config=\think\Config::get('queue');
$redis_cache = \think\Cache::connect([
'type' => 'redis',
'password'=>isset($queue_config['password'])?$queue_config['password']:'',
'host'=>isset($queue_config['host'])?$queue_config['host']:'127.0.0.1',
'port'=>isset($queue_config['port'])?$queue_config['port']:'6379'
]);
$order = $redis_cache->get($cache_key);
}
$fields = \app\admin\model\facrm\Fields::getCustomFieldsTable($type, [], 'isfilter=1 or islist=1');
$config_file = ADDON_PATH . "facrm" . DS . 'config' . DS . "{$type}field.php";
$default_fields = array();
if (is_file($config_file)) {
$default_fields = include $config_file;
}
$fields = array_merge($default_fields, $fields);
//自定义排序
if ($order) {
$order = array_merge($order, array_column($fields, 'field'));
usort($fields, function ($a, $b) use ($order) {
$pos_a = array_search($a['field'], $order);
$pos_b = array_search($b['field'], $order);
return $pos_a - $pos_b;
});
}
return $fields;
}
/**
* 缓存排序【要永久缓存】
* @param $admin_id
* @param $params
* @param string $type
* @return bool
*/
public static function saveDiyorder($admin_id, $params, $type = "customer")
{
$cache_key=("diy".$type."_".$admin_id);
if (!extension_loaded('redis')) {
$model=\app\admin\model\facrm\Setting::detail($cache_key)??new \app\admin\model\facrm\Setting();
return $model->save(['key'=>$cache_key,'describe'=>'自定义排序','values'=>$params]);
} else {
$queue_config=\think\Config::get('queue');
$redis_cache = \think\Cache::connect([
'type' => 'redis',
'password'=>isset($queue_config['password'])?$queue_config['password']:'',
'host'=>isset($queue_config['host'])?$queue_config['host']:'127.0.0.1',
'port'=>isset($queue_config['port'])?$queue_config['port']:'6379'
]);
return $redis_cache->tag('diyorder')->set($cache_key, $params);
}
}
}