| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572 |
- <?php
- namespace addons\SmartForm\common\models;
- use addons\SmartForm\common\enums\SmartFormEnum;
- use common\enums\StatusEnum;
- use common\models\mall\MallAddons;
- use common\models\user\User;
- use Yii;
- use common\components\export\CsvTool;
- use yii\db\Exception;
- use common\enums\DownloadEnum;
- use common\models\common\Download;
- use addons\SmartForm\common\models\AddonsSmartFormTemplateColumn; #模板字段
- use addons\SmartForm\common\models\AddonsSmartFormTemplate; #模板
- use addons\SmartForm\common\models\AddonsSmartFormTemplateUserFormInfo; # 用户明细字段
- use common\helpers\ArrayHelper;
- use common\models\common\Region;
- use yii\helpers\Json;
- /**
- * This is the model class for table "{{%addons_smart_form_template_user_form}}".
- *
- * @property int $id
- * @property int $mall_id 商城ID
- * @property int|null $status 状态[-1:删除;0:禁用;1启用]
- * @property int $created_at 创建时间
- * @property int $updated_at 修改时间
- * @property int $is_ignore 修改时间
- */
- class AddonsSmartFormTemplateUserForm extends \common\models\base\BaseActiveRecord
- {
- const ADDONS_NAME = 'SmartForm';
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_smart_form_template_user_form}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['smart_form_template_id','user_id','mall_id','source'], 'required'],
- [['smart_form_template_id','user_id','mall_id','source','updated_at','created_at','status','diy_page_id', 'is_ignore'], 'integer'],
- [['col_value','smart_form_template_column_id'], 'string'],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => '主键' ,
- 'mall_id' => '商城id',
- 'smart_form_template_id' => '智能装修表单管理id',
- 'user_id' => '用户id',
- 'diy_page_id' => '使用页面id',
- 'smart_form_template_column_id' => '使用字段',
- 'col_value' => '字段值',
- 'source' => '来源[0:小程序]',
- 'status' => '状态[-1:删除;0:禁用;1:启用,2:已过期]',
- 'created_at' => '创建时间',
- 'updated_at' => '修改时间',
- ];
- }
-
- public function getUser()
- {
- return $this->hasOne(User::class, ['id' => 'user_id'])->select('id,mobile,nickname,avatar_url,parent_id,username');
- }
- public function getFormInfo(){
- return $this->hasMany(AddonsSmartFormTemplateUserFormInfo::class, ['smart_form_template_user_form_id' => 'id']);
- }
- public function getForm()
- {
- return $this->hasOne(AddonsSmartFormTemplate::class, ['id' => 'smart_form_template_id']);
- }
- /**
- * @method saveUserForm
- * 保存用户表单
- * @author zqh
- * @datetime 2022-05-07T10:33:40+0800
- * @param [type] $params [description]
- * @return [type] [description]
- */
- public static function saveUserForm($params)
- {
- # 模板参数
- $form = $params['form'];
- if(!isset($form['id']) || !$form['id']){
- self::$static_error = "模板不存在";
- return false;
- }
- # 获取模板信息
- $info = AddonsSmartFormTemplate::getOne([['id' => $form['id']]], true, [
- 'columnsInfo'=> function ($query) {
- }
- ]);
- if(!$info){
- self::$static_error = "模板不存在";
- return false;
- }
- # 获取模板字段信息
- $columnInfo = $params['column'];
- # 对比提交的模板字段是否一致
- $req_column_id = array_column($columnInfo,'key');
- $req_column_value = array_column($columnInfo,'value');
- $tpl_column_id = array_column($info['columnsInfo'],'id');
- # 获取两个字段的差集
- $diff_column_id = array_diff($tpl_column_id,$req_column_id);
- # 存在差集则非法提交
- if(!empty($diff_column_id)){
- self::$static_error = "非法提交!";
- return false;
- }
- # 判断提交文字是否合法
- $sms_notice_data = [];
- foreach ($columnInfo as $k => $v) {
- if($info['columnsInfo'][$v['key']]['required'] && !$v['value']){
- self::$static_error = $info['columnsInfo'][$v['key']]['title'] . '为必填';
- return false;
- }
- $info_extra_data = !empty($info['columnsInfo'][$v['key']]['extra_data']) ? Json::decode($info['columnsInfo'][$v['key']]['extra_data']) : [];
- // 这个需要发送短信
- if (!empty($params['user_id']) && !empty($info_extra_data) &&
- !empty($info_extra_data['is_enable_sms_notice']) &&
- !empty($info_extra_data['sms_template_id']) &&
- !empty($info_extra_data['sms_template_content']) &&
- !empty($v['value'])) {
- // 发送短信
- $goods = SmartFormTemplateGoods::getOne([
- ['goods_id' => $form['goods_id'] ?? 0],
- ['template_id' => $form['id']],
- ['status' => StatusEnum::ENABLED],
- ]);
- if (!empty($goods)) {
- $sms_notice_data[] = self::packSendSmsData($info_extra_data, $params['user_id'],
- $v['value'], $info['columnsInfo'][$v['key']], $params['mall_id'], $form['goods_id'] ?? 0);
- }
- }
- # 存在选项值
- if($info['columnsInfo'][$v['key']]['option']){
- $option = [];
- $option_value = [];
- $option = explode(SmartFormEnum::FIRST_CUTTER,$info['columnsInfo'][$v['key']]['option']);
- $option_value = array_keys($option);
- if(in_array($v['value'],$option_value,true)){
- self::$static_error = $info['columnsInfo'][$v['key']]['title'] . '参数不合法';
- return false;
- }
- }
- switch ($info['columnsInfo'][$v['key']]['smart_form_components_code']) {
- case 'city-chose':
- # 省市区
- // $regin = Region::getOne([['id' => $v['value']]], true);
- $regin = Region::find()->select('name')->where(['id' => $v['value']])->asArray()->all();
- if(!$regin && $info['columnsInfo'][$v['key']]['required']){
- self::$static_error = '选择的城市不存在';
- return false;
- }
- break;
- case 'upload-photo':
- # 上传
- $leng = 1;
- if(is_array($v['value'])){
- $leng = count($v['value']);
- }
- if($info['columnsInfo'][$v['key']]['limit'] && $leng > $info['columnsInfo'][$v['key']]['limit']){
- self::$static_error = $info['columnsInfo'][$v['key']]['title'] . '超出限制长度';
- return false;
- }
- break;
-
- default:
- if(is_array($v['value'])){
- $leng = count($v['value']);
- }else{
- $leng = mb_strlen($v['value']);
- }
- if($info['columnsInfo'][$v['key']]['limit'] && $leng > $info['columnsInfo'][$v['key']]['limit']){
- self::$static_error = $info['columnsInfo'][$v['key']]['title'] . '超出限制长度';
- return false;
- }
- break;
- }
- $arr = [];
- $arr['smart_form_template_id'] = $form['id'];
- $arr['smart_form_template_user_form_id'] = 0;
- $arr['user_id'] = $params['user_id'];
- $arr['smart_form_components_id'] = $v['key'];
- $arr['smart_form_components_code'] = $info['columnsInfo'][$v['key']]['smart_form_components_code'];
- $arr['smart_form_components_title'] = $info['columnsInfo'][$v['key']]['title'];
- $arr['col_value'] = $v['value'];
- $arr['created_at'] = time();
- $arr['updated_at'] = time();
- $insert[] = $arr;
- }
- foreach ($tpl_column_id as $k1 => $v1) {
- if(is_array($tpl_column_id[$k1])){
- $tpl_column_id[$k1] = json_encode($tpl_column_id[$k1],JSON_UNESCAPED_UNICODE);
- }
- }
- foreach ($req_column_value as $k2 => $v2) {
- if(is_array($req_column_value[$k2])){
- $req_column_value[$k2] = json_encode($req_column_value[$k2],JSON_UNESCAPED_UNICODE);
- }
- }
- # 写入主表
- $formModel = new self();
- $formModel->loadDefaultValues();
- $formModel->mall_id = $params['mall_id'];
- $formModel->diy_page_id = $form['diy_page_id'];
- $formModel->smart_form_template_id = $form['id'];
- $formModel->user_id = $params['user_id'];
- $formModel->smart_form_template_column_id = implode(',',$tpl_column_id);
- $formModel->col_value = implode(',',$req_column_value);
- $formModel->source = $form['source'];
- $formModel->created_at = time();
- $formModel->updated_at = time();
- if(!$formModel->save()){
- self::$static_error = $formModel->getErrorMessage();
- return false;
- }
- foreach ($insert as $k => $v) {
- $insert[$k]['smart_form_template_user_form_id'] = $formModel->id;
- if(is_array($insert[$k]['col_value'])){
- $insert[$k]['col_value'] = implode(',',$insert[$k]['col_value']);
- }
- }
- # 写入明细
- $field = ['smart_form_template_id','smart_form_template_user_form_id','user_id','smart_form_components_id','smart_form_components_code','smart_form_components_title','col_value','created_at','updated_at'];
- $res = Yii::$app->db->createCommand()->batchInsert(AddonsSmartFormTemplateUserFormInfo::tableName(), $field, $insert)->execute();
- if ($res == false) {
- self::$static_error = '写入模板字段失败';
- return false;
- }
- if (!empty($sms_notice_data)) { // 短信发送
- foreach ($sms_notice_data as &$datum) {
- $datum['user_form_id'] = $formModel->id;
- }
- $res = Yii::$app->db->createCommand()->batchInsert(AddonsStartFormSmsNotice::tableName(),
- array_keys($sms_notice_data[0]), $sms_notice_data)->execute();
- if (!$res) {
- self::$static_error = '写入短信失败';
- return false;
- }
- }
- return $formModel;
- }
- /**
- * 拼凑发送短信数据
- * @param array $config
- * @param $user_id
- * @param $send_at
- * @param $column
- * @param $mall_id
- * @param $goods_id
- * @return array
- */
- public static function packSendSmsData(array $config, $user_id, $send_at, $column, $mall_id, $goods_id)
- {
- // 创建需要发送的记录
- // 定时去发送
- $send_at = strtotime("$send_at {$config['send_at']}");
- $send_at += intval($config['send_day']) * 86400;
- return [
- 'content' => $config['sms_template_content'],
- 'user_id' => $user_id,
- 'send_at' => $send_at,
- 'send_var' => Json::encode(!empty($config['vars']) ? $config['vars'] : []), // 怎么找出变量
- 'template_id' => $config['sms_template_id'],
- 'column_id' => $column['id'],
- 'created_at'=> time(),
- 'updated_at'=> time(),
- 'mall_id' => $mall_id,
- 'goods_id' => $goods_id,
- 'send_status' => !empty($goods_id) ? StatusEnum::DISABLED : StatusEnum::ENABLED,
- // 'status' => StatusEnum::DISABLED, // 默认是0,如果下单后那么将其修改为1,如果超过时间还是0则将其设置为2
- ];
- }
-
- public static function fieldsList($template_id,$field=null)
- {
- # 获取模板字段
- $select = " id,smart_form_components_code type,smart_form_components_code,title label";
- $header = AddonsSmartFormTemplateColumn::find()->select($select)
- ->orderBy('sort asc')
- ->where(['smart_form_template_id'=>$template_id])->asArray()->all();
- $fields['nickname'] = '填写人';
- foreach ($header as $k => $v) {
- $fields[$v['id']] = $v['label'];
- }
- if ($field === null) return $fields;
- $temp = [];
- foreach ($field as $val) {
- if (isset($fields[$val])) $temp[$val] = $fields[$val];
- }
- return $temp;
- }
- /**
- * 导出字段
- */
- public static function exportFieldsList($template_id,$field=null)
- {
- # 获取模板字段
- $select = 'id,smart_form_components_code type,smart_form_components_code,title';
- $header = AddonsSmartFormTemplateColumn::find()->select($select)
- ->orderBy('sort asc')
- ->where(['smart_form_template_id'=>$template_id])->asArray()->all();
- $fields['nickname'] = '填写人';
- $fields['created_at'] = '填表日期';
- foreach ($header as $k => $v) {
- $fields[$v['id']] = $v['title'];
- }
- if ($field === null) return $fields;
- $temp = [];
- foreach ($field as $val) {
- if (isset($fields[$val])) $temp[$val] = $fields[$val];
- }
- return $temp;
- }
- /**
- * @name:
- * @msg: 处理导出数据,这个方法是异步队列处理时使用的,请别修改
- * @param {array} $data
- * @return bool
- */
- public static function exportHandle(array $data)
- {
- $download_id = $data['download_id'] ?? 0;
- $download = Download::findOne(['id' => $download_id]);
- if ($download) {
- try {
- $params = json_decode($download->params, true);
- $filename = $download->name;
- $type = $download->type;
- $fields = $params['fields'];
- $have_select_field_arr = [];
- foreach ($fields as $value) {
- $have_select_field_arr[] = $value;
- }
- $csv = new CsvTool();
- $csv->filename = $filename;
- $csv->file_dirname = DownloadEnum::getTypeStorageDirMap($type);
- $csv->export_mode = CsvTool::EXPORT_MODE_ASYNC;
- $csv->header = $have_select_field_arr;
- $where = [];
- $where[] = ['=', 'a.smart_form_template_id', $params['template_id']];
- if(isset($params['date_start'])) $where[] = ['>=','a.created_at',strtotime($params['date_start'])];
- if(isset($params['date_end'])) $where[] = ['<=','a.created_at',strtotime($params['date_end'])];
- if(isset($params['keyword'])){
- $user_ids = User::find()
- ->where(['and',['like', 'nickname', $params['keyword']]])
- ->select('id')
- ->asArray()
- ->all();
- $user_id_arr = array_column($user_ids, 'id');
- $where[] = ['in', 'a.user_id', $user_id_arr];
- }
- $where[] = ['>=', 'a.status', StatusEnum::DISABLED];
- # 排序
- $order = 'a.created_at desc';
- # 显示字段
- $select = 'a.id,a.user_id,a.smart_form_template_column_id,a.col_value,a.source,a.created_at,a.updated_at';
-
- $filter = array('where' => $where, 'order' => $order, 'select' => $select, 'alias' => 'a');
- $query = self::find()->select($select);
- self::paramPack($filter, $query);
- # 结果集
- $columnInfo = $query->asArray(true)->all();
- $new_col = [];
- $new_col = [];
- foreach ($columnInfo as $k => $v) {
- $users = User::findOne($v["user_id"]);
- $nickname = "普通用户";
- if(!empty($users)){
- $nickname = $users->nickname;
- }
- $new_col[$k]['nickname'] = $nickname;
- $new_col[$k]['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
-
- // 用户填写表单的具体信息
- $v['formInfo'] = AddonsSmartFormTemplateUserFormInfo::find()
- ->where(['smart_form_template_user_form_id' => $v['id']])
- ->asArray()
- ->all();
- if(empty($v['formInfo'])){
- continue;
- // $v['formInfo'] = [];
- }
- // 表单label信息
- $template_columns = AddonsSmartFormTemplateColumn::find()
- ->where(['and',['in', 'id', array_column($v['formInfo'], 'smart_form_components_id')]])
- ->select('id, option')
- ->asArray()
- ->all();
- $template_columns = array_column($template_columns, 'option', 'id');
- foreach ($v['formInfo'] as $k1 => $v2) {
-
- $v2['option'] = isset($template_columns[$v2['smart_form_components_id']]) ? $template_columns[$v2['smart_form_components_id']] : [];
- switch ($v2['smart_form_components_code']) {
- case 'city-chose':
- $regin = Region::find()->select('name')->where(['id' => explode(',', $v2['col_value'])])->asArray()->all();
- $regin = implode(" ", array_column($regin, 'name'));
- $v2['col_value'] = $regin;
- break;
- case 'upload-photo':
- // $col_value = json_decode($v2['col_value'],true);
- // $v2['col_value'] = explode(',',$col_value);
- break;
- case 'checked-tool':
- # 多选
- // $col_value = json_decode($v2['col_value'], true);
- $col_value = explode(',', $v2['col_value']);
- if (strpos($v2['option'], SmartFormEnum::FIRST_CUTTER) !== false) {
- $col_option = explode(SmartFormEnum::FIRST_CUTTER, $v2['option']);
- } else {
- $col_option = (array)$v2['option'];
- }
- $new_col_option = [];
- if (is_array($col_value)) {
- foreach ($col_value as $ok => $ov) {
- if ($col_option[$ov]) {
- $new_col_option[] = $col_option[$ov];
- }
- }
- } else {
- $new_col_option[0] = $col_option[0];
- }
- $v2['col_value'] = implode(',', $new_col_option);
- break;
- case 'radio-tool':
- # 单选
- $col_value = json_decode($v2['col_value'], true);
- $col_value = explode(',', $col_value);
- if (strpos($v2['option'], SmartFormEnum::FIRST_CUTTER) !== false) {
- $col_option = explode(SmartFormEnum::FIRST_CUTTER, $v2['option']);
- } else {
- $col_option = (array)$v2['option'];
- }
- $new_col_option = [];
- if (is_array($col_value)) {
- foreach ($col_value as $ok => $ov) {
- if ($col_option[$ov]) {
- $new_col_option[] = $col_option[$ov];
- }
- }
- } else {
- $new_col_option[0] = $col_option[0];
- }
- $v2['col_value'] = implode(',', $new_col_option);
- break;
- case 'drow-box':
- # 下拉
- $col_value = json_decode($v2['col_value'], true);
- $col_value = explode(',', $col_value);
- if (strpos($v2['option'], SmartFormEnum::FIRST_CUTTER) !== false) {
- $col_option = explode(SmartFormEnum::FIRST_CUTTER, $v2['option']);
- } else {
- $col_option = (array)$v2['option'];
- }
- $new_col_option = [];
- if (is_array($col_value)) {
- foreach ($col_value as $ok => $ov) {
- if ($col_option[$ov]) {
- $new_col_option[] = $col_option[$ov];
- }
- }
- } else {
- $new_col_option[0] = $col_option[0];
- }
- $v2['col_value'] = implode(',', $new_col_option);
- break;
-
- case 'id-card':
- $v2['col_value'] = "'".$v2['col_value'];
- break;
- default:
- // $new_col[$k][$k1] = $v2['col_value'];
- break;
- }
- // $new_col[$k][$k1] = $v2['col_value'];
- $new_col[$k][$v2['smart_form_components_id']] = $v2['col_value'];
- }
- }
- $s = array_map(function ($vv) use ($fields) {
- $row = [];
- foreach ($fields as $k3 => $v3) {
- if (isset($vv[$k3])) {
- $row[] = $vv[$k3];
- }
- }
- return $row;
- }, $new_col);
- $csv->data = $s;
- $csv->export();
- $csv->updateDown($download, $params['mall_id']);
- return true;
- } catch (Exception $e) {
- $download->status = 3;
- $res = $download->save();
- var_dump($e->getMessage());
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- }
- }
|