Commit bcfd0100 authored by Florent Delmotte's avatar Florent Delmotte Committed by Cédric Houbart
Browse files

add import products by csv to base_product

parent 7461a5ab
......@@ -91,6 +91,20 @@ class ProductsService {
return $ids;
}
static function getByRef($ref) {
$pdo = PDOBuilder::getPDO();
$stmt = $pdo->prepare("SELECT * FROM PRODUCTS "
. "WHERE PRODUCTS.REFERENCE = :ref");
$stmt->bindParam(":ref", $ref, \PDO::PARAM_STR);
if ($stmt->execute()) {
if ($row = $stmt->fetch()) {
$prd = ProductsService::buildDBPrd($row, $pdo);
return $prd;
}
}
return null;
}
static function get($id) {
$pdo = PDOBuilder::getPDO();
$stmt = $pdo->prepare("SELECT * FROM PRODUCTS LEFT JOIN PRODUCTS_CAT "
......
......@@ -39,6 +39,19 @@ class TaxesService {
return $tax;
}
static function getByName($name) {
$pdo = PDOBuilder::getPDO();
$stmt = $pdo->prepare("SELECT * FROM TAXES WHERE NAME = :name");
$stmt->bindParam(":name", $name, \PDO::PARAM_STR);
if ($stmt->execute()) {
if ($row = $stmt->fetch()) {
$tax = TaxesService::buildDBTaxCat($row, $pdo);
return $tax;
}
}
return null;
}
static function getAll() {
$taxcats = array();
$pdo = PDOBuilder::getPDO();
......
......@@ -38,7 +38,11 @@ $products = \Pasteque\ProductsService::getAll(FALSE, TRUE);
<?php \Pasteque\tpl_msg_box($message, $error); ?>
<p><a class="btn" href="<?php echo \Pasteque\get_module_url_action(PLUGIN_NAME, 'product_edit'); ?>"><img src="<?php echo \Pasteque\get_template_url(); ?>img/btn_add.png" /><?php \pi18n("Add a product", PLUGIN_NAME); ?></a></p>
<?php \Pasteque\tpl_btn('btn', \Pasteque\get_module_url_action(PLUGIN_NAME, "product_edit"),
\i18n('Add a product', PLUGIN_NAME), 'img/btn_add.png');?>
<?php \Pasteque\tpl_btn('btn', \Pasteque\get_module_url_action(PLUGIN_NAME, "productsManagement"),
\i18n('Import product from csv', PLUGIN_NAME), 'img/btn_add.png');?>
<p><?php \pi18n("%d products", PLUGIN_NAME, count($products)); ?></p>
......@@ -66,7 +70,10 @@ $par = !$par;
<td><?php echo $product->reference; ?></td>
<td><?php echo $product->label; ?></td>
<td class="edition">
<a href="<?php echo \Pasteque\get_module_url_action(PLUGIN_NAME, 'product_edit', array('id' => $product->id)); ?>"><img src="<?php echo \Pasteque\get_template_url(); ?>img/edit.png" alt="<?php \pi18n('Edit'); ?>" title="<?php \pi18n('Edit'); ?>"></a>
<?php \Pasteque\tpl_btn('edition', \Pasteque\get_module_url_action(
PLUGIN_NAME, 'product_edit', array("id" => $product->id)), "",
'img/edit.png', \i18n('Edit'), \i18n('Edit'));
?>
<form action="<?php echo \Pasteque\get_current_url(); ?>" method="post"><?php \Pasteque\form_delete("product", $product->id, \Pasteque\get_template_url() . 'img/delete.png') ?></form>
</td>
</tr>
......@@ -114,7 +121,7 @@ $par = !$par;
<?php
if (count($products) == 0) {
?>
<div class="alert"><?php \pi18n("No product found", PLUGIN_NAME); ?></div>
<div class="alert"><?php \pi18n("No product found", PLUGIN_NAME);?></div>
<?php
}
?>
<?php
namespace BaseProducts;
// open csv return null if the file selected had not extension "csv"
// or user not selected file
function init_csv() {
if ($_FILES['csv']['tmp_name'] === NULL) {
return NULL;
}
$ext = strchr($_FILES['csv']['type'], "/");
$ext = strtolower($ext);
if($ext !== "/csv") {
return NULL;
}
$key = array('reference', 'barcode', 'label', 'price_buy', 'price_sell',
'category', 'tax_cat');
$optionKey = array('visible', 'scaled', 'disp_order', 'discount_rate',
'discount_enabled');
$optionKey = array();
$csv = new \Pasteque\Csv($_FILES['csv']['tmp_name'], $key, $optionKey);
if (!$csv->open()) {
return $csv;
}
$csv->addFilter("reference", NULL);
$csv->addFilter("barcode", NULL);
$csv->addFilter("price_buy", NULL);
$csv->addFilter("price_sell", NULL);
$csv->addFilter("category", NULL);
$csv->addFilter("label", NULL);
$csv->addFilter("tax_cat", NULL);
$csv->addFilter("visible", true);
$csv->addFilter("scaled", false);
$csv->addFilter("disp_order", "0");
return $csv;
}
// return an array whith all key set
function initArray($key, $tab) {
$array = array_fill_keys($key, NULL);
$array['visible'] = true;
$array['scaled'] = false;
$tab['disp_order'] = 0;
foreach ($tab as $field => $value) {
$array[$field] = $value;
}
return $array;
}
function import_csv($csv) {
$error = 0;
$create = 0;
$update = 0;
$error_mess = array();
while ($tab = $csv->readLine()) {
//init optionnal values
$AllKeyPossible = array_merge($csv->getKey(), $csv->getOptionalKey());
$tab = initArray($AllKeyPossible, $tab);
//check
$category = \Pasteque\CategoriesService::getByName($tab['category']);
$tax_cat = \Pasteque\Taxesservice::getByName($tab['tax_cat']);
if ($tax_cat && $category) {
$prod = new \Pasteque\Product($tab['reference'], $tab['label'],
$tab['price_sell'], $category, $tab['disp_order'],
$tax_cat, $tab['visible'], $tab['scaled']);
// manage optional value may be present in $tab
$prod = manage_header_option($prod, $tab);
$product_exist= \Pasteque\ProductsService::getByRef($prod->reference);
//UPDATE product
if ($product_exist !== NULL ) {
$prod->id = $product_exist->id;
$prod = mergeProduct($product_exist, $prod);
//if update imposible an is occurred
if (!\Pasteque\ProductsService::update($prod)) {
$error++;
$error_mess[] = \i18n("On line %d: Cannot update product: '%s'", PLUGIN_NAME,
$csv->getCurrentLineNumber(), $tab['label']);
} else {
// update stock_curr and stock_diary
manage_stock_level($prod->id, $tab, FALSE);
$update++;
}
//CREATE product
} else {
$id = \Pasteque\ProductsService::create($prod);
if ($id) {
//create stock_curr and stock diary
manage_stock_level($id, $tab, TRUE);
$create++;
} else {
$error++;
$error_mess[] = \i18n("On line %d: Cannot create product: '%s'", PLUGIN_NAME,
$csv->getCurrentLineNumber(), $tab['label']);
}
}
// category or tax_category doesn't exist
} else {
$error++;
if (!$category) {
$error_mess[] = \i18n("On line %d category: '%s' doesn't exist", PLUGIN_NAME,
$csv->getCurrentLineNumber(), $tab['category']);
}
if (!$tax_cat) {
$error_mess[] = \i18n("On line %d: Tax category: '%s' doesn't exist", PLUGIN_NAME,
$csv->getCurrentLineNumber(), $tab['tax_cat']);
}
}
}
$message = \i18n("%d line(s) inserted, %d line(s) modified, %d error(s)", PLUGIN_NAME,
$create, $update, $error);
\Pasteque\tpl_msg_box($message, $error_mess);
}
// add to product values not obligatory may be present in array
function manage_header_option($product, $array) {
if (isset($array['barcode'])) {
$product->barcode = $array['barcode'];
}
if (isset($array['price_buy'])) {
$product->price_buy = $array['price_buy'];
}
if (isset($array['discount_enabled'])) {
$product->discount_enabled = $array['discount_enabled'];
}
if (isset($array['discount_rate'])) {
$product->discount_rate = $array['discount_rate'];
}
if (isset($array['attributes_set'])) {
$product->attributes_set = $array['attributes_set'];
}
return $product;
}
/** Manage stockDiary and stockCurr whith id and location by default:"Principal"
* check if fields 'stock_min' and 'stock_max' are set in array
* if $create is true create a new entry in stockDiary and stockCurr in BDD
* else update stockDiarry and stockCurr.
*/
function manage_stock_level($id, $array, $create) {
$stockLevel = new \Pasteque\StockLevel($id, "Principal", NULL, NULL);
if (isset($array['stock_min'])) {
$stockLevel->security = $array['stock_min'];
}
if (isset($array['stock_max'])) {
$stockLevel->max = $array['stock_max'];
}
if ($create) {
\Pasteque\StocksService::createLevel($stockLevel);
} else {
\Pasteque\StocksService::updateLevel($stockLevel);
}
return $stockLevel;
}
/* merge the old field values of product to new product
* if the fields corresponding are not set */
function mergeProduct($old, $new) {
if (!isset($new->barcode)) {
$new->barcode = $old->barcode;
}
if (!isset($new->price_buy)) {
$new->price_buy = $old->price_buy;
}
if (!isset($new->image)) {
$new->image = $old->image;
}
if (!isset($new->discount_enabled)) {
$new->discount_enabled = $old->discount_enabled;
}
if (!isset($new->discount_rate)) {
$new->discount_rate = $old->discount_rate;
}
if (!isset($new->attributes_set)) {
$new->attributes_set = $old->attributes_set;
}
return $new;
}
?>
<?php
if (isset($_FILES['csv'])) {
$dateStr = isset($_POST['date']) ? $_POST['date'] : \i18nDate(time());
$dateStr = \i18nRevDate($dateStr);
$date = \Pasteque\stdstrftime($dateStr);
$csv = init_csv();
if ($csv === NULL) {
\Pasteque\tpl_msg_box(NULL, \i18n("Selected file empty or bad format", PLUGIN_NAME));
} else if (!$csv->isOpen()) {
$err = array();
foreach ($csv->getErrors() as $mess) {
$err[] = \i18n($mess);
}
\Pasteque\tpl_msg_box(NULL, $err);
} else {
import_csv($csv, $date);
}
}
?>
<h1><?php \pi18n("Import products from csv file", PLUGIN_NAME); ?></h1>
<form method="post" action="<?php echo \Pasteque\get_module_url_action(PLUGIN_NAME, 'productsManagement');?>" enctype="multipart/form-data">
<?php \pi18n("File", PLUGIN_NAME) ?>: <input type="file" name="csv">
<input type="submit" name="envoyer" value=<?php \pi18n("send", PLUGIN_NAME)?>>
</form>
......@@ -32,6 +32,8 @@
"File": "Fichier",
"send": "send",
"Selected file empty or bad format": "Selected file empty or bad format",
"%d line(s) inserted, %d line(s) modified, %d error(s)": "%d line(s) inserted, %d line(s) modified, %d error(s)",
"Only empty category can be deleted": "Only empty category can be deleted",
"Import category": "Import category",
......@@ -39,6 +41,12 @@
"On line %d: Cannot create category: '%s'": "On line %d: Cannot create category: '%s'",
"On line %d: Cannot update category: '%s'": "On line %d: Cannot update category: '%s'",
"On line %d: Category parent doesn't exist": "On line %d: Category parent doesn't exist",
"%d line(s) inserted, %d line(s) modified, %d error(s)": "%d line(s) inserted, %d line(s) modified, %d error(s)",
"Selected file empty or bad format": "Selected file empty or bad format"
"Import products": "Import products",
"Import products from csv": "Import products from csv",
"On line %d: Cannot create product: '%s'": "On line %d: Cannot create product: '%s'",
"On line %d: Cannot update update: '%s'": "On line %d: Cannot update update: '%s'",
"On line %d: Tax category: '%s' doesn't exist": "On line %d: Tax category: '%s' doesn't exist",
"On line %d category: '%s' doesn't exist": "On line %d category: '%s' doesn't exist"
}
......@@ -31,6 +31,8 @@
"send": "envoyer",
"File": "Fichier",
"Selected file empty or bad format": "Aucun fichier sélectionné ou mauvais format",
"%d line(s) inserted, %d line(s) modified, %d error(s)": "%d ligne(s) inserée(s), %d ligne(s) modifiée(s), %d erreur(s)",
"Only empty category can be deleted": "Une catégorie non vide ne peut être supprimée",
"Import categories": "Importer des catégories",
......@@ -38,8 +40,9 @@
"On line %d: Cannot update category: '%s'": "À la ligne %d: Impossible de mettre à jour la category: '%s'",
"On line %d: Cannot create product: '%s'": "À la ligne %d: Impossible de créer le produit: '%s'",
"On line %d: Category parent doesn't exist": "À la ligne %d: La categorie parent n'existe pas",
"Cannot open file": "Impossible d'ouvrir le fichier",
"%d line(s) inserted, %d line(s) modified, %d error(s)": "%d ligne(s) inserée(s), %d ligne(s) modifiée(s), %d erreur(s)",
"Selected file empty or bad format": "Aucun fichier sélectionné ou mauvais format"
"On line %d: Cannot create product: '%s'": "À la ligne %d: Impossible de créer le produit: '%s'",
"On line %d: Cannot update update: '%s'": "À la ligne %d: Impossible de mettre a jour le produit: '%s'",
"On line %d: Category parent doesn't exist": "À la ligne %d: La categorie parent n'existe pas",
"On line %d: Tax category: '%s' doesn't exist": "À la ligne %d: La categorie de taxe: '%s' n'existe pas"
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment