source: branches/version-2_5-dev/data/class/helper/SC_Helper_Purchase.php @ 19872

Revision 19872, 20.6 KB checked in by nanasess, 13 years ago (diff)

#843(複数配送先の指定)

  • 非会員購入に対応
Line 
1<?php
2/*
3 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2010 LOCKON CO.,LTD. All Rights Reserved.
6 *
7 * http://www.lockon.co.jp/
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 */
23
24/**
25 * 商品購入関連のヘルパークラス.
26 *
27 * TODO 購入時強制会員登録機能(#521)の実装を検討
28 * TODO dtb_customer.buy_times, dtb_customer.buy_total の更新
29 *
30 * @package Helper
31 * @author Kentaro Ohkouchi
32 * @version $Id$
33 */
34class SC_Helper_Purchase {
35
36    /**
37     * 受注を完了する.
38     *
39     * 下記のフローで受注を完了する.
40     *
41     * 1. トランザクションを開始する
42     * 2. カートの内容を検証する.
43     * 3. 受注一時テーブルから受注データを読み込む
44     * 4. ユーザーがログインしている場合はその他の発送先へ登録する
45     * 5. 受注データを受注テーブルへ登録する
46     * 6. トランザクションをコミットする
47     *
48     * 実行中に, 何らかのエラーが発生した場合, 処理を中止しエラーページへ遷移する
49     *
50     * 決済モジュールを使用する場合は受注ステータスを「決済処理中」に設定し,
51     * 決済完了後「新規受付」に変更すること
52     *
53     * @param integer $orderStatus 受注処理を完了する際に設定する受注ステータス
54     * @return void
55     */
56    function completeOrder($orderStatus = ORDER_NEW) {
57        $objQuery =& SC_Query::getSingletonInstance();
58        $objSiteSession = new SC_SiteSession();
59        $objCartSession = new SC_CartSession();
60        $objCustomer = new SC_Customer();
61        $customerId = $objCustomer->getValue('customer_id');
62
63        $objQuery->begin();
64        SC_Utils_Ex::sfIsPrePage($objSiteSession);
65
66        $uniqId = $objSiteSession->getUniqId();
67        $this->verifyChangeCart($uniqId, $objCartSession);
68
69        $orderTemp = $this->getOrderTemp($uniqId);
70
71        $orderTemp['status'] = $orderStatus;
72        $orderId = $this->registerOrder($orderTemp, $objCartSession,
73                                        $objCartSession->getKey());
74        $shippingTemp =& $this->getShippingTemp();
75        if (count($shippingTemp) > 1) {
76            foreach ($shippingTemp as $shippingId => $val) {
77                $this->registerShipmentItem($orderId, $shippingId,
78                                            $val['shipment_item']);
79            }
80        }
81
82        $this->registerShipping($orderId, $shippingTemp);
83        $objQuery->commit();
84        $this->unsetShippingTemp();
85        $objCustomer->updateSession();
86    }
87
88    /**
89     * カートに変化が無いか検証する.
90     *
91     * ユニークIDとセッションのユニークIDを比較し, 異なる場合は
92     * エラー画面を表示する.
93     *
94     * カートが空の場合, 購入ボタン押下後にカートが変更された場合は
95     * カート画面へ遷移する.
96     *
97     * @param string $uniqId ユニークID
98     * @param SC_CartSession $objCartSession
99     * @return void
100     */
101    function verifyChangeCart($uniqId, &$objCartSession) {
102        $cartkeys = $objCartSession->getKeys();
103
104        foreach ($cartKeys as $cartKey) {
105            // 初回のみカートの内容を保存
106            $objCartSess->saveCurrentCart($uniqid, $cartKey);
107            /*
108             * POSTのユニークIDとセッションのユニークIDを比較
109             *(ユニークIDがPOSTされていない場合はスルー)
110             */
111            if(!SC_SiteSession::checkUniqId()) {
112                // エラーページの表示
113                // XXX $objSiteSess インスタンスは未使用?
114                SC_Utils_Ex::sfDispSiteError(CANCEL_PURCHASE, $objSiteSess);
115            }
116
117            // カート内が空でないか || 購入ボタンを押してから変化がないか
118            $quantity = $objCartSess->getTotalQuantity($cartKey);
119            if($objCartSess->checkChangeCart($cartKey) || !($quantity > 0)) {
120                // カート情報表示に強制移動する
121                if (Net_UserAgent_Mobile::isMobile()) {
122                    header("Location: ". MOBILE_CART_URL_PATH
123                           . "?" . session_name() . "=" . session_id());
124                } else {
125                    header("Location: ".CART_URL_PATH);
126                }
127                exit;
128            }
129        }
130    }
131
132    /**
133     * 受注一時情報を取得する.
134     *
135     * @param integer $uniqId 受注一時情報ID
136     * @return array 受注一時情報の配列
137     */
138    function getOrderTemp($uniqId) {
139        $objQuery =& SC_Query::getSingletonInstance();
140        return $objQuery->getRow("*", "dtb_order_temp", "order_temp_id = ?",
141                                 array($uniqId));
142    }
143
144    /**
145     * 受注一時情報を保存する.
146     *
147     * 既存のデータが存在しない場合は新規保存. 存在する場合は更新する.
148     * 既存のデータが存在せず, ユーザーがログインしている場合は,
149     * 会員情報をコピーする.
150     *
151     * @param integer $uniqId 受注一時情報ID
152     * @param array $params 登録する受注情報の配列
153     * @param SC_Customer $objCustomer SC_Customer インスタンス
154     * @return array void
155     */
156    function saveOrderTemp($uniqId, $params, &$objCustomer) {
157        if (SC_Utils_Ex::isBlank($uniqId)) {
158            return;
159        }
160
161        $objQuery =& SC_Query::getSingletonInstance();
162        // 存在するカラムのみを対象とする
163        $cols = $objQuery->listTableFields('dtb_order_temp');
164        foreach ($params as $key => $val) {
165            if (in_array($key, $cols)) {
166                $sqlval[$key] = $val;
167            }
168        }
169
170        $sqlval['session'] = serialize($_SESSION);
171        $exists = $this->getOrderTemp($uniqId);
172        if (SC_Utils_Ex::isBlank($exists)) {
173            $this->copyFromCustomer($sqlval, $objCustomer);
174            $sqlval['order_temp_id'] = $uniqId;
175            $sqlval['create_date'] = "now()";
176            $objQuery->insert("dtb_order_temp", $sqlval);
177        } else {
178            $objQuery->update("dtb_order_temp", $sqlval, 'order_temp_id = ?',
179                              array($uniqId));
180        }
181    }
182
183    /**
184     * セッションの配送情報を取得する.
185     */
186    function getShippingTemp() {
187        return $_SESSION['shipping'];
188    }
189
190    /**
191     * 配送商品を設定する.
192     */
193    function setShipmentItemTemp($otherDelivId, $productClassId, $quantity) {
194        $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['shipping_id'] = $otherDelivId;
195        $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['product_class_id'] = $productClassId;
196        $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['quantity'] += $quantity;
197
198        $objProduct = new SC_Product();
199        if (empty($_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['productsClass'])) {
200            $product = $objProduct->getDetailAndProductsClass($productClassId);
201            $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['productsClass'] = $product;
202        }
203        $incTax = SC_Helper_DB_Ex::sfCalcIncTax($_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['productsClass']['price02']);
204        $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['total_inctax'] = $incTax * $_SESSION['shipping'][$otherDelivId]['shipment_item'][$productClassId]['quantity'];
205    }
206
207    /**
208     * 複数配送指定の購入かどうか.
209     *
210     * @return boolean 複数配送指定の購入の場合 true
211     */
212    function isMultiple() {
213        return (count($this->getShippingTemp()) > 1);
214    }
215
216    /**
217     * 配送情報をセッションに保存する.
218     */
219    function saveShippingTemp(&$src, $otherDelivId = 0) {
220        if (empty($_SESSION['shipping'][$otherDelivId])) {
221            $_SESSION['shipping'][$otherDelivId] = $src;
222        } else {
223            $_SESSION['shipping'][$otherDelivId] = array_merge($_SESSION['shipping'][$otherDelivId], $src);
224        }
225    }
226
227    /**
228     * セッションの配送情報を破棄する.
229     */
230    function unsetShippingTemp() {
231        unset($_SESSION['shipping']);
232    }
233
234    /**
235     * 会員情報を受注情報にコピーする.
236     *
237     * ユーザーがログインしていない場合は何もしない.
238     * 会員情報を $dest の order_* へコピーする.
239     * customer_id は強制的にコピーされる.
240     *
241     * @param array $dest コピー先の配列
242     * @param SC_Customer $objCustomer SC_Customer インスタンス
243     * @param string $prefix コピー先の接頭辞. デフォルト order
244     * @param array $keys コピー対象のキー
245     * @return void
246     */
247    function copyFromCustomer(&$dest, &$objCustomer, $prefix = 'order',
248                              $keys = array('name01', 'name02', 'kana01', 'kana02',
249                                            'sex', 'zip01', 'zip02', 'pref',
250                                            'addr01', 'addr02',
251                                            'tel01', 'tel02', 'tel03', 'job',
252                                            'birth', 'email')) {
253        if ($objCustomer->isLoginSuccess(true)) {
254
255            foreach ($keys as $key) {
256                if (in_array($key, $keys)) {
257                    $dest[$prefix . '_' . $key] = $objCustomer->getValue($key);
258                }
259            }
260
261            if (Net_UserAgent_Mobile::isMobile()
262                && in_array('email', $keys)) {
263                $email_mobile = $objCustomer->getValue('email_mobile');
264                if (empty($email_mobile)) {
265                    $dest[$prefix . '_email'] = $objCustomer->getValue('email');
266                } else {
267                    $dest[$prefix . '_email'] = $email_mobile;
268                }
269            }
270
271            $dest['customer_id'] = $objCustomer->getValue('customer_id');
272            $dest['update_date'] = 'Now()';
273        }
274    }
275
276    /**
277     * 受注情報を配送情報にコピーする.
278     *
279     * 受注情報($src)を $dest の order_* へコピーする.
280     *
281     * @param array $dest コピー先の配列
282     * @param array $src コピー元の配列
283     * @param array $keys コピー対象のキー
284     * @param string $prefix コピー先の接頭辞. デフォルト shipping
285     * @param string $src_prefix コピー元の接頭辞. デフォルト order
286     * @return void
287     */
288    function copyFromOrder(&$dest, $src,
289                           $prefix = 'shipping', $src_prefix = 'order',
290                           $keys = array('name01', 'name02', 'kana01', 'kana02',
291                                         'sex', 'zip01', 'zip02', 'pref',
292                                         'addr01', 'addr02',
293                                         'tel01', 'tel02', 'tel03')) {
294        foreach ($keys as $key) {
295            if (in_array($key, $keys)) {
296                $dest[$prefix . '_' . $key] = $src[$src_prefix . '_' . $key];
297            }
298        }
299    }
300
301    /**
302     * 購入金額に応じた支払方法を取得する.
303     *
304     * @param integer $total 購入金額
305     * @param array $productClassIds 購入する商品規格IDの配列
306     * @return array 購入金額に応じた支払方法の配列
307     */
308    function getPayment($total, $productClassIds) {
309        // 有効な支払方法を取得
310        $objProduct = new SC_Product();
311        $paymentIds = $objProduct->getEnablePaymentIds($productClassIds);
312
313        $objQuery =& SC_Query::getSingletonInstance();
314
315        // 削除されていない支払方法を取得
316        $where = 'del_flg = 0 AND payment_id IN (' . implode(', ', array_pad(array(), count($paymentIds), '?')) . ')';
317        $objQuery->setOrder("rank DESC");
318        $payments = $objQuery->select("payment_id, payment_method, rule, upper_rule, note, payment_image", "dtb_payment", $where, $paymentIds);
319
320        foreach ($payments as $data) {
321            // 下限と上限が設定されている
322            if (strlen($data['rule']) != 0 && strlen($data['upper_rule']) != 0) {
323                if ($data['rule'] <= $total_inctax && $data['upper_rule'] >= $total_inctax) {
324                    $arrPayment[] = $data;
325                }
326            }
327            // 下限のみ設定されている
328            elseif (strlen($data['rule']) != 0) {
329                if($data['rule'] <= $total_inctax) {
330                    $arrPayment[] = $data;
331                }
332            }
333            // 上限のみ設定されている
334            elseif (strlen($data['upper_rule']) != 0) {
335                if($data['upper_rule'] >= $total_inctax) {
336                    $arrPayment[] = $data;
337                }
338            }
339            // いずれも設定なし
340            else {
341                $arrPayment[] = $data;
342            }
343          }
344        return $arrPayment;
345    }
346
347    /**
348     * 商品規格IDの配列からお届け予定日の配列を取得する.
349     *
350     * @param array $productClassIds 商品規格IDの配列
351     */
352    function getDelivDate($productClassIds) {
353        // TODO
354    }
355
356    /**
357     * 商品種別ID からお届け時間の配列を取得する.
358     */
359    function getDelivTime($productTypeId) {
360        $objQuery =& SC_Query::getSingletonInstance();
361        $from = <<< __EOS__
362                 dtb_deliv T1
363            JOIN dtb_delivtime T2
364              ON T1.deliv_id = T2. deliv_id
365__EOS__;
366            $objQuery->setOrder("time_id");
367            $where = "deliv_id = ?";
368            $results = $objQuery->select("time_id, deliv_time", $from,
369                                         "product_type_id = ?", array($productTypeId));
370            $arrDelivTime = array();
371            foreach ($results as $val) {
372                $arrDelivTime[$val['time_id']] = $val['deliv_time'];
373            }
374            return $arrDelivTime;
375    }
376
377    /**
378     * 商品種別ID から配送業者ID を取得する.
379     */
380    function getDeliv($productTypeId) {
381        $objQuery =& SC_Query::getSingletonInstance();
382        return $objQuery->get("deliv_id", "dtb_deliv", "product_type_id = ?",
383                                 array($productTypeId));
384    }
385
386    /**
387     * 配送情報を登録する.
388     */
389    function registerShipping($orderId, $params) {
390        $objQuery =& SC_Query::getSingletonInstance();
391
392        $cols = $objQuery->listTableFields('dtb_shipping');
393
394        foreach ($params as $shipping_id => $shipping_val) {
395            // 存在するカラムのみ INSERT
396            foreach ($shipping_val as $key => $val) {
397                if (in_array($key, $cols)) {
398                    $sqlval[$key] = $val;
399                }
400            }
401
402            $sqlval['order_id'] = $orderId;
403            $sqlval['shipping_id'] = $shipping_id;
404            $sqlval['create_date'] = 'Now()';
405            $sqlval['update_date'] = 'Now()';
406            $objQuery->insert("dtb_shipping", $sqlval);
407        }
408    }
409
410    /**
411     * 配送商品を登録する.
412     */
413    function registerShipmentItem($orderId, $shippingId, $params) {
414        $objQuery =& SC_Query::getSingletonInstance();
415        $objProduct = new SC_Product();
416        foreach ($params as $productClassId => $val) {
417            $d = $objProduct->getDetailAndProductsClass($productClassId);
418            $sqlval['order_id'] = $orderId;
419            $sqlval['shipping_id'] = $shippingId;
420            $sqlval['product_class_id'] = $productClassId;
421            $sqlval['product_name'] = $d['name'];
422            $sqlval['product_code'] = $d['product_code'];
423            $sqlval['classcategory_name1'] = $d['classcategory_name1'];
424            $sqlval['classcategory_name2'] = $d['classcategory_name2'];
425            $sqlval['price'] = $d['price'];
426            $sqlval['quantity'] = $val['quantity'];
427            $objQuery->insert("dtb_shipment_item", $sqlval);
428        }
429    }
430
431    /**
432     * 受注情報を登録する.
433     *
434     * 引数の受注情報を受注テーブル及び受注詳細テーブルに登録する.
435     * 登録後, 受注一時テーブルに削除フラグを立て, カートの内容を削除する.
436     *
437     * TODO ダウンロード商品の場合の扱いを検討
438     *
439     * @param array $orderParams 登録する受注情報の配列
440     * @param SC_CartSession $objCartSession カート情報のインスタンス
441     * @param integer $cartKey 登録を行うカート情報のキー
442     * @param integer 受注ID
443     */
444    function registerOrder($orderParams, &$objCartSession, $cartKey) {
445        $objQuery =& SC_Query::getSingletonInstance();
446
447        // 別のお届け先を指定が無ければ, お届け先に登録住所をコピー
448        /* FIXME
449        if ($orderParams['deliv_check'] == "-1") {
450            $keys = array('name01', 'name02', 'kana01', 'kana02', 'pref', 'zip01',
451                          'zip02', 'addr01', 'addr02', 'tel01', 'tel02', 'tel03');
452            foreach ($keys as $key) {
453                $orderParams['deliv_' . $key] = $orderParams['order_' . $key];
454            }
455        }
456        */
457        // 不要な変数を unset
458        $unsets = array('mailmaga_flg', 'deliv_check', 'point_check', 'password',
459                        'reminder', 'reminder_answer', 'mail_flag', 'session');
460        foreach ($unsets as $unset) {
461            unset($orderParams[$unset]);
462        }
463
464        // ポイントは別登録
465        $addPoint = $orderParams['add_point'];
466        $usePoint = $orderParams['use_point'];
467        $orderParams['add_point'] = 0;
468        $orderParams['use_point'] = 0;
469
470        // 注文ステータスの指定が無い場合は新規受付
471        if(SC_Utils_Ex::isBlank($orderParams['status'])) {
472            $orderParams['status'] = ORDER_NEW;
473        }
474
475        $orderParams['create_date'] = 'Now()';
476        $orderParams['update_date'] = 'Now()';
477
478        $objQuery->insert("dtb_order", $orderParams);
479
480        // 受注.対応状況の更新
481        SC_Helper_DB_Ex::sfUpdateOrderStatus($orderParams['order_id'],
482                                             null, $addPoint, $usePoint);
483
484        // 詳細情報を取得
485        $cartItems = $objCartSession->getCartList($cartKey);
486
487        // 既に存在する詳細レコードを消しておく。
488        $objQuery->delete("dtb_order_detail", "order_id = ?",
489                          array($orderParams['order_id']));
490
491        $objProduct = new SC_Product();
492        foreach ($cartItems as $item) {
493            $p =& $item['productsClass'];
494            $detail['order_id'] = $orderParams['order_id'];
495            $detail['product_id'] = $p['product_id'];
496            $detail['product_class_id'] = $p['product_class_id'];
497            $detail['product_name'] = $p['name'];
498            $detail['product_code'] = $p['product_code'];
499            $detail['classcategory_name1'] = $p['classcategory_name1'];
500            $detail['classcategory_name2'] = $p['classcategory_name2'];
501            $detail['point_rate'] = $item['point_rate'];
502            $detail['price'] = $item['price'];
503            $detail['quantity'] = $item['quantity'];
504
505            // 在庫の減少処理
506            if (!$objProduct->reduceStock($p['product_class_id'], $item['quantity'])) {
507                $objQuery->rollback();
508                SC_Utils_Ex::sfDispSiteError(SOLD_OUT, "", true);
509            }
510            $objQuery->insert("dtb_order_detail", $detail);
511        }
512
513        $objQuery->update("dtb_order_temp", array('del_flg' => 1),
514                          "order_temp_id = ?",
515                          array(SC_SiteSession::getUniqId()));
516
517        $objCartSession->delAllProducts($cartKey);
518        SC_SiteSession::unsetUniqId();
519        return $orderParams['order_id'];
520    }
521
522    /**
523     * 受注完了メールを送信する.
524     *
525     * HTTP_USER_AGENT の種別により, 携帯電話の場合は携帯用の文面,
526     * PC の場合は PC 用の文面でメールを送信する.
527     *
528     * @param integer $orderId 受注ID
529     * @return void
530     */
531    function sendOrderMail($orderId) {
532        $mailHelper = new SC_Helper_Mail_Ex();
533        $mailHelper->sfSendOrderMail($orderId,
534                                     SC_MobileUserAgent::isMobile() ? 2 : 1);
535    }
536}
Note: See TracBrowser for help on using the repository browser.