PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.5.1
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.5.1
1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 trunk All 48 releases
fluent-cart / database / Seeder / OrderSeeder.php

OrderSeeder.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.5.1, at database/Seeder/OrderSeeder.php

283 lines 11.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCart\Database\Seeder;
4
5 use FluentCart\Api\StoreSettings;
6 use FluentCart\App\Helpers\CustomerHelper;
7 use FluentCart\App\Models\AppliedCoupon;
8 use FluentCart\App\Models\Coupon;
9 use FluentCart\App\Models\Customer;
10 use FluentCart\App\Models\Order;
11 use FluentCart\App\Models\OrderItem;
12 use FluentCart\App\Models\OrderTransaction;
13 use FluentCart\App\Models\Product;
14 use FluentCart\App\Services\DateTime\DateTime;
15 use FluentCart\Faker\Factory;
16 use FluentCart\Framework\Support\Arr;
17
18 class OrderSeeder
19 {
20 public static function seed($count, $assoc_args = [])
21 {
22 $db = \FluentCart\App\App::getInstance('db');
23
24 $faker = Factory::create();
25 $faker->addProvider(new \FluentCart\Database\Seeder\ProductNameProvide($faker));
26
27 $customerIds = Customer::query()->select('id')->orderBy('id', 'desc')->take($count / 2)->pluck('id');
28 $products = Product::with('variants')->take(100)->get()->toArray();
29 $orderCount = Order::query()->count();
30 $orderItems = [];
31 $orderTransactions = [];
32 $coupons = Coupon::query()->where('status', 'active')->get()->toArray();
33
34 if (defined('WP_CLI') && WP_CLI) {
35 $progress = \WP_CLI\Utils\make_progress_bar('%CSeeding Orders', $count);
36 }
37
38 $storeSettings = new StoreSettings();
39 for ($i = 0; $i < $count; $i++) {
40 $totalPrice = 0;
41 $discountTotal = 0;
42 $tempOrderItems = [];
43 $createdDate = $faker->dateTimeBetween('-450 days', 'now')->format('Y-m-d H:i:s');
44 $createdDateGmt = DateTime::anyTimeToGmt($createdDate);
45
46 $fulfilmentType = $faker->randomElement(['physical', 'digital']);
47
48 // Filter only products that have at least one variant with the selected fulfilment type
49 $filteredProducts = array_filter($products, function ($product) use ($fulfilmentType) {
50 return !empty(array_filter($product['variants'], function ($variant) use ($fulfilmentType) {
51 return isset($variant['fulfillment_type']) && $variant['fulfillment_type'] === $fulfilmentType;
52 }));
53 });
54
55 // If no product matches the type, fallback to all products
56 $availableProducts = count($filteredProducts) > 0 ? array_values($filteredProducts) : $products;
57
58 // Randomize
59 $randomizeProduct = count($availableProducts) < 2
60 ? $availableProducts
61 : array_map(function ($index) use ($availableProducts) {
62 return $availableProducts[$index];
63 }, (array)array_rand($availableProducts, min(wp_rand(2, 5), count($availableProducts))));
64
65 // Randomly pick a coupon
66 $appliedCoupon = $faker->randomElement($coupons ?? []);
67 $couponType = Arr::get($appliedCoupon, 'type');
68 $couponAmount = (int)Arr::get($appliedCoupon, 'amount', 0);
69
70 foreach ($randomizeProduct as $key => $productIndex) {
71 $product = $products[$key];
72 $variant = $faker->randomElement($product['variants']);
73 $quantity = wp_rand(1, 3);
74 $itemPrice = $variant['item_price'] ?? 0;
75 $subTotalPrice = $quantity * $itemPrice;
76
77 $lineDiscount = 0;
78 if ($couponType === 'percentage' && $couponAmount > 0) {
79 $lineDiscount = intval(($couponAmount / 100) * $subTotalPrice);
80 }
81
82 $discountTotal += $lineDiscount;
83 $totalPrice += $subTotalPrice;
84
85 $tempOrderItems[] = [
86 'post_title' => $product['post_title'],
87 'title' => $variant['variation_title'] ?? '',
88 'fulfillment_type' => $variant['fulfillment_type'],
89 'payment_type' => $variant['payment_type'],
90 'quantity' => $quantity,
91 'unit_price' => $itemPrice,
92 'line_total' => $subTotalPrice - $lineDiscount,
93 'subtotal' => $subTotalPrice,
94 'post_id' => $product['ID'],
95 'object_id' => $variant['id'],
96 'discount_total' => $lineDiscount,
97 'cart_index' => $i + 1,
98 'created_at' => $createdDateGmt,
99 ];
100 }
101
102 $paymentMethod = $faker->randomElement(['offline_payment', 'online_payment']);
103 $paymentMethodTitle = $faker->randomElement(['Cash on Delivery', 'PayPal', 'Stripe']);
104 $customerId = $faker->randomElement($customerIds);
105
106 $paymentStatus = $faker->randomElement([
107 'pending',
108 'paid',
109 'partially_paid',
110 'refunded',
111 'partially_refunded',
112 'failed',
113 ]);
114
115 switch ($paymentStatus) {
116 case 'paid':
117 if ($fulfilmentType === 'digital') {
118 $status = 'completed';
119 } else {
120 $status = $faker->randomElement(['completed', 'processing']);
121 }
122 break;
123
124 case 'partially_paid':
125 $status = 'processing';
126 break;
127
128 case 'partially_refunded':
129 $status = 'completed';
130 break;
131
132 case 'refunded':
133 $status = 'canceled';
134 break;
135
136 default:
137 // For pending, failed, authorized
138 $status = $faker->randomElement(['on-hold', 'canceled', 'failed']);
139 break;
140 }
141
142 $refundedAt = $faker->dateTimeBetween($createdDate, 'now')->format('Y-m-d H:i:s');
143 $currency = 'USD';
144 $shippingTax = 0;
145 $taxTotal = 0;
146 $orderDiscountTotal = 0;
147 $totalRefund = 0;
148 $totalPaid = 0;
149 $completedAt = null;
150 $totalAmount = $totalPrice - $shippingTax - $taxTotal - $orderDiscountTotal - $discountTotal;
151 if ($status === 'completed') {
152 $endDate = (new DateTime($createdDateGmt))->modify('+3 days')->format('Y-m-d H:i:s');
153 $completedAt = $faker->dateTimeBetween($createdDateGmt, $endDate)->format('Y-m-d H:i:s');
154 }
155
156 if ($paymentStatus === 'paid') {
157 $totalPaid = $totalAmount;
158 } elseif ($paymentStatus === 'refunded') {
159 $totalPaid = $totalAmount;
160 $totalRefund = $totalPaid;
161 } elseif ($paymentStatus === 'partially_refunded') {
162 $totalPaid = $totalAmount;
163 $refundPercentage = wp_rand(20, 30) / 100;
164 $totalRefund = round($totalPaid * $refundPercentage, 2);
165 } elseif ($paymentStatus === 'partially_paid') {
166 $paymentPercentage = wp_rand(50, 60) / 100;
167 $totalPaid = round($totalAmount * $paymentPercentage, 2);
168 $totalRefund = 0;
169 }
170
171 $orderData = [
172 'parent_id' => 0,
173 'invoice_no' => $storeSettings->getInvoicePrefix() . ($orderCount + $i + 1) . $storeSettings->getInvoiceSuffix(),
174 'receipt_number' => ($orderCount + $i + 1),
175 'customer_id' => $customerId,
176 'payment_method' => $paymentMethod,
177 'payment_method_title' => $paymentMethodTitle,
178 'payment_status' => $paymentStatus,
179 'currency' => $currency,
180 'subtotal' => $totalPrice,
181 'shipping_tax' => $shippingTax,
182 'fulfillment_type' => $fulfilmentType,
183 'tax_total' => $taxTotal,
184 'manual_discount_total' => $orderDiscountTotal,
185 'coupon_discount_total' => $discountTotal,
186 'total_amount' => $totalPrice - $shippingTax - $taxTotal - $orderDiscountTotal - $discountTotal,
187 'total_paid' => $totalPaid,
188 'status' => $status,
189 'created_at' => $createdDateGmt,
190 'total_refund' => $totalRefund,
191 'refunded_at' => $refundedAt,
192 'completed_at' => $completedAt,
193 ];
194
195 $order = Order::query()->create($orderData);
196
197 switch ($paymentStatus) {
198 case 'paid':
199 case 'partially_paid':
200 case 'authorized':
201 $transactionStatus = 'completed';
202 break;
203
204 case 'refunded':
205 $transactionStatus = 'refunded';
206 break;
207
208 case 'partially_refunded':
209 $transactionStatus = 'partially_refunded';
210 break;
211
212 case 'pending':
213 $transactionStatus = 'pending';
214 break;
215
216 case 'failed':
217 $transactionStatus = 'failed';
218 break;
219
220 default:
221 $transactionStatus = 'pending';
222 break;
223 }
224
225
226 $orderTransactions[] = [
227 'order_id' => $order->id,
228 'order_type' => $order->type,
229 'payment_method' => $paymentMethod,
230 'payment_mode' => 'test',
231 'status' => $transactionStatus,
232 'currency' => $currency,
233 'total' => $totalPrice,
234 'created_at' => $createdDateGmt,
235 ];
236
237 $appliedCouponData = [];
238 if (!empty($appliedCoupon) && $discountTotal > 0) {
239 $appliedCouponData[] = [
240 'order_id' => $order->id,
241 'coupon_id' => $appliedCoupon['id'],
242 'customer_id' => $customerId,
243 'code' => $appliedCoupon['code'],
244 'amount' => $discountTotal,
245 'created_at' => $createdDateGmt,
246 ];
247 }
248
249
250 foreach ($tempOrderItems as $index => $item) {
251 $tempOrderItems[$index]['order_id'] = $order->id;
252 }
253
254 $orderItems = array_merge($orderItems, $tempOrderItems);
255
256 if (defined('WP_CLI') && WP_CLI) {
257 if ($i !== $count - 1) {
258 $progress->tick();
259 }
260 } else {
261 echo wp_kses_post( sprintf(
262 /* translators: %d: order ID */
263 __('Inserting Order %1$s<br>', 'fluent-cart'),
264 esc_html($i + 1)
265 ) );
266 }
267 }
268
269 OrderTransaction::query()->insert($orderTransactions);
270 OrderItem::query()->insert($orderItems);
271 AppliedCoupon::query()->insert($appliedCouponData);
272
273 (new CustomerHelper)->calculateCustomerStats();
274
275 if (defined('WP_CLI') && WP_CLI) {
276 $progress->tick();
277 $progress->finish();
278 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
279 echo \WP_CLI::colorize('%n');
280 }
281 }
282 }
283