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

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