Browse Source

修改分销商时导入模版与变量

moshaorui 5 months ago
parent
commit
d0b9a5efcd

+ 1 - 1
app/Admin/Actions/Grid/AppearanceImport.php

@@ -46,7 +46,7 @@ class AppearanceImport extends RowAction
         $this->sourcePath = $path;
         $this->appearanceId = $appearanceId;
         // 清空旧的
-        DistAppearanceTemplate::deleteTemplates(0, $appearanceId);
+        DistAppearanceTemplate::deleteTemplates($appearanceId, 0);
         // 导入模板
         $this->readDirectory($path);
         // 更新状态

+ 19 - 4
app/Admin/Controllers/DistAdminDistributorController.php

@@ -3,6 +3,7 @@
 namespace App\Admin\Controllers;
 
 use App\Admin\Repositories\DistAdminDistributor;
+use App\Admin\Repositories\DistAppearance;
 use Dcat\Admin\Form;
 use Dcat\Admin\Grid;
 use Dcat\Admin\Show;
@@ -31,7 +32,7 @@ class DistAdminDistributorController extends AdminController
      */
     protected function grid()
     {
-        return Grid::make(new DistAdminDistributor(), function (Grid $grid) {
+        return Grid::make(DistAdminDistributor::with(['appearance']), function (Grid $grid) {
             $grid->column('id')->sortable();
             $grid->column('company_name','Company Name');
             $grid->column('site_name');
@@ -39,6 +40,7 @@ class DistAdminDistributorController extends AdminController
             $grid->column('country');
             $grid->column('contact_number');
             $grid->column('service_hotline');
+            $grid->column('appearance.title' ,'appearance');
             $grid->column('enabled')->switch();
             $grid->column('created_at');
             $grid->column('updated_at')->sortable();
@@ -71,12 +73,13 @@ class DistAdminDistributorController extends AdminController
      */
     protected function detail($id)
     {
-        return Show::make($id, new DistAdminDistributor(), function (Show $show) {
+        return Show::make($id, DistAdminDistributor::with(['appearance']), function (Show $show) {
             $show->field('id');
             $show->field('company_name','Company Name');
             $show->field('company_address','Company Address');
             $show->field('site_name');
             $show->field('level_domain');
+            $show->field('appearance.title' ,'appearance');
             $show->field('country');
             $show->field('contact_number');
             $show->field('service_hotline');
@@ -87,7 +90,7 @@ class DistAdminDistributorController extends AdminController
             $show->field('linkedin');
             $show->field('tiktok');
             $show->field('remark');
-            $show->width(6)->field('enabled')->using(config('dictionary.enabled'));
+            $show->field('enabled')->using(config('dictionary.enabled'));
             $show->field('created_at');
             $show->field('updated_at');
             // 按钮
@@ -108,6 +111,7 @@ class DistAdminDistributorController extends AdminController
             $form->text('company_address','Company Address');
             $form->text('site_name')->required();
             $form->text('level_domain')->required();
+            $form->select('appearance_id','select appearance')->options(DistAppearance::selectOptions())->required();
             $form->text('country')->required();
             $form->text('contact_number');
             $form->text('service_hotline');
@@ -119,6 +123,16 @@ class DistAdminDistributorController extends AdminController
             $form->text('tiktok');
             $form->textarea('remark');
             $form->switch('enabled')->default(1);
+            //保存前回调
+            $form->saving(function (Form $form) {
+                if (!$form->isCreating()) {
+                    //如果appearance_id有变化,则更新模版与变量
+                    if ($form->model()->appearance_id != $form->input('appearance_id')) {
+                        $id = $form->model()->id;
+                        DistAppearance::switchTheme($form->input('appearance_id'), $id);
+                    }
+                }
+            });
             //保存后回调
             $form->saved(function (Form $form, $result) {
                 if ($form->isCreating()) {
@@ -131,9 +145,10 @@ class DistAdminDistributorController extends AdminController
                         'enabled' => 1,
                         'dist_id'=>$newId,
                     ]);
+                    //更新模版与变量
+                    DistAppearance::switchTheme($form->input('appearance_id'), $newId);
                 }
             });
         });
-
     }
 }

+ 1 - 1
app/Admin/Controllers/DistAdminUserController.php

@@ -122,10 +122,10 @@ class DistAdminUserController extends AdminController
             });
             $form->text('name','name')->required();
             $form->select('language')->options(config('dictionary.languages'))->required();
-            $form->switch('enabled')->default(1);
             $form->selectTable('dist_id', 'Select Distributor')
                 ->title('distId')
                 ->from(DistDistributorTable::make());
+            $form->switch('enabled')->default(1);
             //保存前回调
             $form->saving(function (Form $form) {
                 //判断用户名是否重复

+ 25 - 16
app/Admin/Controllers/DistAppearanceVariableController.php

@@ -32,27 +32,33 @@ class DistAppearanceVariableController extends AdminController
         $templateId = isset($_GET['templateId']) ? intval($_GET['templateId']) : 0;
         $appearanceId = isset($_GET['appearanceId']) ? intval($_GET['appearanceId']) : 0;
         $distId = isset($_GET['distId']) ? intval($_GET['distId']) : 0;
-        if (empty($templateId) || empty($appearanceId)) {
-            die(' templateId or appearanceId is empty');
+        if (empty($appearanceId)) {
+            die(' <h3>Please select the theme.<h3>');
         }
         return Grid::make(DistAppearanceVariable::with(['distributor','appearance']), function (Grid $grid) use ($templateId, $appearanceId, $distId) {
             $grid->column('id')->sortable();
             $grid->column('distributor.company_name','Distributor Name')->display(function ($company_name) {
                 if (empty($company_name)) {
-                    return 'Raw Template Variables';
+                    return '-';
                 }
                 return $company_name;
-            })->help('If the distributor is empty, then use the Raw Template Variables.');
-            $grid->column('appearance.title','Appearance Title');
-            $grid->column('template_ids','site variable')->display(function ($templateIds) {
+            });
+            $grid->column('appearance.title','Appearance');
+            //变量名
+            $grid->column('variable_name');
+            //变量类型
+            $grid->column('variable_type')->using(['1' => 'text', '2' => 'textarea', '3' => 'json']);
+            //是否是站点变量
+            $grid->column('template_id','site variable')->display(function ($templateIds) {
                 if ($templateIds == 0) {
                     return 'Yes';
                 } else {
                     return 'No';
                 }
-            });
-            $grid->column('variable_name');
-            $grid->column('variable_type')->using(['1' => 'text', '2' => 'textarea', '3' => 'json']);
+            })->label([
+                '0' => 'success',
+                '1' => 'default',
+            ]);;
             //搜索
             $grid->quickSearch(['variable_name']);
             //工具栏
@@ -62,7 +68,7 @@ class DistAppearanceVariableController extends AdminController
             $grid->disableEditButton();
             $addUrl = '?templateId='. $templateId . '&appearanceId='. $appearanceId . '&distId='. $distId;
             //排序
-            $grid->model()->where('appearance_id', $appearanceId)->where('dist_id', $distId)->whereIn('template_ids', [0, $templateId])->orderBy("id",'asc');
+            $grid->model()->where('appearance_id', $appearanceId)->where('dist_id', $distId)->whereIn('template_id', [0, $templateId])->orderBy("id",'asc');
             //增加js 向新增按钮添加参数还有编辑按钮添加参数
 
             Admin::script(
@@ -130,11 +136,12 @@ JS
             $form->display('id');
             $form->hidden('appearance_id')->value($appearanceId);
             $form->hidden('dist_id')->value($distId);
-            $form->hidden('template_ids')->value($templateId);
-            //编辑时当template_ids为0时,site_variable为默认值1,否则为0
+            $form->hidden('template_id')->value($templateId);
+            $form->hidden('variable_code');
+            //编辑时当template_id为0时,site_variable为默认值1,否则为0
             $variableDefaul = 0;
             if (!$form->isCreating()) {
-                if ($form->model()->template_ids == 0) {
+                if ($form->model()->template_id == 0) {
                     $variableDefaul = 1;
                 }
             }
@@ -145,13 +152,15 @@ JS
                 '3'=>'json'
             ])->default(1);
             $form->text('variable_name');
-            $form->textarea('variable_value');
-
+            $form->textarea('variable_value')->rows(12);
             $form->ignore(['site_variable']);
 
             $form->submitted(function (Form $form) {
                 if ($form->site_variable == 1) {
-                    $form->template_ids = 0;
+                    $form->template_id = 0;
+                }
+                if ($form->isCreating()) {
+                    $form->variable_code = uniqueCode();
                 }
             });
 

+ 22 - 1
app/Admin/Repositories/DistAppearance.php

@@ -17,7 +17,7 @@ class DistAppearance extends EloquentRepository
 
     public static function selectOptions()
     {
-        $data = Model::all();
+        $data = Model::where('enabled', 1)->get();
         $options = [];
         foreach ($data as $item) {
             $options[$item->id] = $item->title;
@@ -39,4 +39,25 @@ class DistAppearance extends EloquentRepository
         return true;
     }
 
+    /*
+     * 切换主题操作,生成销应商主题模版与变量
+     * (如果原本就有模板与变量,不会重复生成)
+     */
+    public static function switchTheme($appearanceId,$distId) {
+        DistAppearanceTemplate::copyTemplateToDist($appearanceId, $distId);
+        DistAppearanceVariable::copyAppearanceVariable($appearanceId, $distId);
+        return true;
+    }
+
+    /*
+     * 初始化分销商模版与变量
+     */
+    public static function initTheme($appearanceId,$distId)
+    {
+        //请空模版与变量
+        DistAppearanceTemplate::deleteTemplates($appearanceId,$distId);
+        DistAppearanceVariable::deleteVariable($appearanceId, $distId);
+        //重新生成模版与变量
+        self::switchTheme($appearanceId, $distId);
+    }
 }

+ 12 - 1
app/Admin/Repositories/DistAppearanceTemplate.php

@@ -61,7 +61,7 @@ class DistAppearanceTemplate extends EloquentRepository
     /*
      * 请空指定模板
      */
-    public static function deleteTemplates($distId,$appearanceId) {
+    public static function deleteTemplates($appearanceId,$distId) {
         $self = new self();
         $self->model()->where('dist_id',$distId)->where('appearance_id',$appearanceId)->delete();
         return true;
@@ -79,6 +79,7 @@ class DistAppearanceTemplate extends EloquentRepository
         $model->parent_id = $parentId;
         $model->file_type = 0;
         $model->file_path = $filePath;
+        $model->template_code = uniqueCode('');
         $model->save();
         // 获取插入数据的 ID
         $insertedId = $model->id;
@@ -98,9 +99,19 @@ class DistAppearanceTemplate extends EloquentRepository
         $model->file_type = 1;
         $model->file_path = $filePath;
         $model->content = $content;
+        $model->template_code = uniqueCode('');
         $model->save();
         // 获取插入数据的 ID
         $insertedId = $model->id;
         return $insertedId;
     }
+
+    /*
+     * 把原始模板复制给分销商
+     */
+    public static function copyTemplateToDist($appearanceId,$distId) {
+        return Model::copyTemplateToDist($appearanceId, $distId);
+    }
+
+
 }

+ 14 - 1
app/Admin/Repositories/DistAppearanceVariable.php

@@ -19,7 +19,7 @@ class DistAppearanceVariable extends EloquentRepository
     public static function getVariableRow($distId,$appearanceId,$templateId)
     {
         $model = new Model();
-        $variable = $model->where('dist_id',$distId)->where('appearance_id',$appearanceId)->whereIn('template_ids',[0,$templateId])->get();
+        $variable = $model->where('dist_id',$distId)->where('appearance_id',$appearanceId)->whereIn('template_id',[0,$templateId])->get();
         if($variable){
             return $variable;
         }else{
@@ -27,8 +27,21 @@ class DistAppearanceVariable extends EloquentRepository
         }
     }
 
+    /*
+     * 把原始变量复制给分销商
+     */
+    public static function copyAppearanceVariable($appearanceId, $distId){
+        Model::copyAppearanceVariable($appearanceId, $distId);
+    }
 
 
+    /*
+     * 删除分销商主题变量
+     */
+    public static function deleteVariable($appearanceId,$distId)
+    {
+        return Model::where('appearance_id', $appearanceId)->where('dist_id', $distId)->delete();
+    }
 
 
 }

+ 11 - 0
app/Models/DistAdminDistributor.php

@@ -11,8 +11,19 @@ class DistAdminDistributor extends Model
 	use HasDateTimeFormatter;
     protected $table = 'dist_admin_distributor';
 
+    /*
+     * 用户一对多关联
+     */
     public function user()
     {
         return $this->hasMany(DistAdminUser::class, 'dist_id', 'id');
     }
+
+    /*
+     * 外观一对一关联
+     */
+    public function appearance()
+    {
+        return $this->hasOne(DistAppearance::class, 'id', 'appearance_id');
+    }
 }

+ 47 - 1
app/Models/DistAppearanceTemplate.php

@@ -5,10 +5,56 @@ namespace App\Models;
 use Dcat\Admin\Traits\HasDateTimeFormatter;
 
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\DB;
 
 class DistAppearanceTemplate extends Model
 {
 	use HasDateTimeFormatter;
     protected $table = 'dist_appearance_template';
-    
+
+    /*
+     * 把原始模板复制给分销商
+     */
+    public static function copyTemplateToDist($appearanceId,$distId) {
+        $appearanceId = intval($appearanceId);
+        $distId = intval($distId);
+        $count = self::where('dist_id', $distId)->where('appearance_id', $appearanceId)->count();
+        if ($count > 0) {
+            return;
+        }
+        //复制
+        DB::statement("
+INSERT INTO `dist_appearance_template` (`dist_id`, `appearance_id`, `file_name`, `file_path`, `content`, `created_at`, `updated_at`, `parent_id`, `file_type`,`template_code`)
+SELECT {$distId}, `appearance_id`, `file_name`, `file_path`, `content`, NOW(), NOW(), `parent_id`, `file_type`,`template_code`
+FROM `dist_appearance_template`
+WHERE `dist_id` = 0 AND `appearance_id` = {$appearanceId};
+        ");
+        //更新parent_id
+        $rows = self::select('id','file_path','file_name','parent_id')->where('dist_id',$distId)->where('appearance_id',$appearanceId)->get();
+        if ($rows) {
+            $updateData = [];
+            foreach ($rows as $row) {
+                $parentId = $row->parent_id;
+                if ($parentId > 0) {
+                    $newParentId = self::findParentId($rows, $row->file_path, $row->file_name);
+                    if ($newParentId > -1) {
+                        $updateData[] = ['id' => $row->id, 'parent_id' => $newParentId];
+                    }
+                }
+            }
+            //批量更新
+            if ($updateData) {
+                self::upsert($updateData,['id'],['parent_id']);
+            }
+        }
+    }
+    private static function findParentId(&$rows,$filePath,$fileName) {
+        foreach ($rows as $row) {
+            $filePath = str_replace('/'.$fileName,'',$filePath);
+            if ($row->file_path == $filePath) {
+                return $row->id;
+            }
+        }
+        return -1;
+    }
 }

+ 59 - 1
app/Models/DistAppearanceVariable.php

@@ -5,13 +5,14 @@ namespace App\Models;
 use Dcat\Admin\Traits\HasDateTimeFormatter;
 
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\DB;
 
 class DistAppearanceVariable extends Model
 {
 	use HasDateTimeFormatter;
     protected $table = 'dist_appearance_variable';
 
-    protected $fillable = ['dist_id', 'appearance_id', 'variable_name','variable_value','variable_type','created_at','updated_at','template_ids'];
+    protected $fillable = ['dist_id', 'appearance_id', 'variable_name','variable_value','variable_type','created_at','updated_at','template_id'];
 
     /*
      * 关联到分销商表
@@ -29,4 +30,61 @@ class DistAppearanceVariable extends Model
         return $this->hasOne(DistAppearance::class, 'id', 'appearance_id');
     }
 
+
+    /*
+     * 把原始变量复制给分销商
+     */
+    public static function copyAppearanceVariable($appearanceId, $distId){
+        $distId = intval($distId);
+        $appearanceId = intval($appearanceId);
+
+        $count = self::where('dist_id', $distId)->where('appearance_id', $appearanceId)->count();
+        if ($count > 0) {
+            return;
+        }
+        //复制
+        DB::statement("
+INSERT INTO `dist_appearance_variable` (`dist_id`, `appearance_id`, `variable_name`, `variable_value`, `variable_type`, `created_at`, `updated_at`, `template_id`,`variable_code`)
+SELECT {$distId}, `appearance_id`, `variable_name`, `variable_value`, `variable_type`, NOW(), NOW(), `template_id`,`variable_code`
+FROM `dist_appearance_variable`
+WHERE `dist_id` = 0 AND `appearance_id` = {$appearanceId};
+        ");
+        //更新模版ID
+        $tmpModel = new DistAppearanceTemplate();
+        $tmpRow = $tmpModel->select('id','dist_id','file_path','file_name','parent_id')->wherein('dist_id',[0,$distId])->where('appearance_id',$appearanceId)->get();
+        $variableRows = self::select('id','dist_id','appearance_id','variable_name','template_id')->where('dist_id', $distId)->where('appearance_id', $appearanceId)->get();
+        if ($variableRows) {
+            $updateData = [];
+            foreach ($variableRows as $row) {
+                if ($row->template_id > 0) {
+                    $newTemplateId = self::findTemplateId($row->template_id,$tmpRow);
+                    if ($newTemplateId > -1) {
+                        $updateData[] = ['id' => $row->id, 'template_id' => $newTemplateId];
+                    }
+                }
+            }
+            //批量更新
+            if ($updateData) {
+                self::upsert($updateData,['id'],['template_id']);
+            }
+        }
+    }
+    private static function findTemplateId($oldTemplateId,&$tmpRow)
+    {
+        if (!$tmpRow) {return -1;}
+        $oldRow = null;
+        foreach ($tmpRow as $row) {
+            if ($row->id == $oldTemplateId && $row->dist_id == 0) {
+                $oldRow = $row;
+            }
+        }
+        if ($oldRow) {
+            foreach ($tmpRow as $row) {
+                if ($oldRow->file_path == $row->file_path && $row->dist_id > 0) {
+                    return $row->id;
+                }
+            }
+        }
+        return -1;
+    }
 }

+ 12 - 0
app/helpers.php

@@ -2,6 +2,7 @@
 
 use Illuminate\Support\Arr;
 use Illuminate\Support\Facades\Session;
+use Illuminate\Support\Str;
 
 if (! function_exists('user_admin_config')) {
     function user_admin_config($key = null, $value = null)
@@ -99,3 +100,14 @@ if (!function_exists('flattenTree')) {
         return $result;
     }
 }
+
+if (!function_exists('uniqueCode')) {
+
+    function uniqueCode($prefix = '')
+    {
+        //$uniqueId = strtolower(Str::random($length));
+        $uniqueId = uniqid($prefix);
+        return $uniqueId;
+    }
+}
+

+ 15 - 1
resources/views/admin/pages-custom/ace.blade.php

@@ -98,6 +98,7 @@
     });
 
     $(document).ready(function() {
+        var loadingIndex = '';
         var fileId = '';
         var changeIframeUrl = function() {
             appearance_id = $('select[name="appearance_id"]').val();
@@ -108,7 +109,7 @@
         //中间的Ace编辑器,内容展示
         var actionclick = function() {
             $('.file-action').click(function() {
-                var loadingIndex = layer.load(1, {
+                loadingIndex = layer.load(1, {
                     shade: [0.5, '#000'] // 设置遮罩层
                 });
 
@@ -156,6 +157,7 @@
                     dist_id: dist_id
                 },
                 success: function(response) {
+                    layer.close(loadingIndex);
                     $('.main-card-body').html(response);
                     actionclick();
                 }
@@ -163,9 +165,21 @@
         }
         //左边外观选择与分销商选择联动
         $('select[name="appearance_id"]').change(function() {
+            loadingIndex = layer.load(1, {
+                shade: [0.5, '#000'] // 设置遮罩层
+            });
+            //请空编辑器内容
+            editor.setValue('');
+            //显示代码树
             postData();
         });
         $('input[name="dist_id"]').change(function() {
+            loadingIndex = layer.load(1, {
+                shade: [0.5, '#000'] // 设置遮罩层
+            });
+            //请空编辑器内容
+            editor.setValue('');
+            //显示代码树
             postData();
         });
         // 模版编辑保存