Răsfoiți Sursa

整理draw程式

maa3606 2 ani în urmă
părinte
comite
26a78b35d3

+ 24 - 19
app/Http/Controllers/DrawController.php

@@ -26,26 +26,31 @@ class DrawController extends Controller
     {
 
         $prize = Prize::where('id', $request->prize_id)->first();
-        $activity = Activity::where('id', $request->activity_id)->first();
-        $users = CheckIn::where('activity_id', $request->activity_id)
-            ->where('is_checked_in', 'true')
-            ->where('is_awarded', 'false')
-            ->whereTime('check_ins.updated_at', '<=', $activity->deadline)
-            ->whereIn('region', $request->region)
-            ->inRandomOrder()
-            ->get();
-        if ($prize->count >= $request->number && count($users) >= $request->number) {
-            $output = [];
-            $draw_user = $users->random($request->number);
-            foreach ($draw_user as $user) {
-                array_push($output, [
-                    'user_id' => $user->user_id,
-                    'user_name' => $user->name,
-                    'department_id' => $user->department_id,
-                ]);
+        if ($prize->count > 0) {
+            $activity = Activity::where('id', $request->activity_id)->first();
+            $users = CheckIn::
+            where('activity_id', $request->activity_id)
+                ->where('is_checked_in', 'true')
+                ->where('is_awarded', 'false')
+                ->whereTime('check_ins.updated_at', '<=', $activity->deadline)
+                ->whereIn('region', $request->region)
+                ->join('departments', 'check_ins.department_id', '=', 'departments.department_id')
+                ->inRandomOrder()
+                ->get();
+            $draw_count = $request->draw_one ? 1 : $prize->count;
+
+            if ($draw_count <= count($users)) {
+                $output = [];
+                $draw_user = $users->random($draw_count);
+                foreach ($draw_user as $user) {
+                    array_push($output, [
+                        'user_id' => $user->user_id,
+                        'user_name' => $user->name,
+                        'department_name' => $user->department_name,
+                    ]);
+                }
+                return $output;
             }
-            
-            return $output;
         }
         return false;
     }

+ 16 - 7
app/Http/Controllers/RecipientsController.php

@@ -27,7 +27,16 @@ class RecipientsController extends Controller
     public function index_by_activity(UpdateRecipientsRequest $request)
     {
         return Recipients::join('prizes', 'recipients.prize_id', '=', 'prizes.id')
-            ->select('user_id', 'prizes.activity_id', 'prize_id', 'recipients.created_at')
+            ->join('users', 'recipients.user_id', '=', 'users.user_id')
+            ->select(
+                'prizes.activity_id',
+                'recipients.user_id',
+                'users.name as user_name',
+                'recipients.prize_id',
+                'prizes.name as prize_name',
+                'prizes.provider',
+                'recipients.created_at'
+            )
             ->where('prizes.activity_id', $request->activity_id)
             ->orderBy('recipients.created_at', 'DESC')
             ->get();
@@ -83,7 +92,7 @@ class RecipientsController extends Controller
      * @param  \App\Models\Recipients  $recipients
      * @return \Illuminate\Http\Response
      */
-    public function show(Request $request,Recipients $recipients)
+    public function show(Request $request, Recipients $recipients)
     {
         //
     }
@@ -186,8 +195,8 @@ class RecipientsController extends Controller
             ->orderBy('prizes.id')
             ->get();
 
-        $filename = "recipients_list_" . date('Y_m_d_H_i_s',time()) . ".csv";
-        $filepath = "./upload/".$filename;
+        $filename = "recipients_list_" . date('Y_m_d_H_i_s', time()) . ".csv";
+        $filepath = "./upload/" . $filename;
         $handle = fopen($filepath, 'w+');
         fputcsv($handle, array('prize', 'name', 'created_at'));
 
@@ -208,12 +217,12 @@ class RecipientsController extends Controller
         $prizeList = DB::select("SELECT [check_ins].[user_id],[name],[is_claimed],[alias] FROM [recipients] 
         LEFT JOIN [check_ins] ON [recipients].[user_id] = [check_ins].[user_id]
         LEFT JOIN [departments] ON [check_ins].[department_id] = [departments].[department_id]
-        WHERE [prize_id] = ? ORDER BY [check_ins].[department_id],[user_id];",[$prize_id]);
-        $prize = DB::select("SELECT [name] FROM [prizes] WHERE [id] = ?;",[$prize_id]);
+        WHERE [prize_id] = ? ORDER BY [check_ins].[department_id],[user_id];", [$prize_id]);
+        $prize = DB::select("SELECT [name] FROM [prizes] WHERE [id] = ?;", [$prize_id]);
         $response = [
             "prize" => $prize,
             "list" => $prizeList,
-            
+
         ];
         return response($response, 201);
     }

+ 1 - 1
resources/js/src/router/config.js

@@ -214,7 +214,7 @@ export const settings = {
             name: 'draw',
             component: () => import('@/views/lottery/Draw.vue'),
             meta: {
-                pageTitle: 'Draw',
+                pageTitle: '抽獎',
                 breadcrumb: [{
                         text: '活動列表',
                         to: '/activityList'

+ 60 - 189
resources/js/src/views/lottery/Draw.vue

@@ -2,9 +2,9 @@
   <div>
     <b-row class="prize-list-wrapper">
       <b-col md="6">
-        <b-card title="獎項列表" style="height:75vh;">
-          <b-table responsive hover sticky-header=true :items="getPrizeList(prizeList)" bordered :fields="fields"
-            @row-clicked="click" style="max-height: 57vh; overflow: auto;">
+        <b-card title="獎項列表" style="height:70vh;">
+          <b-table responsive hover sticky-header=true :items="prizeList" bordered :fields="prizeTableFields"
+            style="max-height: 52vh; overflow: auto;" @row-clicked="click">
             <template #cell(ICON)="data">
               <div class="text-center">
                 <feather-icon :icon="data.value" />
@@ -20,17 +20,17 @@
 
       <b-modal ref="draw-modal" id="draw-modal" centered title="抽獎" no-stacking hide-footer>
         <label>獎品:</label>
-        <b-form-input v-model="prize" :disabled=true />
+        <b-form-input v-model="prizeName" :disabled=true />
         <br>
         <label>地區: </label>
-        <v-select multiple v-model="region" :options="regionOption" />
+        <v-select multiple v-model="drawOption.region" :options="regionOption" />
         <br>
         <label>數量: </label>
         <div class="demo-inline-spacing">
-          <b-form-radio v-model="drawOne" name="some-radios" :value=true>
+          <b-form-radio v-model="drawOption.draw_one" name="some-radios" :value=true>
             單抽
           </b-form-radio>
-          <b-form-radio v-model="drawOne" name="some-radios" :value=false>
+          <b-form-radio v-model="drawOption.draw_one" name="some-radios" :value=false>
             全抽
           </b-form-radio>
         </div>
@@ -54,20 +54,15 @@
         </b-button>
       </b-modal>
 
-      <b-modal ref="draw-animation" title="得獎者是......" centered no-stacking hide-footer>
+      <b-modal ref="draw-output" title="得獎者是......" centered no-stacking hide-footer>
         <br>
         <div :key="index" v-for="(item, index) in drawList" :class=counterId(index)>
-          <i :datafinal=item.department>部門</i>
-          <div :datafinal=item.userId>
-            <i>0</i>
-            <i>0</i>
-            <i>0</i>
-            <i>0</i>
-            <span :datafinal=item.userName></span>
-          </div>
+          <i>{{ item.user_id }}</i>
+          <span>{{ item.user_name }}</span>
+          <span>{{ item.department_name }}</span>
         </div>
 
-        <div v-if="drawOne">
+        <div v-if="drawOption.draw_one">
           <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="outline-primary" block
             @click="donate">
             捐出
@@ -81,13 +76,13 @@
 
       <b-modal ref="add-prize" centered title="加碼" no-stacking hide-footer>
         <label>獎品:</label>
-        <b-form-input v-model="addPrizeName" />
+        <b-form-input v-model="addPrizeOption.name" />
         <br>
         <label>加碼者: </label>
-        <b-form-input v-model="addPrizeUser" />
+        <b-form-input v-model="addPrizeOption.provider" />
         <br>
         <label>數量: </label>
-        <b-form-spinbutton v-model="addPrizeNumber" min="1" />
+        <b-form-spinbutton v-model="addPrizeOption.count" min="1" />
 
         <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
           @click="hideModal">
@@ -99,9 +94,9 @@
       </b-modal>
 
       <b-col md="6">
-        <b-card title="抽獎紀錄" style="height:75vh;">
-          <b-table responsive sticky-header=true :items="getRecipientsList(recipientsList)" bordered
-            style="max-height: 65vh; overflow: auto;">
+        <b-card title="抽獎紀錄" style="height:70vh;">
+          <b-table responsive sticky-header=true :items="recipientsList" bordered :fields="recipientsTableFields"
+            style="max-height: 60vh; overflow: auto;">
             <template #cell(ICON)="data">
               <div class="text-center">
                 <feather-icon :icon="data.value" />
@@ -144,85 +139,40 @@ export default {
   },
   data() {
     return {
-      activityId: this.$route.params.activity_id,
-      activity: {},
-      userList: [],
-      departmentList: [],
       prizeList: [],
       recipientsList: [],
 
-      fields: ['獎項', '數量'],
+      prizeTableFields: ['name', 'provider', 'count'],
+      recipientsTableFields: ['prize_name', 'user_id', 'user_name', 'created_at'],
       regionOption: ['北區', '中區', '南區', '來賓'],
-      region: ['北區', '中區', '南區', '來賓'],
-      drawMax: 1,
-      drawOne: true,
 
-      prize: '',
-      prizeId: '',
-      drawList: [],
-
-      addPrizeName: '',
-      addPrizeUser: '',
-      addPrizeNumber: 1,
+      prizeName: '',
+      drawOption: {
+        activity_id: this.$route.params.activity_id,
+        prize_id: '0',
+        region: ['北區', '中區', '南區', '來賓'],
+        draw_one: true,
+      },
+      addPrizeOption: {
+        activity_id: this.$route.params.activity_id,
+        name: '',
+        provider: '',
+        count: 1,
+      },
 
-      departments: [
-        "行管部庶務科",
-        "人力資源科",
-        "行管部文書科",
-        "南區辦事處",
-        "中區辦事處",
-        "工程管理一部",
-        "工程管理二部",
-        "發展與企畫部",
-        "工程製圖科",
-        "工務部",
-        "大地工程部",
-        "財務部",
-        "運輸土木部",
-        "城鄉發展部",
-        "軌道工程部",
-        "董事長室",
-        "總經理室",
-        "企業發展中心",
-        "成本中心",
-        "資訊中心",
-        "環境水務部",
-        "環境永續部",
-        "機電工程部",
-        "結構工程部",
-        "工程設計群",
-        "工程監理群",
-        "總管理處",
-        "建築及設施群",
-        "數位發展部",
-        "淡海輕軌專案",
-        "安坑輕軌專案",
-        "先進技術中心",
-        "塭仔圳專案",
-        "萬大市場專案",
-        "來賓"
-      ]
+      drawList: [],
     }
   },
   created() {
-    useJwt.postData('/api/activity/show', { activity_id: this.activityId }).then(res => {
-      this.activity = res.data;
-    });
-
-    useJwt.postData('/api/check_in/index_by_activity', { activity_id: this.activityId }).then(res => {
-      this.userList = res.data;
-    });
-
-    useJwt.postData('/api/prize/index_by_activity', { activity_id: this.activityId }).then(res => {
+    useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
       this.prizeList = res.data;
     });
 
-    useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.activityId }).then(res => {
+    useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
       this.recipientsList = res.data;
-    });
-
-    useJwt.postData('/api/department/index').then(res => {
-      this.departmentList = res.data;
+      this.recipientsList.forEach(element => {
+        element.created_at = this.dateFormat(element.created_at);
+      });
     });
   },
   methods: {
@@ -230,48 +180,19 @@ export default {
       var d = new Date(date);
       return d.getFullYear()
         + '/' + (d.getMonth() + 1).toString().padStart(2, '0')
-        + '/' + d.getDay().toString().padStart(2, '0')
+        + '/' + d.getDate().toString().padStart(2, '0')
         + '/' + d.getHours().toString().padStart(2, '0')
         + ':' + d.getMinutes().toString().padStart(2, '0')
         + ':' + d.getSeconds().toString().padStart(2, '0');
     },
-    getPrizeList(prizeList) {
-      var output = [];
-      prizeList.forEach(element => {
-        output.push({ id: element.id, '獎項': element.name, '數量': element.count });
-      });
-      return output;
-    },
-    getPrizeName(prizeId) {
-      var output = '';
-      this.prizeList.forEach(element => {
-        if (prizeId == element.id) {
-          output = element.name;
-        }
-      });
-      return output;
-    },
-    getRecipientsList(recipientsList) {
-      var output = [];
-      recipientsList.forEach(element => {
-        output.push({ '獎項': this.getPrizeName(element.prize_id), '獲獎人': this.userList[element.user_id], '時間': this.dateFormat(element.created_at) });
-      });
-      return output;
-    },
-    counterId(id) {
-      return "counter_" + id;
-    },
-    drawNumber() {
-      if (this.drawOne) {
-        return 1;
-      }
-      return this.drawMax;
+    counterId(id){
+      return 'counter_' + id;
     },
     showDraw() {
       this.$refs['draw-modal'].show();
     },
-    showDrawAnimation() {
-      this.$refs['draw-animation'].show();
+    showDrawOutput() {
+      this.$refs['draw-output'].show();
     },
     showAddPrize() {
       this.$refs['add-prize'].show();
@@ -282,43 +203,36 @@ export default {
     hideModal() {
       this.$refs['draw-modal'].hide();
       this.$refs['draw-error'].hide();
-      this.$refs['draw-animation'].hide();
+      this.$refs['draw-output'].hide();
       this.$refs['add-prize'].hide();
       this.updateDataset();
     },
     updateDataset() {
-      useJwt.postData('/api/prize/index_by_activity', { activity_id: this.activityId }).then(res => {
+      useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
         this.prizeList = res.data;
       });
-      useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.activityId }).then(res => {
+      useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
         this.recipientsList = res.data;
+        this.recipientsList.forEach(element => {
+          element.created_at = this.dateFormat(element.created_at);
+        });
       });
     },
     click(params) {
-      this.prize = this.getPrizeName(params.id);
-      this.prizeId = params.id;
-      this.drawOne = true;
-      this.drawMax = params["數量"];
       this.drawList = [];
-      if (this.drawMax == 0) {
-        this.showDrawError();
-      } else {
+      if (params.count > 0) {
+        this.prizeName = params.name;
+        this.drawOption.prize_id = params.id;
         this.showDraw();
+      } else {
+        this.showDrawError();
       }
     },
     draw() {
-      useJwt.postData('/api/draw/draw', {
-        activity_id: this.activityId,
-        prize_id: this.prizeId,
-        region: this.region,
-        number: this.drawNumber()
-      }).then(res => {
+      useJwt.postData('/api/draw/draw', this.drawOption).then(res => {
         if (res.data) {
           this.drawList = res.data;
-          setTimeout(() => {
-            this.count();
-          }, 500);
-          this.showDrawAnimation();
+          this.showDrawOutput();
         } else {
           this.showDrawError();
           console.log("draw error");
@@ -332,11 +246,10 @@ export default {
       });
       useJwt.postData('/api/draw/store', {
         users: idList,
-        prize_id: String(this.prizeId),
-        number: this.drawNumber()
+        prize_id: this.drawOption.prize_id,
       }).then(res => {
         if (res.data) {
-          console.log("store success");
+          console.log(res.data);
         } else {
           console.log("store error");
         }
@@ -358,12 +271,7 @@ export default {
       });
     },
     addPrize() {
-      useJwt.postData('/api/prize/store', {
-        activity_id: this.activityId,
-        name: this.addPrizeName,
-        provider: this.addPrizeUser,
-        count: this.addPrizeNumber
-      }).then(res => {
+      useJwt.postData('/api/prize/store', this.addPrizeOption).then(res => {
         if (res.data) {
           console.log("add prize success");
         } else {
@@ -372,43 +280,6 @@ export default {
         this.hideModal();
       });
     },
-    count() {
-      var departments = this.departments;
-      var numbers = "0123456789"
-      var string = numbers;
-
-      this.drawList.forEach((element, index) => {
-        var departmentName = this.departmentList[element.department_id];
-        var deps = document.querySelectorAll(".counter_" + index + " > i");
-        var allCounters = document.querySelectorAll(".counter_" + index + " > div > i");
-
-        deps.forEach(function (el) {
-          var duration = 1000;
-          var interval = setInterval(function () {
-            el.innerText = departments[Math.floor(Math.random() * departments.length)];
-            duration = duration - 50;
-            if (duration <= 0) {
-              clearInterval(interval);
-              el.innerText = departmentName;
-            }
-          }, 50);
-        });
-        allCounters.forEach((el, i) => {
-          var duration = 500 + i * 1000;
-          var interval = setInterval(e => {
-            el.innerText = string.charAt(Math.random() * string.length);
-            duration = duration - 50;
-            if (duration <= 0) {
-              clearInterval(interval);
-              el.innerText = element.user_id[i];
-              if (i == 3) {
-                document.querySelectorAll(".counter_" + index + " > div > span")[0].innerText = element.user_name;
-              }
-            }
-          }, 50);
-        });
-      });
-    },
   },
 }
 </script>