当前位置: 首页>>代码示例>>PHP>>正文


PHP StockAvailable::synchronize方法代码示例

本文整理汇总了PHP中StockAvailable::synchronize方法的典型用法代码示例。如果您正苦于以下问题:PHP StockAvailable::synchronize方法的具体用法?PHP StockAvailable::synchronize怎么用?PHP StockAvailable::synchronize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在StockAvailable的用法示例。


在下文中一共展示了StockAvailable::synchronize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: processGenerate

 public function processGenerate()
 {
     if (!is_array(Tools::getValue('options'))) {
         $this->errors[] = Tools::displayError('Please select at least one attribute.');
     } else {
         $tab = array_values(Tools::getValue('options'));
         if (count($tab) && Validate::isLoadedObject($this->product)) {
             AdminAttributeGeneratorController::setAttributesImpacts($this->product->id, $tab);
             $this->combinations = array_values(AdminAttributeGeneratorController::createCombinations($tab));
             $values = array_values(array_map(array($this, 'addAttribute'), $this->combinations));
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 foreach ($attributes as $attribute) {
                     StockAvailable::removeProductFromStockAvailable($this->product->id, $attribute['id_product_attribute'], Context::getContext()->shop);
                 }
             }
             SpecificPriceRule::disableAnyApplication();
             $this->product->deleteProductAttributes();
             $this->product->generateMultipleCombinations($values, $this->combinations);
             // @since 1.5.0
             if ($this->product->depends_on_stock == 0) {
                 $attributes = Product::getProductAttributesIds($this->product->id, true);
                 $quantity = str_replace(',', '.', Tools::getValue('quantity'));
                 foreach ($attributes as $attribute) {
                     StockAvailable::setQuantity($this->product->id, $attribute['id_product_attribute'], $quantity);
                 }
             } else {
                 StockAvailable::synchronize($this->product->id);
             }
             SpecificPriceRule::enableAnyApplication();
             SpecificPriceRule::applyAllRules(array((int) $this->product->id));
             Tools::redirectAdmin($this->context->link->getAdminLink('AdminProducts') . '&id_product=' . (int) Tools::getValue('id_product') . '&updateproduct&key_tab=Combinations&conf=4');
         } else {
             $this->errors[] = Tools::displayError('Unable to initialize these parameters. A combination is missing or an object cannot be loaded.');
         }
     }
 }
开发者ID:Oldwo1f,项目名称:yakaboutique,代码行数:38,代码来源:AdminAttributeGeneratorController.php

示例2: attributeImportOne


//.........这里部分代码省略.........
        $product->checkDefaultAttributes();
        if (!$product->cache_default_attribute && !$validateOnly) {
            Product::updateDefaultAttribute($product->id);
        }
        if ($id_product_attribute) {
            if (!$validateOnly) {
                // now adds the attributes in the attribute_combination table
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')', false);
                }
            }
            // set advanced stock managment
            if (isset($info['advanced_stock_management'])) {
                if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!$validateOnly) {
                    $product->setAdvancedStockManagement($info['advanced_stock_management']);
                }
                // automaticly disable depends on stock, if a_s_m set to disabled
                if (!$validateOnly && StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                    StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                }
            }
            // Check if warehouse exists
            if (isset($info['warehouse']) && $info['warehouse']) {
                if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse is not set on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } else {
                    if (Warehouse::exists($info['warehouse'])) {
                        $warehouse_location_entity = new WarehouseProductLocation();
                        $warehouse_location_entity->id_product = $product->id;
                        $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                        $warehouse_location_entity->id_warehouse = $info['warehouse'];
                        if (!$validateOnly) {
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        }
                    } else {
                        $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                    }
                }
            }
            // stock available
            if (isset($info['depends_on_stock'])) {
                if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                    $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Notifications.Error'), $product->name[$default_language]);
                } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                } elseif (!$validateOnly) {
                    StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                }
                // This code allows us to set qty and disable depends on stock
                if (isset($info['quantity']) && (int) $info['quantity']) {
                    // if depends on stock and quantity, add quantity to stock
                    if ($info['depends_on_stock'] == 1) {
                        $stock_manager = StockManagerFactory::getManager();
                        $price = str_replace(',', '.', $info['wholesale_price']);
                        if ($price == 0) {
                            $price = 1.0E-6;
                        }
                        $price = round(floatval($price), 6);
                        $warehouse = new Warehouse($info['warehouse']);
                        if (!$validateOnly && $stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) {
                            StockAvailable::synchronize((int) $product->id);
                        }
                    } elseif (!$validateOnly) {
                        if ($shop_is_feature_active) {
                            foreach ($id_shop_list as $shop) {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                            }
                        } else {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                        }
                    }
                }
            } elseif (!$validateOnly) {
                // if not depends_on_stock set, use normal qty
                if ($shop_is_feature_active) {
                    foreach ($id_shop_list as $shop) {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                    }
                } else {
                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                }
            }
        }
    }
开发者ID:M03G,项目名称:PrestaShop,代码行数:101,代码来源:AdminImportController.php

示例3: postProcessUpdateReceipt

 /**
  * Helper function for AdminSupplyOrdersController::postProcess()
  *
  * @see AdminSupplyOrdersController::postProcess()
  */
 protected function postProcessUpdateReceipt()
 {
     // gets all box selected
     $rows = Tools::getValue('supply_order_detailBox');
     if (!$rows) {
         $this->errors[] = Tools::displayError('You did not select any products to update.');
         return;
     }
     // final array with id_supply_order_detail and value to update
     $to_update = array();
     // gets quantity for each id_order_detail
     foreach ($rows as $row) {
         if (Tools::getValue('quantity_received_today_' . $row)) {
             $to_update[$row] = (int) Tools::getValue('quantity_received_today_' . $row);
         }
     }
     // checks if there is something to update
     if (!count($to_update)) {
         $this->errors[] = Tools::displayError('You did not select any products to update.');
         return;
     }
     $supply_order = new SupplyOrder((int) Tools::getValue('id_supply_order'));
     foreach ($to_update as $id_supply_order_detail => $quantity) {
         $supply_order_detail = new SupplyOrderDetail($id_supply_order_detail);
         if (Validate::isLoadedObject($supply_order_detail) && Validate::isLoadedObject($supply_order)) {
             // checks if quantity is valid
             // It's possible to receive more quantity than expected in case of a shipping error from the supplier
             if (!Validate::isInt($quantity) || $quantity <= 0) {
                 $this->errors[] = sprintf(Tools::displayError('Quantity (%d) for product #%d is not valid'), (int) $quantity, (int) $id_supply_order_detail);
             } else {
                 // creates the history
                 $supplier_receipt_history = new SupplyOrderReceiptHistory();
                 $supplier_receipt_history->id_supply_order_detail = (int) $id_supply_order_detail;
                 $supplier_receipt_history->id_employee = (int) $this->context->employee->id;
                 $supplier_receipt_history->employee_firstname = pSQL($this->context->employee->firstname);
                 $supplier_receipt_history->employee_lastname = pSQL($this->context->employee->lastname);
                 $supplier_receipt_history->id_supply_order_state = (int) $supply_order->id_supply_order_state;
                 $supplier_receipt_history->quantity = (int) $quantity;
                 // updates quantity received
                 $supply_order_detail->quantity_received += (int) $quantity;
                 // if current state is "Pending receipt", then we sets it to "Order received in part"
                 if (3 == $supply_order->id_supply_order_state) {
                     $supply_order->id_supply_order_state = 4;
                 }
                 // Adds to stock
                 $warehouse = new Warehouse($supply_order->id_warehouse);
                 if (!Validate::isLoadedObject($warehouse)) {
                     $this->errors[] = Tools::displayError('The warehouse could not be loaded.');
                     return;
                 }
                 $price = $supply_order_detail->unit_price_te;
                 // converts the unit price to the warehouse currency if needed
                 if ($supply_order->id_currency != $warehouse->id_currency) {
                     // first, converts the price to the default currency
                     $price_converted_to_default_currency = Tools::convertPrice($supply_order_detail->unit_price_te, $supply_order->id_currency, false);
                     // then, converts the newly calculated pri-ce from the default currency to the needed currency
                     $price = Tools::ps_round(Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true), 6);
                 }
                 $manager = StockManagerFactory::getManager();
                 $res = $manager->addProduct($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse, (int) $quantity, Configuration::get('PS_STOCK_MVT_SUPPLY_ORDER'), $price, true, $supply_order->id);
                 $location = Warehouse::getProductLocation($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse->id);
                 $res = Warehouse::setProductlocation($supply_order_detail->id_product, $supply_order_detail->id_product_attribute, $warehouse->id, $location ? $location : '');
                 if ($res) {
                     $supplier_receipt_history->add();
                     $supply_order_detail->save();
                     StockAvailable::synchronize($supply_order_detail->id_product);
                 } else {
                     $this->errors[] = Tools::displayError('Something went wrong when setting warehouse on product record');
                 }
             }
         }
     }
     $supply_order->id_supply_order_state = $supply_order->id_supply_order_state == 4 && $supply_order->getAllPendingQuantity() > 0 ? 4 : 5;
     $supply_order->save();
     if (!count($this->errors)) {
         // display confirm message
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         $redirect = self::$currentIndex . '&token=' . $token;
         $this->redirect_after = $redirect . '&conf=4';
     }
 }
开发者ID:zangles,项目名称:lennyba,代码行数:86,代码来源:AdminSupplyOrdersController.php

示例4: resetStockAvailable

 public function resetStockAvailable()
 {
     $products = WarehouseProductLocation::getProducts((int) $this->id);
     foreach ($products as $product) {
         StockAvailable::synchronize((int) $product['id_product']);
     }
 }
开发者ID:dev-lav,项目名称:htdocs,代码行数:7,代码来源:Warehouse.php

示例5: productHandler


//.........这里部分代码省略.........
             // if advanced stock manager
             if ($this->advanced_stock_management == 1) {
                 $stock = new ErpStock();
                 $stock->id_product = $product['idproduct'];
                 $stock->id_product_attribute = $product['idproductattribute'];
                 $stock->id_warehouse = $this->id_warehouse;
                 $stock->physical_quantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity'];
                 $stock->usable_quantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity'];
                 // get reference price
                 $price = $stock->getPriceTe();
                 // if $price is false, we dont have stock for this product. si quantity is lower than stock, set price to 0
                 if (isset($product['foundquantity']) && (int) $product['foundquantity'] < $product['physicalquantity'] || ($price = false)) {
                     $price = 0;
                 }
                 $stock->price_te = $price;
                 // if we already have a stock line for this production, we update else we insert
                 if ($stock->id = $stock->getStockId()) {
                     $maj_stock = $stock->update();
                 } else {
                     $maj_stock = $stock->add();
                 }
             } else {
                 $maj_stock = StockAvailable::setQuantity($product['idproduct'], $product['idproductattribute'], (int) $product['foundquantity']);
                 if (is_null($maj_stock)) {
                     $maj_stock = true;
                 }
             }
             // if update stock ok --> update location
             if ($maj_stock) {
                 // no stock change if advanced stock inactive
                 if ($this->advanced_stock_management == 1) {
                     require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/stock/ErpWarehouseProductLocation.php';
                     $wpl_id = ErpWarehouseProductLocationClass::getWarehouseProductLocationId($product['idproduct'], $product['idproductattribute']);
                     $warehouse_location = new ErpWarehouseProductLocationClass($wpl_id);
                     $warehouse_location->id_product = $product['idproduct'];
                     $warehouse_location->id_product_attribute = $product['idproductattribute'];
                     $warehouse_location->id_warehouse = $this->id_warehouse;
                     /*if ($product['area'] != '--')
                               $warehouse_location->zone = $product['area'];
                       if ($product['subarea'] != '--')
                               $warehouse_location->sous_zone = $product['subarea'];*/
                     $warehouse_location->location = $product['location'];
                     $warehouse_location->id_warehouse_product_location = $wpl_id;
                     // if update location ok & advanced stock active -> generate stock movement
                     if ($warehouse_location->update()) {
                         //echo 'Maj location OK';
                         // No stock movement if advanced stock inactive
                         if ($this->advanced_stock_management == 1) {
                             $stock_mvt = new ErpStockMvt();
                             $stock_mvt->id_stock = $stock->id;
                             $stock_mvt->id_order = 0;
                             $stock_mvt->id_supply_order = 0;
                             // if not mvt reason selected => depend of quantity to increase or decrease
                             if (!isset($product['idreason']) || $product['idreason'] == '') {
                                 if ($inventory_product->qte_before <= $inventory_product->qte_after) {
                                     $stock_mvt->id_stock_mvt_reason = 1;
                                 } else {
                                     $stock_mvt->id_stock_mvt_reason = 2;
                                 }
                             } else {
                                 $stock_mvt->id_stock_mvt_reason = $product['idreason'];
                             }
                             $stock_mvt->id_employee = $this->id_employee;
                             $stock_mvt->employee_firstname = $this->firstname;
                             $stock_mvt->employee_lastname = $this->lastname;
                             $stock_mvt->price_te = $price;
                             $stock_mvt->current_wa = $price;
                             // Récupération du sign (flèche up / down)
                             // Get sign (arrow up/down)
                             if (isset($product['foundquantity']) && ((int) $product['foundquantity'] >= (int) $product['physicalquantity'] || (int) $product['foundquantity'] == 0)) {
                                 $stock_mvt->sign = 1;
                             } else {
                                 $stock_mvt->sign = -1;
                             }
                             // calculate the quantity movement of stock
                             $foundquantity = !isset($product['foundquantity']) || $product['foundquantity'] == '' ? 0 : (int) $product['foundquantity'];
                             $physicalquantity = !isset($product['physicalquantity']) || $product['physicalquantity'] == '' ? 0 : (int) $product['physicalquantity'];
                             $mvt = abs($foundquantity - $physicalquantity);
                             $stock_mvt->physical_quantity = $mvt;
                             // Synchronise available stock
                             if ($stock_mvt->add(true)) {
                                 StockAvailable::synchronize($product['idproduct']);
                             } else {
                                 $this->errors[] = Tools::displayError($this->l('Error while inserting stock movement. Please try again.'));
                             }
                         } else {
                             $this->errors[] = Tools::displayError($this->l('No stock movement. You need to activate the advanced stock management in Preference > Products'));
                         }
                     } else {
                         $this->errors[] = Tools::displayError($this->l('Error while updating product location'));
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError($this->l('Error while updating stock'));
             }
         } else {
             $this->errors[] = Tools::displayError($this->l('Error while inserting product inventory row'));
         }
     }
 }
开发者ID:prestamodule,项目名称:erpillicopresta,代码行数:101,代码来源:AdminInventory.php

示例6: validateOrder


//.........这里部分代码省略.........
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = 0;
                     $customer_message->message = $update_message->message;
                     $customer_message->private = 0;
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving message');
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Hook validate order
                 Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                 foreach ($this->context->cart->getProducts() as $product) {
                     if ($order_status->logable) {
                         ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Set the order status
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                 $new_history->addWithemail(true, $extra_vars);
                 // Switch to back order if needed
                 if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                     $history = new OrderHistory();
                     $history->id_order = (int) $order->id;
                     $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
                     $history->addWithemail();
                 }
                 unset($order_detail);
                 // Order is reloaded because the status just changed
                 $order = new Order($order->id);
                 // Send an e-mail to customer (one order = one email)
                 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                     $invoice = new Address($order->id_address_invoice);
                     $delivery = new Address($order->id_address_delivery);
                     $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                     $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                     $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false));
                     if (is_array($extra_vars)) {
                         $data = array_merge($data, $extra_vars);
                     }
                     // Join PDF invoice
                     if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                         $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                         $file_attachement = array();
                         $file_attachement['content'] = $pdf->render(false);
                         $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                         $file_attachement['mime'] = 'application/pdf';
                     } else {
                         $file_attachement = null;
                     }
                     if (self::DEBUG_MODE) {
                         PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
                     }
                     if (Validate::isEmail($this->context->customer->email)) {
                         Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                     }
                 }
                 // updates stock in shops
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                     $product_list = $order->getProducts();
                     foreach ($product_list as $product) {
                         // if the available quantities depends on the physical stock
                         if (StockAvailable::dependsOnStock($product['product_id'])) {
                             // synchronizes
                             StockAvailable::synchronize($product['product_id'], $order->id_shop);
                         }
                     }
                 }
             } else {
                 $error = Tools::displayError('Order creation failed');
                 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart);
                 die($error);
             }
         }
         // End foreach $order_detail_list
         // Update Order Details Tax in case cart rules have free shipping
         foreach ($order->getOrderDetailList() as $detail) {
             $order_detail = new OrderDetail($detail['id_order_detail']);
             $order_detail->updateTaxAmount($order);
         }
         // Use the last order as currentOrder
         if (isset($order) && $order->id) {
             $this->currentOrder = (int) $order->id;
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
         }
         return true;
     } else {
         $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
         PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id);
         die($error);
     }
 }
开发者ID:Oldwo1f,项目名称:yakaboutique,代码行数:101,代码来源:PaymentModule.php

示例7: postProcess

 /**
  * AdminController::postProcess() override
  * @see AdminController::postProcess()
  */
 public function postProcess()
 {
     parent::postProcess();
     // Checks access
     if (Tools::isSubmit('addStock') && !($this->tabAccess['add'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to add stock.');
     }
     if (Tools::isSubmit('removeStock') && !($this->tabAccess['delete'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to delete stock');
     }
     if (Tools::isSubmit('transferStock') && !($this->tabAccess['edit'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to transfer stock.');
     }
     if (count($this->errors)) {
         return;
     }
     // Global checks when add / remove / transfer product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') || Tools::isSubmit('transferstock')) && Tools::isSubmit('is_post')) {
         // get product ID
         $id_product = (int) Tools::getValue('id_product', 0);
         if ($id_product <= 0) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get product_attribute ID
         $id_product_attribute = (int) Tools::getValue('id_product_attribute', 0);
         // check the product hash
         $check = Tools::getValue('check', '');
         $check_valid = md5(_COOKIE_KEY_ . $id_product . $id_product_attribute);
         if ($check != $check_valid) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get quantity and check that the post value is really an integer
         // If it's not, we have nothing to do
         $quantity = Tools::getValue('quantity', 0);
         if (!is_numeric($quantity) || (int) $quantity <= 0) {
             $this->errors[] = Tools::displayError('The quantity value is not valid.');
         }
         $quantity = (int) $quantity;
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         $redirect = self::$currentIndex . '&token=' . $token;
     }
     // Global checks when add / remove product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock')) && Tools::isSubmit('is_post')) {
         // get warehouse id
         $id_warehouse = (int) Tools::getValue('id_warehouse', 0);
         if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) {
             $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
         }
         // get stock movement reason id
         $id_stock_mvt_reason = (int) Tools::getValue('id_stock_mvt_reason', 0);
         if ($id_stock_mvt_reason <= 0 || !StockMvtReason::exists($id_stock_mvt_reason)) {
             $this->errors[] = Tools::displayError('The reason is not valid.');
         }
         // get usable flag
         $usable = Tools::getValue('usable', null);
         if (is_null($usable)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity is usable for sale on shops or not.');
         }
         $usable = (bool) $usable;
     }
     if (Tools::isSubmit('addstock') && Tools::isSubmit('is_post')) {
         // get product unit price
         $price = str_replace(',', '.', Tools::getValue('price', 0));
         if (!is_numeric($price)) {
             $this->errors[] = Tools::displayError('The product price is not valid.');
         }
         $price = round(floatval($price), 6);
         // get product unit price currency id
         $id_currency = (int) Tools::getValue('id_currency', 0);
         if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
             $this->errors[] = Tools::displayError('The selected currency is not valid.');
         }
         // if all is ok, add stock
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             // convert price to warehouse currency if needed
             if ($id_currency != $warehouse->id_currency) {
                 // First convert price to the default currency
                 $price_converted_to_default_currency = Tools::convertPrice($price, $id_currency, false);
                 // Convert the new price from default currency to needed currency
                 $price = Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true);
             }
             // add stock
             $stock_manager = StockManagerFactory::getManager();
             if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $usable)) {
                 // Create warehouse_product_location entry if we add stock to a new warehouse
                 $id_wpl = (int) WarehouseProductLocation::getIdByProductAndWarehouse($id_product, $id_product_attribute, $id_warehouse);
                 if (!$id_wpl) {
                     $wpl = new WarehouseProductLocation();
                     $wpl->id_product = (int) $id_product;
                     $wpl->id_product_attribute = (int) $id_product_attribute;
                     $wpl->id_warehouse = (int) $id_warehouse;
                     $wpl->save();
                 }
                 StockAvailable::synchronize($id_product);
                 if (Tools::isSubmit('addstockAndStay')) {
//.........这里部分代码省略.........
开发者ID:ortegon000,项目名称:tienda,代码行数:101,代码来源:AdminStockManagementController.php

示例8: productImport


//.........这里部分代码省略.........
                        if (!empty($feature_name) && !empty($feature_value)) {
                            $id_feature = (int) Feature::addFeatureImport($feature_name, $position);
                            $id_product = null;
                            if (Tools::getValue('forceIDs') || Tools::getValue('match_ref')) {
                                $id_product = (int) $product->id;
                            }
                            $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
                            Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                        }
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
                // set advanced stock managment
                if (isset($product->advanced_stock_management)) {
                    if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product %1$s '), $product->name[$default_language_id]);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        $product->setAdvancedStockManagement($product->advanced_stock_management);
                    }
                    // automaticly disable depends on stock, if a_s_m set to disabled
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0);
                    }
                }
                // Check if warehouse exists
                if (isset($product->warehouse) && $product->warehouse) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        if (Warehouse::exists($product->warehouse)) {
                            // Get already associated warehouses
                            $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                            // Delete any entry in warehouse for this product
                            foreach ($associated_warehouses_collection as $awc) {
                                $awc->delete();
                            }
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = 0;
                            $warehouse_location_entity->id_warehouse = $product->warehouse;
                            if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language_id]);
                        }
                    }
                }
                // stock available
                if (isset($product->depends_on_stock)) {
                    if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, cannot set "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                    }
                    // This code allows us to set qty and disable depends on stock
                    if (isset($product->quantity) && (int) $product->quantity) {
                        // if depends on stock and quantity, add quantity to stock
                        if ($product->depends_on_stock == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $product->wholesale_price);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round(floatval($price), 6);
                            $warehouse = new Warehouse($product->warehouse);
                            if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, (int) $product->quantity, 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($shops as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
开发者ID:julienlerch,项目名称:xburning,代码行数:101,代码来源:AdminImportController.php

示例9: postProcess


//.........这里部分代码省略.........
         if ($delivery_expected <= new DateTime('yesterday')) {
             $this->errors[] = Tools::displayError($this->l('The date you specified cannot be in the past.'));
         }
         // gets threshold
         $quantity_threshold = null;
         if (Tools::getValue('load_products') && Validate::isInt(Tools::getValue('load_products'))) {
             $quantity_threshold = (int) Tools::getValue('load_products');
         }
         if (!count($this->errors)) {
             // forces date for templates
             if (Tools::isSubmit('is_template') && !Tools::getValue('date_delivery_expected')) {
                 $_POST['date_delivery_expected'] = date('Y-m-d h:i:s');
             }
             // specify initial state
             $_POST['id_supply_order_state'] = 1;
             //defaut creation state
             // specify global reference currency
             $_POST['id_ref_currency'] = Currency::getDefaultCurrency()->id;
             // specify supplier name
             $_POST['supplier_name'] = Supplier::getNameById($id_supplier);
             //specific discount check
             $_POST['discount_rate'] = (double) str_replace(array(' ', ','), array('', '.'), Tools::getValue('discount_rate', 0));
         }
         // manage each associated product
         $this->manageOrderProducts();
         // if the threshold is defined and we are saving the order
         if (Tools::isSubmit('submitAddsupply_order') && $quantity_threshold != null) {
             $this->loadProducts($quantity_threshold);
         }
     }
     // Manage state change
     if (Tools::isSubmit('submitChangestate') && Tools::isSubmit('id_supply_order') && Tools::isSubmit('id_supply_order_state')) {
         if ($this->tabAccess['edit'] != '1') {
             $this->errors[] = Tools::displayError($this->l('You do not have permission to change the order status.'));
         }
         // get state ID
         $id_state = (int) Tools::getValue('id_supply_order_state', 0);
         if ($id_state <= 0) {
             $this->errors[] = Tools::displayError($this->l('The selected supply order status is not valid.'));
         }
         // get supply order ID
         $id_supply_order = (int) Tools::getValue('id_supply_order', 0);
         if ($id_supply_order <= 0) {
             $this->errors[] = Tools::displayError($this->l('The supply order ID is not valid.'));
         }
         if (!count($this->errors)) {
             // try to load supply order
             $supply_order = new SupplyOrder($id_supply_order);
             if (Validate::isLoadedObject($supply_order)) {
                 // get valid available possible states for this order
                 $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state);
                 foreach ($states as $state) {
                     // if state is valid, change it in the order
                     if ($id_state == $state['id_supply_order_state']) {
                         $new_state = new SupplyOrderState($id_state);
                         $old_state = new SupplyOrderState($supply_order->id_supply_order_state);
                         // special case of validate state - check if there are products in the order and the required state is not an enclosed state
                         if ($supply_order->isEditable() && !$supply_order->hasEntries() && !$new_state->enclosed) {
                             $this->errors[] = Tools::displayError($this->l('It is not possible to change the status of this order because you did not order any products.'));
                         }
                         if (!count($this->errors)) {
                             $supply_order->id_supply_order_state = $state['id_supply_order_state'];
                             if ($supply_order->save()) {
                                 // if pending_receipt,
                                 // or if the order is being canceled,
                                 // synchronizes StockAvailable
                                 if ($new_state->pending_receipt && !$new_state->receipt_state || $old_state->receipt_state && $new_state->enclosed && !$new_state->receipt_state) {
                                     $supply_order_details = $supply_order->getEntries();
                                     $products_done = array();
                                     foreach ($supply_order_details as $supply_order_detail) {
                                         if (!in_array($supply_order_detail['id_product'], $products_done)) {
                                             StockAvailable::synchronize($supply_order_detail['id_product']);
                                             $products_done[] = $supply_order_detail['id_product'];
                                         }
                                     }
                                 }
                                 $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
                                 $redirect = self::$currentIndex . '&token=' . $token;
                                 $this->redirect_after = $redirect . '&conf=5';
                             }
                         }
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError($this->l('The selected supplier is not valid.'));
             }
         }
     }
     // updates receipt
     if (Tools::isSubmit('submitFiltersupply_order_detail') && Tools::isSubmit('submitBulkUpdatesupply_order_detail') && Tools::isSubmit('id_supply_order')) {
         $this->postProcessUpdateReceipt();
     }
     // use template to create a supply order
     if (Tools::isSubmit('create_supply_order') && Tools::isSubmit('id_supply_order')) {
         $this->postProcessCopyFromTemplate();
     }
     if (!count($this->errors) && $this->is_editing_order || !$this->is_editing_order) {
         parent::postProcess();
     }
 }
开发者ID:FAVHYAN,项目名称:a3workout,代码行数:101,代码来源:AdminSupplyOrdersController.php

示例10: postProcess


//.........这里部分代码省略.........
                 $id_stock_s2 = $value['id_stock_s2'];
                 if (empty($id_stock_s1)) {
                     $this->errors[] = 'Error while updating the stock for a product : stock id missing !';
                     return true;
                 }
                 // update stock un warehouse A (source)
                 $stock = new ErpStock((int) $id_stock_s1);
                 $stock->physical_quantity -= $transfer_quantity;
                 $stock->usable_quantity -= $transfer_quantity;
                 if ($stock->physical_quantity < 0) {
                     $stock->physical_quantity = 0;
                 }
                 if ($stock->usable_quantity < 0) {
                     $stock->usable_quantity = 0;
                 }
                 /*  Update Stock */
                 if ($stock->update()) {
                     /*  Movment A to B */
                     $stock_mvt = new ErpStockMvt();
                     $stock_mvt->id_stock = $stock->id;
                     $stock_mvt->id_order = 0;
                     $stock_mvt->id_supply_order = 0;
                     $stock_mvt->id_stock_mvt_reason = 6;
                     $stock_mvt->id_employee = Tools::getValue('id_employee');
                     $stock_mvt->employee_firstname = Tools::getValue('firstname');
                     $stock_mvt->employee_lastname = Tools::getValue('lastname');
                     $stock_mvt->price_te = $stock->getPriceTe();
                     $stock_mvt->current_wa = $stock->getPriceTe();
                     $stock_mvt->sign = -1;
                     $stock_mvt->physical_quantity = $transfer_quantity;
                     // if movment OK, update stock in B warehouse (location)
                     if ($stock_mvt->add(true)) {
                         // add id movment stock generated (useful to generate the warehouse delivery notice)
                         array_push($ids_mvt, $stock_mvt->getLastId());
                         if ((int) $id_stock_s2 > 0) {
                             $stock_s2 = new ErpStock((int) $id_stock_s2);
                             $stock_s2->physical_quantity += $transfer_quantity;
                             $stock_s2->usable_quantity += $transfer_quantity;
                         } else {
                             require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/ErpProduct.php';
                             //get product information
                             $product_stock = new ProductCore((int) $id_product, (int) $id_product_attribute);
                             // stock not existe we add row in stock table
                             $stock_s2 = new ErpStock();
                             $stock_s2->physical_quantity += $transfer_quantity;
                             $stock_s2->usable_quantity += $transfer_quantity;
                             $stock_s2->id_product = (int) $id_product;
                             $stock_s2->id_product_attribute = (int) $id_product_attribute;
                             $stock_s2->id_warehouse = (int) Tools::getValue('id_stockB');
                             $stock_s2->price_te = $product_stock->wholesale_price;
                             $stock_s2->ean13 = $product_stock->ean13;
                             $stock_s2->upc = $product_stock->upc;
                         }
                         /*  of OK, movment from B to A */
                         if ($stock_s2->save()) {
                             $stock_mvt->id_stock = $stock_s2->id;
                             $stock_mvt->id_stock_mvt_reason = 7;
                             $stock_mvt->sign = 1;
                             // add id movment stock generated (useful to generate warehouse inter delivery)
                             if ($stock_mvt->add(true)) {
                                 array_push($ids_mvt, $stock_mvt->getLastId());
                             } else {
                                 $this->errors[] = 'Error while updating the stock for a product';
                             }
                         } else {
                             $this->errors[] = 'Error while updating the stock for a product';
                         }
                     } else {
                         $this->errors[] = 'Error while updating the stock for a product';
                     }
                 } else {
                     $this->errors[] = 'Error while updating the stock for a product';
                 }
                 // synchronize availbale stock ::quantity
                 StockAvailable::synchronize($id_product);
             }
             $ids_mvt = implode('|', $ids_mvt);
             // we reset values
             $transfer_ok = true;
         }
     }
     // transfer is ok, we redirect the user to home page of transfer
     if (Tools::isSubmit('validate_transfer') && isset($transfer_ok) && $transfer_ok) {
         $url_redirect = self::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminStockTransfer');
         $url_redirect .= '&validate_transfer&ids_mvt=' . $ids_mvt . '&ids_mvt_csv=' . Tools::getValue('ids_mvt_csv');
         $url_redirect .= '&id_warehouse_src=' . Tools::getValue('id_warehouse_src') . '&id_warehouse_dst=' . Tools::getValue('id_warehouse_dst');
         Tools::redirectAdmin($url_redirect);
     }
     if (Tools::isSubmit('ids_mvt_csv') && Tools::isSubmit('get_csv_transfer')) {
         $this->renderCSV();
     }
     // Generate PDF of tranfert
     if (Tools::isSubmit('ids_mvt') && Tools::isSubmit('action') && Tools::getValue('action') == 'generateTransferPDF') {
         $this->processGenerateTransferPDF();
     }
     // to get erp feature list
     require_once _PS_MODULE_DIR_ . 'erpillicopresta/models/ErpFeature.php';
     // send warehouse liste to template
     $this->context->smarty->assign(array('warehousesA' => $warehousesA, 'warehousesB' => $warehousesB, 'categories' => Category::getSimpleCategories((int) $this->context->language->id), 'suppliers' => Supplier::getSuppliers(), 'manufacturers' => Manufacturer::getManufacturers(), 'id_category' => -1, 'id_supplier' => -1, 'id_manufacturer' => -1, 'name_or_ean' => '', 'erp_feature' => ErpFeature::getFeaturesWithToken($this->context->language->iso_code), 'template_path' => $this->template_path));
 }
开发者ID:prestamodule,项目名称:erpillicopresta,代码行数:101,代码来源:AdminStockTransfer.php

示例11: synchronize

 public static function synchronize($id_product, $order_id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     if (Pack::isPack($id_product)) {
         if (Validate::isLoadedObject($product = new Product((int) $id_product))) {
             if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                 $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                 foreach ($products_pack as $product_pack) {
                     StockAvailable::synchronize($product_pack->id, $order_id_shop);
                 }
             }
         } else {
             return false;
         }
     }
     $ids_warehouse = Warehouse::getWarehousesGroupedByShops();
     if ($order_id_shop !== null) {
         $order_warehouses = array();
         $wh = Warehouse::getWarehouses(false, (int) $order_id_shop);
         foreach ($wh as $warehouse) {
             $order_warehouses[] = $warehouse['id_warehouse'];
         }
     }
     $ids_product_attribute = array();
     foreach (Product::getProductAttributesIds($id_product) as $id_product_attribute) {
         $ids_product_attribute[] = $id_product_attribute['id_product_attribute'];
     }
     $out_of_stock = StockAvailable::outOfStock($id_product);
     $manager = StockManagerFactory::getManager();
     foreach ($ids_warehouse as $id_shop => $warehouses) {
         if (StockAvailable::dependsOnStock($id_product, $id_shop)) {
             $product_quantity = 0;
             if (empty($ids_product_attribute)) {
                 $allowed_warehouse_for_product = WareHouse::getProductWarehouseList((int) $id_product, 0, (int) $id_shop);
                 $allowed_warehouse_for_product_clean = array();
                 foreach ($allowed_warehouse_for_product as $warehouse) {
                     $allowed_warehouse_for_product_clean[] = (int) $warehouse['id_warehouse'];
                 }
                 $allowed_warehouse_for_product_clean = array_intersect($allowed_warehouse_for_product_clean, $warehouses);
                 if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_product_clean, $order_warehouses))) {
                     continue;
                 }
                 $product_quantity = $manager->getProductRealQuantities($id_product, null, $allowed_warehouse_for_product_clean, true);
                 Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => 0, 'quantity' => $product_quantity));
             } else {
                 foreach ($ids_product_attribute as $id_product_attribute) {
                     $allowed_warehouse_for_combination = WareHouse::getProductWarehouseList((int) $id_product, (int) $id_product_attribute, (int) $id_shop);
                     $allowed_warehouse_for_combination_clean = array();
                     foreach ($allowed_warehouse_for_combination as $warehouse) {
                         $allowed_warehouse_for_combination_clean[] = (int) $warehouse['id_warehouse'];
                     }
                     $allowed_warehouse_for_combination_clean = array_intersect($allowed_warehouse_for_combination_clean, $warehouses);
                     if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_combination_clean, $order_warehouses))) {
                         continue;
                     }
                     $quantity = $manager->getProductRealQuantities($id_product, $id_product_attribute, $allowed_warehouse_for_combination_clean, true);
                     $query = new DbQuery();
                     $query->select('COUNT(*)');
                     $query->from('stock_available');
                     $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                     if ((int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query)) {
                         $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array(), 'quantity', $quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                         Db::getInstance()->update($query['table'], $query['data'], $query['where']);
                     } else {
                         $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array('depends_on_stock' => 1, 'out_of_stock' => $out_of_stock, 'id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute), 'quantity', $quantity));
                         StockAvailable::addSqlShopParams($query['data']);
                         Db::getInstance()->insert($query['table'], $query['data']);
                     }
                     $product_quantity += $quantity;
                     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $quantity));
                 }
             }
             $query = array('table' => 'stock_available', 'data' => PP::hydrateQty(array(), 'quantity', $product_quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = 0' . StockAvailable::addSqlShopRestriction(null, $id_shop));
             Db::getInstance()->update($query['table'], $query['data'], $query['where']);
         }
     }
     if (count($ids_warehouse) == 0 && StockAvailable::dependsOnStock((int) $id_product)) {
         Db::getInstance()->update('stock_available', array('quantity' => 0, 'quantity_remainder' => 0), 'id_product = ' . (int) $id_product);
     }
     Cache::clean('StockAvailable::getQuantityAvailableByProduct_' . (int) $id_product . '*');
 }
开发者ID:Oldwo1f,项目名称:yakaboutique,代码行数:83,代码来源:StockAvailable.php

示例12: upsert


//.........这里部分代码省略.........
     $location->id_product = $product->id;
     $location->id_product_attribute = 0;
     $location->id_warehouse = $line['warehouse'];
     $location->save();
     /*
     $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
     $stock = new Stock($stock);
     $stock->id_product = $product->id;
     $stock->id_product_attribute = 0;
     $stock->id_warehouse = $line['warehouse'];
     $stock->physical_quantity = $line['count'];
     $stock->usable_quantity = $line['count'];
     $stock->price_te = 0;
     $stock->save();
     */
     //установить зависимость количества товара от остатка на складе для каждого магазинеа
     //исходим из того, что в настройках Мультимагазина остаток НЕ единый на все магазины
     $id_product = $product->id;
     $depends_on_stock = true;
     $out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (ставь 1, т.к. 2 (как в Preferences) не дает заказать товар на сайте)
     for ($id_shop = 1; $id_shop <= 4; $id_shop++) {
         StockAvailable::setProductDependsOnStock($id_product, $depends_on_stock, $id_shop);
     }
     //разрешить или запретить продажу товара без остатка
     /*  для магазина 2,3 запретить продажу, если нет в наличии. out_of_stock = 0
             2   Second shop Gelikon 
             3   First shop Gelikon
         */
     $out_of_stock = 0;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 2);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 3);
     /*
         Для online и заказов по телефону разрешить заказ товара, которого нет в наличии
         1 Gelikon DE online
         4 Заказы по телефону
     */
     $out_of_stock = 1;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 1);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 4);
     //Добавить партию товара на склад с записью в журнал движения товаров
     $id_product = $product->id;
     $id_product_attribute = 0;
     $id_stock_mvt_reason = 1;
     $price = 1;
     $id_currency = 1;
     $id_warehouse = $line['warehouse'];
     $warehouse = new Warehouse($id_warehouse);
     $stock_manager = StockManagerFactory::getManager();
     if ($line['count'] != 0) {
         //echo "добавляем товар ";
         $is_usable = true;
         $quantity = $line['count'];
         // add stock
         if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $is_usable)) {
             StockAvailable::synchronize($id_product);
         } else {
             $errors[] = Tools::displayError('An error occurred. No stock was added.');
         }
     }
     /*
             $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
             $available = new StockAvailable($available);
             $available->id_product = $product->id;
             $available->id_product_attribute = 0;
             //$available->id_shop = Context::getContext()->shop->id;
             $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
             $available->save();
     
             StockAvailable::setProductDependsOnStock($product->id, true, null);
             StockAvailable::setProductOutOfStock($product->id, 1, null); //allow
     */
     while (strlen($line['reference']) < 9) {
         $line['reference'] = '0' . $line['reference'];
     }
     if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
         $product->deleteImages();
         $image = new Image();
         $image->id_product = $product->id;
         $image->cover = 1;
         $image->position = 0;
         $image->save();
         $name = $image->getPathForCreation();
         copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '.' . $image->image_format);
         $types = ImageType::getImagesTypes('products');
         foreach ($types as $type) {
             ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
         }
     }
     /*
             Db::getInstance()->update('stock_available', array(
       'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
        'out_of_stock' => (int)1, //1-allow
             ), 'id_product='.$product->id.'');
     $affrows = Db::getInstance()->Affected_Rows();
     var_dump($affrows);
     */
     //var_dump($product->reference);
     //echo "<br/><br/><br/><br/>";
 }
开发者ID:,项目名称:,代码行数:101,代码来源:

示例13: postProcess

    public function postProcess()
    {
        // If id_order is sent, we instanciate a new Order object
        if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
            $order = new Order(Tools::getValue('id_order'));
            if (!Validate::isLoadedObject($order)) {
                throw new PrestaShopException('Can\'t load Order object');
            }
        }
        /* Update shipping number */
        if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
            if ($this->tabAccess['edit'] === '1') {
                $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
                if (!Validate::isLoadedObject($order_carrier)) {
                    $this->errors[] = Tools::displayError('Order carrier ID is invalid');
                } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                    $this->errors[] = Tools::displayError('Tracking number is incorrect');
                } else {
                    // update shipping number
                    // Keep these two following lines for backward compatibility, remove on 1.6 version
                    $order->shipping_number = Tools::getValue('tracking_number');
                    $order->update();
                    // Update order_carrier
                    $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                    if ($order_carrier->update()) {
                        // Send mail to customer
                        $customer = new Customer((int) $order->id_customer);
                        $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                        if (!Validate::isLoadedObject($customer)) {
                            throw new PrestaShopException('Can\'t load Customer object');
                        }
                        if (!Validate::isLoadedObject($carrier)) {
                            throw new PrestaShopException('Can\'t load Carrier object');
                        }
                        $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference());
                        if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                            Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order));
                            Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                        } else {
                            $this->errors[] = Tools::displayError('An error occurred while sending e-mail to the customer.');
                        }
                    } else {
                        $this->errors[] = Tools::displayError('Order carrier can\'t be updated');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitState') && isset($order)) {
            if ($this->tabAccess['edit'] === '1') {
                $order_state = new OrderState(Tools::getValue('id_order_state'));
                if (!Validate::isLoadedObject($order_state)) {
                    $this->errors[] = Tools::displayError('Invalid new order status');
                } else {
                    $current_order_state = $order->getCurrentOrderState();
                    if ($current_order_state->id != $order_state->id) {
                        // Create new OrderHistory
                        $history = new OrderHistory();
                        $history->id_order = $order->id;
                        $history->id_employee = (int) $this->context->employee->id;
                        $use_existings_payment = false;
                        if (!$order->hasInvoice()) {
                            $use_existings_payment = true;
                        }
                        $history->changeIdOrderState($order_state->id, $order->id, $use_existings_payment);
                        $carrier = new Carrier($order->id_carrier, $order->id_lang);
                        $templateVars = array();
                        if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                            $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                        }
                        // Save all changes
                        if ($history->addWithemail(true, $templateVars)) {
                            // synchronizes quantities if needed..
                            if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                                foreach ($order->getProducts() as $product) {
                                    if (StockAvailable::dependsOnStock($product['product_id'])) {
                                        StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                    }
                                }
                            }
                            Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                        }
                        $this->errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.');
                    } else {
                        $this->errors[] = Tools::displayError('This order is already assigned this status');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
            if ($this->tabAccess['edit'] === '1') {
                $customer = new Customer(Tools::getValue('id_customer'));
                if (!Validate::isLoadedObject($customer)) {
                    $this->errors[] = Tools::displayError('Customer is invalid');
                } elseif (!Tools::getValue('message')) {
                    $this->errors[] = Tools::displayError('Message cannot be blank');
                } else {
                    /* Get message rules and and check fields validity */
                    $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
//.........这里部分代码省略.........
开发者ID:jicheng17,项目名称:vipinsg,代码行数:101,代码来源:AdminOrdersController.php

示例14: attributeImport


//.........这里部分代码省略.........
                        }
                        if (isset($attributes[$group . '_' . $attribute])) {
                            $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                        }
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
            $product->checkDefaultAttributes();
            if (!$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            if ($id_product_attribute) {
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')');
                }
                if (isset($info['advanced_stock_management'])) {
                    if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product with id %d.'), $product->id);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product with id %d.'), $product->id);
                    } else {
                        $product->setAdvancedStockManagement($info['advanced_stock_management']);
                    }
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                    }
                }
                if (isset($info['warehouse']) && $info['warehouse']) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse is not set on product with id %d.'), $product->id);
                    } else {
                        if (Warehouse::exists($info['warehouse'])) {
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                            $warehouse_location_entity->id_warehouse = $info['warehouse'];
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language]);
                        }
                    }
                }
                if (isset($info['depends_on_stock'])) {
                    if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for depends on stock for product %1$s '), $product->name[$default_language]);
                    } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot set depends on stock %1$s '), $product->name[$default_language]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                    }
                    if (isset($info['quantity']) && $info['quantity']) {
                        if ($info['depends_on_stock'] == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $info['wholesale_price']);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round((double) $price, 6);
                            $warehouse = new Warehouse($info['warehouse']);
                            if ($stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, $info['quantity'], 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($id_shop_list as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($id_shop_list as $shop) {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
开发者ID:Oldwo1f,项目名称:yakaboutique,代码行数:101,代码来源:AdminImportController.php

示例15: processWarehouses

 /**
  * Post treatment for warehouses
  */
 public function processWarehouses()
 {
     if ((int) Tools::getValue('warehouse_loaded') === 1 && Validate::isLoadedObject($product = new Product((int) ($id_product = Tools::getValue('id_product'))))) {
         // Get all id_product_attribute
         $attributes = $product->getAttributesResume($this->context->language->id);
         if (empty($attributes)) {
             $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => '');
         }
         // Get all available warehouses
         $warehouses = Warehouse::getWarehouses(true);
         // Get already associated warehouses
         $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
         $elements_to_manage = array();
         // get form inforamtion
         foreach ($attributes as $attribute) {
             foreach ($warehouses as $warehouse) {
                 $key = $warehouse['id_warehouse'] . '_' . $product->id . '_' . $attribute['id_product_attribute'];
                 // get elements to manage
                 if (Tools::isSubmit('check_warehouse_' . $key)) {
                     $location = Tools::getValue('location_warehouse_' . $key, '');
                     $elements_to_manage[$key] = $location;
                 }
             }
         }
         // Delete entry if necessary
         foreach ($associated_warehouses_collection as $awc) {
             if (!array_key_exists($awc->id_warehouse . '_' . $awc->id_product . '_' . $awc->id_product_attribute, $elements_to_manage)) {
                 $awc->delete();
             }
         }
         // Manage locations
         foreach ($elements_to_manage as $key => $location) {
             $params = explode('_', $key);
             $wpl_id = (int) WarehouseProductLocation::getIdByProductAndWarehouse((int) $params[1], (int) $params[2], (int) $params[0]);
             if (empty($wpl_id)) {
                 //create new record
                 $warehouse_location_entity = new WarehouseProductLocation();
                 $warehouse_location_entity->id_product = (int) $params[1];
                 $warehouse_location_entity->id_product_attribute = (int) $params[2];
                 $warehouse_location_entity->id_warehouse = (int) $params[0];
                 $warehouse_location_entity->location = pSQL($location);
                 $warehouse_location_entity->save();
             } else {
                 $warehouse_location_entity = new WarehouseProductLocation((int) $wpl_id);
                 $location = pSQL($location);
                 if ($location != $warehouse_location_entity->location) {
                     $warehouse_location_entity->location = pSQL($location);
                     $warehouse_location_entity->update();
                 }
             }
         }
         StockAvailable::synchronize((int) $id_product);
     }
 }
开发者ID:,项目名称:,代码行数:57,代码来源:


注:本文中的StockAvailable::synchronize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。