Просмотр исходного кода

Merge branch 'llp_gift_26_04_10' into dev

llp 5 дней назад
Родитель
Сommit
cae4125db7

+ 111 - 0
packages/Longyi/Gift/src/Console/Commands/ImportGiftCards.php

@@ -0,0 +1,111 @@
+<?php
+
+namespace Longyi\Gift\Console\Commands;
+
+use Illuminate\Console\Command;
+use Longyi\Gift\Models\GiftCards;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Monolog\Logger;
+use Monolog\Handler\StreamHandler;
+
+class ImportGiftCards extends Command
+{
+    protected $signature = 'gift-cards:import {--force}';
+    protected $customLogger = null;
+    protected $logFile = 'gift_import.log';
+
+    public function handle()
+    {
+        set_time_limit(0);
+        $limit = 500;
+        $offset = 0;
+        // 初始化自定义日志
+        $this->initCustomLogger($this->logFile);
+        //用户等级
+        $data = [];
+        do {
+            try {
+                $data = $this->fetchData($offset, $limit);
+                $this->saveDatas($data);
+                $offset = $offset + $limit;
+            } catch (\Exception $e) {
+                $this->logError(sprintf('[GiftCard Import] Error at offset %d: %s', $offset, $e->getMessage()));
+                exit(1);
+            }
+            echo $offset;
+            echo PHP_EOL;
+
+        } while (is_array($data) && !empty($data));
+
+        echo 'gift card import over~~';
+        echo PHP_EOL;
+    }
+
+    protected function fetchData($offset, $limit)
+    {
+        $sql = "select * from giftcard_customer where status=1 and endtime > '" . date('Y-m-d H:i:s') . "' order by gitfcard_id ASC limit {$offset}, {$limit}";
+        return DB::select($sql);
+    }
+    protected function saveDatas($data)
+    {
+        if (!$data) {
+            return false;
+        }
+        foreach ($data as $item) {
+            $this->saveGiftCard($item);
+        }
+    }
+
+    protected function saveGiftCard($item)
+    {
+        GiftCards::addGiftCard(
+            $item->customer_id,
+            $item->giftcard_amount,
+            0,
+            $item->endtime,
+            'activity_26_06_03',
+            '手动迁移'
+        );
+    }
+
+
+    /**
+     * Initialize custom logger with specified file
+     *
+     * @param string $logFile
+     */
+    protected function initCustomLogger(string $logFile)
+    {
+        $this->customLogger = new Logger('gift-card-import');
+        $this->customLogger->pushHandler(new StreamHandler($logFile, Logger::INFO));
+    }
+
+    /**
+     * Log info message
+     *
+     * @param string $message
+     */
+    protected function logInfo(string $message)
+    {
+        if ($this->customLogger) {
+            $this->customLogger->info($message);
+        } else {
+            Log::info($message);
+        }
+    }
+
+    /**
+     * Log error message
+     *
+     * @param string $message
+     */
+    protected function logError(string $message)
+    {
+        if ($this->customLogger) {
+            $this->customLogger->error($message);
+        } else {
+            Log::error($message);
+        }
+    }
+}

+ 21 - 1
packages/Longyi/Gift/src/Http/Controllers/Shop/GiftController.php

@@ -15,7 +15,8 @@ use Longyi\Gift\Http\Resources\CustomCartResource;
 class GiftController extends Controller
 {
     public function __construct(
-        protected GiftCardsRepository $giftCardRepository
+        protected GiftCardsRepository $giftCardRepository,
+        protected GiftCards $giftCardsModel
     ) {
     }
 
@@ -24,6 +25,25 @@ class GiftController extends Controller
         echo 111;exit;
         return view('giftcard::shop.index');
     }
+
+    public function lists(): JsonResponse
+    {
+        $gifts = $this->giftCardsModel->giftcards();
+        return response()->json([
+            'success' => true,
+            'data' => $gifts,
+        ]);
+    }
+
+    public function add($request): JsonResponse
+    {
+        $id = $request->input('id');
+        $success = $this->giftCardsModel->add($id);
+        return response()->json([
+            'success' => $success,
+            'message' => $success ? 'Gift card added successfully' : 'Failed to add gift card',
+        ]);
+    }
     /**
      * Get customer's gift cards list
      */

+ 96 - 1
packages/Longyi/Gift/src/Models/GiftCards.php

@@ -105,18 +105,49 @@ class GiftCards extends Model implements GiftCardsContract
                 throw new \Exception('gift num is not enough');
             }
         }
+        $expirationDate = self::calculateExpirationDate($expirationdate);
         static::create([
             'giftcard_number' => self::generateGiftCardNumber(),
             'giftcard_amount' => $giftcardAmount,
             'used_giftcard_amount' => 0,
             'remaining_giftcard_amount' => $giftcardAmount,
             'customer_id' => $customerId,
-            'expirationdate' => now()->addDays($expirationdate),
+            'expirationdate' => $expirationDate,
             'giftcard_status' => 1,
             'channel' => $channel,
             'notes' => $notes
         ]);
     }
+    /**
+     * Calculate expiration date from various input types.
+     *
+     * @param  mixed  $expirationdate  Days (int), date string, or Carbon instance
+     * @return \Carbon\Carbon  Calculated expiration date
+     * @throws \Exception If the input type is invalid
+     */
+    protected static function calculateExpirationDate($expirationdate): Carbon
+    {
+        if ($expirationdate instanceof Carbon) {
+            return $expirationdate;
+        }
+
+        if (is_string($expirationdate)) {
+            try {
+                return Carbon::parse($expirationdate);
+            } catch (\Exception $e) {
+                throw new \Exception("Invalid date format: {$expirationdate}. Use Y-m-d format.");
+            }
+        }
+
+        if (is_int($expirationdate) || is_float($expirationdate)) {
+            if ($expirationdate <= 0) {
+                throw new \Exception('Expiration days must be greater than 0');
+            }
+            return now()->addDays((int) $expirationdate);
+        }
+
+        throw new \Exception('Invalid expiration date type. Must be integer (days), string (Y-m-d), or Carbon instance.');
+    }
     public static function generateGiftCardNumber()
     {
         do {
@@ -132,4 +163,68 @@ class GiftCards extends Model implements GiftCardsContract
 
         return $code;
     }
+
+    public function giftcards()
+    {
+        return [
+            1 => [
+                'id' => 1,
+                'name' => 'Gift Card 1',
+                'amount' => 20.00,
+                'points' => 20,
+                'num' => 0,
+                'expirationdate' => 30,
+                'channel' => 'activity_26_04_21',
+                'notes' => '拉新活动添加'
+            ],
+            2 => [
+                'id' => 2,
+                'name' => 'Gift Card 2',
+                'amount' => 30.00,
+                'points' => 30,
+                'num' => 0,
+                'expirationdate' => 30,
+                'channel' => 'activity_26_04_21',
+                'notes' => '拉新活动添加'
+            ],
+            3 => [
+                'id' => 3,
+                'name' => 'Gift Card 3',
+                'amount' => 40.00,
+                'points' => 40,
+                'num' => 0,
+                'expirationdate' => 30,
+                'channel' => 'activity_26_04_21',
+                'notes' => '拉新活动添加'
+            ],
+            4 => [
+                'id' => 4,
+                'name' => 'Gift Card 4',
+                'amount' => 50.00,
+                'points' => 50,
+                'num' => 0,
+                'expirationdate' => 30,
+                'channel' => 'activity_26_04_21',
+                'notes' => '拉新活动添加'
+            ],
+        ];
+    }
+
+    public function add($id)
+    {
+        $gifts = $this->giftcards();
+        $giftInfo = $gifts[$id] ?? null;
+        if (!$giftInfo) {
+            return false;
+        }
+        try {
+            DB::beginTransaction();
+            self::addGiftCard($id, $giftInfo['amount'], $giftInfo['num'], $giftInfo['expirationdate'], $giftInfo['channel'], $giftInfo['notes']);
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            throw $e;
+        }
+        return true;
+    }
 }