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

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