public function test_update() { /** === Test Data === */ $MAGE_ID = 1234; $NAME = 'product name'; $IS_ACTIVE = true; $PRICE = 43.21; $WEIGHT = 54.321; /** === Setup Mocks === */ // $product = $this->_mageRepoProd->getById($mageId); $mProduct = $this->_mock(\Magento\Catalog\Api\Data\ProductInterface::class); $this->mMageRepoProd->shouldReceive('getById')->once()->andReturn($mProduct); $mProduct->shouldReceive('setName', 'setStatus', 'setPrice', 'setWeight'); // $this->_mageRepoProd->save($product); $this->mMageRepoProd->shouldReceive('save')->once(); /** === Call and asserts === */ $this->obj->update($MAGE_ID, $NAME, $IS_ACTIVE, $PRICE, $WEIGHT); }
/** * Update product * * @param int $id Id of product to update * @param array $request_data Datas * @return int * * @url PUT product/{id} */ function put($id, $request_data = NULL) { if (!DolibarrApiAccess::$user->rights->produit->creer) { throw new RestException(401); } $result = $this->product->fetch($id); if (!$result) { throw new RestException(404, 'Product not found'); } if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { $this->product->{$field} = $value; } if ($this->product->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) { return $this->get($id); } return false; }
function import2Dolibarr($object, $typeimport) { global $conf; global $langs; $this->process_msg = ''; $error = 0; $fp = @fopen($this->filename, "r"); if ($fp) { switch ($object) { case 'ImportStock': $doliprod = new Product($this->db); $i = 0; while ($ligne = fgetcsv($fp, 1000, ";")) { $doliprod->id = ''; $i++; if ($this->firstline && $i == 1) { continue; } if ($conf->global->IMPORT_BARCODE) { $ligne[0] = $this->get_product_by_barcode($ligne[0]); } if ($doliprod->fetch('', $ligne[0]) <= 0) { $this->process_msg .= $langs->trans("ErrProdNoExist", $ligne[0], $doliprod->error) . "\n"; } else { $pid = $doliprod->id; $doliprod->ref = $ligne[0]; $entrepot = $ligne[1]; $newstock = $ligne[2]; $price = $ligne[3]; if ($conf->global->IMPORT_TOTAL_STOCK) { $doliprod->load_stock(); dol_syslog("stock produit " . $doliprod->stock_warehouse[$entrepot]->real . " entrepot " . $entrepot . " " . $doliprod->stock_reel, LOG_DEBUG); // correction de stock $delta = 0; if ($newstock > $doliprod->stock_warehouse[$entrepot]->real) { $delta = $newstock - $doliprod->stock_warehouse[$entrepot]->real; $sens = 0; } elseif ($newstock < $doliprod->stock_warehouse[$entrepot]->real) { $delta = $doliprod->stock_warehouse[$entrepot]->real - $newstock; $sens = 1; } if ($delta) { $res = $doliprod->correct_stock($this->user, $entrepot, $delta, $sens, $langs->trans("StockCorrection"), $price); if ($res < 0) { $this->process_msg .= $langs->trans("ErrMovStock", $ligne[0], $doliprod->error) . "\n"; $error++; } } dol_syslog("maj stock delta = " . $delta . " sens " . $sens, LOG_DEBUG); } else { $res = $doliprod->correct_stock($this->user, $entrepot, abs($newstock), $newstock > 0 ? 0 : 1, $langs->trans("StockCorrection"), $price); if ($res < 0) { $this->process_msg .= $langs->trans("ErrMovStock", $ligne[0], $doliprod->error) . "\n"; $error++; } } } } break; case 'ImportProduct': //$doliprod = new Product($this->db); $i = 0; while ($ligne = fgetcsv($fp, 1000, ";")) { $i++; $doliprod = new Product($this->db); $doliprod->id = ''; if ($this->firstline && $i == 1) { continue; } if ($doliprod->fetch('', $ligne[0]) < 0) { $this->process_msg .= $langs->trans("ErrProdNoExist", $ligne[0], $doliprod->error) . "\n"; } else { $pid = $doliprod->id; $doliprod->ref = $ligne[0]; if (!empty($ligne[1])) { $doliprod->libelle = $ligne[1]; } if (!empty($ligne[2])) { $doliprod->status = $ligne[2]; } $doliprod->status_buy = 1; if (!empty($ligne[3])) { $doliprod->description = $ligne[3]; } if (!empty($ligne[4])) { $doliprod->price = $ligne[4]; } if (!empty($ligne[5])) { $doliprod->tva_tx = $ligne[5]; } if (!empty($ligne[6])) { $doliprod->weight = $ligne[6]; } if (!empty($ligne[7])) { $doliprod->volume = $ligne[7]; } if (!empty($ligne[9])) { $doliprod->barcode = $ligne[9]; } if (!empty($ligne[9])) { $doliprod->barcode_type = dol_getIdFromCode($this->db, $ligne[10], 'c_barcode_type', 'libelle', 'rowid'); } if (!empty($ligne[10])) { $doliprod->type = $ligne[11]; } $doliprod->price_base_type = 'HT'; $this->db->begin; switch ($typeimport) { case 'C': if ($pid > 0) { if ($doliprod->update($pid, $this->user) < 0) { $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error) . "\n"; $error++; } if ($doliprod->updatePrice($doliprod->price, $doliprod->price_base_type, $this->user) < 0) { $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error) . "\n"; $error++; } } else { if ($doliprod->create($this->user) < 0) { $this->process_msg .= $langs->trans("ErrProductCreate", $ligne[0], $doliprod->error) . "\n"; $error++; } else { // image et code barre if ($ligne[8]) { $this->add_photo_web($conf->produit->dir_output, $ligne[8], $doliprod->id); } /*if ($ligne[9]) { if ($doliprod->setValueFrom('fk_barcode_type', 2) < 0){ $this->process_msg .= $langs->trans("ErrProductCreate", $ligne[0], $doliprod->error)."\n"; // TODO paramétrer $error++; } if ($doliprod->setValueFrom('barcode', $ligne[9]) < 0 ){ $this->process_msg .= $langs->trans("ErrProductCreate", $ligne[0], $doliprod->error)."\n"; $error++; } }*/ } } break; /*case 'M': if ($pid>0) { if ($doliprod->update($pid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } if (version_compare(DOL_VERSION, 3.5) >= 0){ if ($doliprod->updatePrice($doliprod->price, $doliprod->price_base_type, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } } else{ if ($doliprod->updatePrice($doliprod->id, $doliprod->price, $doliprod->price_base_type, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ErrProdNoExist", $ligne[0])."\n"; break;*/ /*case 'M': if ($pid>0) { if ($doliprod->update($pid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } if (version_compare(DOL_VERSION, 3.5) >= 0){ if ($doliprod->updatePrice($doliprod->price, $doliprod->price_base_type, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } } else{ if ($doliprod->updatePrice($doliprod->id, $doliprod->price, $doliprod->price_base_type, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrProductUpdate", $ligne[0], $doliprod->error)."\n"; $error++; } } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ErrProdNoExist", $ligne[0])."\n"; break;*/ case 'D': if ($pid > 0) { if ($doliprod->delete($pid) < 0) { $this->process_msg .= $langs->trans("ErrProductDelete", $ligne[0], $doliprod->error) . "\n"; $error++; } } else { $this->process_msg .= $langs->trans("Untreated", $i) . ' ' . $langs->trans("ErrProdNoExist", $ligne[0]) . "\n"; } } if (!$error) { $this->db->commit(); } else { $this->db->rollback(); } } } // while break; case 'ImportThirtdparty': $i = 0; //$societe = new Societe($this->db); while ($ligne = fgetcsv($fp, 1000, ";")) { $i++; $societe = new Societe($this->db); if ($this->firstline && $i == 1) { continue; } if (!$ligne[0]) { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrNameRequired") . "\n"; continue; } // vérifier par code_client if ($ligne[13]) { $sid = $this->get_socbyclientcode($ligne[13]); } else { if ($ligne[14]) { $sid = $this->get_socbysuplliercode($ligne[14]); } } if ($sid > 0) { $societe->fetch($sid); } else { $sid = $societe->fetch('', $ligne[0]); } if ($ligne[12]) { $pid = dol_getIdFromCode($this->db, $ligne[12], "c_pays", "code", "rowid"); } else { $pid = ''; } if ($pid <= 0) { $pid = ''; } $did = ''; $societe->id = $sid; $societe->name = $ligne[0]; $societe->particulier = 0; //Société $societe->address = $ligne[1] . "\n" . $ligne[2] . "\n" . $ligne[3]; $societe->zip = $ligne[4]; $societe->town = $ligne[5]; $societe->state_id = $did; if ($ligne[12]) { $societe->country_code = $ligne[12]; } $societe->country_id = $pid; dol_syslog("codes {$pid} " . $lige[12], LOG_DEBUG); $societe->phone = $ligne[6]; $societe->fax = $ligne[7]; $societe->email = $ligne[8]; $societe->url = $ligne[9]; $societe->idprof1 = $ligne[10]; switch ($ligne[11]) { case '0': $societe->fournisseur = 0; $societe->client = $ligne[11]; break; case '1': $societe->fournisseur = 0; $societe->client = $ligne[11]; break; case '2': $societe->fournisseur = 0; $societe->client = $ligne[11]; break; case '10': $societe->client = 0; $societe->fournisseur = 1; break; default: break; } if ($ligne[13]) { $societe->code_client = $ligne[13]; } if ($ligne[14]) { $societe->code_fournisseur = $ligne[14]; } /*if ($ligne[15]) $societe->array_options["options_zone"]=$ligne[15]; if (!empty($ligne[16])) $societe->array_options["options_CA"]=$ligne[16]; if (!empty($ligne[17])) { if ($ligne[17] <= 5) $societe->effectif_id = 1; elseif ($ligne[17] <= 10) $societe->effectif_id = 2; elseif ($ligne[17] <= 50) $societe->effectif_id = 3; elseif ($ligne[17] <= 100) $societe->effectif_id = 4; elseif ($ligne[17] <= 500) $societe->effectif_id = 5; else $societe->effectif_id = 7; } dol_syslog("effectif " . $lige[17].' '.$societe->effectif_id." ".print_r($societe->array_options, true), LOG_DEBUG);*/ $this->db->begin; switch ($typeimport) { case 'C': if ($sid > 0) { if ($societe->update($sid, $this->user) < 0) { $this->process_msg .= $langs->trans("ErrCompanyUpdate", $ligne[0], $societe->error) . "\n"; $error++; } } elseif ($societe->create($this->user) < 0) { $this->process_msg .= $langs->trans("ErrCompanyCreate", $ligne[0], $societe->error) . "\n"; $error++; } break; /*case 'M': if ($sid>0) { if ($societe->update($sid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrCompanyUpdate", $ligne[0], $societe->error)."\n"; $error++; } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("CompanyNoExist", $ligne[0])."\n"; break;*/ /*case 'M': if ($sid>0) { if ($societe->update($sid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrCompanyUpdate", $ligne[0], $societe->error)."\n"; $error++; } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("CompanyNoExist", $ligne[0])."\n"; break;*/ case 'D': if ($sid > 0) { if ($societe->delete($sid) < 0) { $this->process_msg .= $langs->trans("ErrCompanyDelete", $ligne[0], $societe->error) . "\n"; $error++; } } else { $this->process_msg .= $langs->trans("Untreated", $i) . ' ' . $langs->trans("CompanyNoExist", $ligne[0]) . "\n"; } } if (!$error) { $this->db->commit(); } else { $this->db->rollback(); } } break; case 'ImportContact': $i = 0; //$contact=new Contact($this->db); //$societe = new Societe($this->db); while ($ligne = fgetcsv($fp, 1000, ";")) { $i++; $contact = new Contact($this->db); $societe = new Societe($this->db); if ($this->firstline && $i == 1) { continue; } //if ($societe->fetch('',$ligne[0]) < 0 ) $this->process_msg .= "erreur lecture Société "."\n"; if ($ligne[0]) { $socid = $this->get_socbyclientcode($ligne[0]); } else { if ($ligne[1]) { $socid = $this->get_socbysuplliercode($ligne[1]); } } if ($socid < 0) { $this->process_msg .= $i . " " . $langs->trans("ErrCompanyRequired") . "\n"; } else { $societe->fetch($socid); } if (!$societe->id) { $this->process_msg .= $langs->trans("ErrCompanyNoExist", $ligne[0] . " " . $ligne[1]) . "\n"; continue; } if (empty($ligne[2])) { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrNameRequired") . "\n"; continue; } $contactid = $this->get_contact_id($socid, $ligne[2], $ligne[3]); $contact->id = $contactid; $contact->civilite_id = $ligne[4]; $contact->lastname = $ligne[2]; $contact->firstname = $ligne[3]; if ($ligne[5] || $ligne[6] || $ligne[7]) { $contact->address = $ligne[5] . "\n" . $ligne[6] . "\n" . $ligne[7]; } else { $contact->address = $societe->address; } if ($ligne[8]) { $contact->zip = $ligne[8]; } else { $contact->zip = $societe->zip; } if ($ligne[9]) { $contact->town = $ligne[9]; } else { $contact->town = $societe->town; } if ($ligne[10]) { $pid = dol_getIdFromCode($this->db, $ligne[10], "c_pays", "code", "rowid"); if ($pid <= 0) { $pid = ''; } $contact->country_id = $pid; $contact->country_code = $ligne[10]; } else { $contact->country_id = $societe->country_id; $contact->country_code = $societe->country_code; } $contact->socid = $socid; // fk_soc $contact->status = 1; $contact->email = $ligne[11]; $contact->phone_pro = $ligne[12]; $contact->fax = $ligne[13]; $contact->phone_mobile = $ligne[14]; $contact->priv = 0; $this->db - begin; switch ($typeimport) { case 'C': if ($contactid > 0) { if ($contact->update($contactid, $this->user) < 0) { $this->process_msg .= $langs->trans("ErrContactUpdate", $ligne[2], $contact->error) . "\n"; $error++; } } elseif ($contact->create($this->user) < 0) { $this->process_msg .= $langs->trans("ErrContactCreate", $ligne[2], $contact->error) . "\n"; $error++; } break; /*case 'M': if ($contactid>0) { if ($contact->update($contactid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrContactUpdate", $ligne[2], $contact->error)."\n"; $error++; } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ContactNoExist", $ligne[2])."\n"; break;*/ /*case 'M': if ($contactid>0) { if ($contact->update($contactid, $this->user) < 0){ $this->process_msg .= $langs->trans("ErrContactUpdate", $ligne[2], $contact->error)."\n"; $error++; } } else $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ContactNoExist", $ligne[2])."\n"; break;*/ case 'D': if ($contactid > 0) { if ($contact->delete($contactid) < 0) { $this->process_msg .= $langs->trans("ErrContactDelete", $ligne[2], $contact->error) . "\n"; $error++; } } else { $this->process_msg .= $langs->trans("Untreated", $i) . ' ' . $langs->trans("ContactNoExist", $ligne[2]) . "\n"; } } if (!$error) { $this->db->commit(); } else { $this->db->rollback(); } } break; /*case 'ImportActions': $i=0; $contact=new Contact($this->db); $societe = new Societe($this->db); $actioncomm = new ActionComm($this->db); $actuser = new User($this->db); while ($ligne = fgetcsv($fp,1000,";")) { $i++; if ($this->firstline && $i== 1) continue; //if ($societe->fetch('',$ligne[0]) < 0 ) $this->process_msg .= "erreur lecture Société "."\n"; //else $socid = $societe->id; $socid = $this->get_socbyclientcode($ligne[0]); if ($socid < 0 ) $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ErrCompanyRequired")."\n"; else $societe->fetch($socid); $socid = $societe->id; if (!$socid) { $this->process_msg .= $langs->trans("ErrCompanyNoExist", $ligne[0])."\n"; continue; } //action sur un contact de la soc if ($ligne[1]) { $contactid = $this->get_contact_id($socid, $ligne[1], $ligne[2]) ; if ($contactid < 0) { $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ContactNoExist", $ligne[1].' '. $ligne[2])."\n"; // réinitialiser ?? continue; } else $contact->fetch($contactid); } $usertodo = ''; if ($ligne[9]) { $usertodo=new User($this->db); if ( $usertodo->fetch('',$ligne[9]) < 0 ) $this->process_msg .= $langs->trans("ErrUserNoExist", $ligne[9])."\n"; } $userdone= '' ; if ($ligne[10]) { $usertodo=new User($this->db); if ( $usertodo->fetch('',$ligne[10]) < 0 ) $this->process_msg .= $langs->trans("ErrUserNoExist", $ligne[10])."\n"; } $datep = ''; if ($ligne[6]) { // voir date $n = sscanf($ligne[6],"%02d/%02d/%04d", $d_day, $d_mon, $d_year); if ($n==3) $datep=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year); if (!$datep) $this->process_msg .= $langs->trans("ErrDateConversion", $ligne[6])."\n"; } else $datep =''; $datef=''; if ($ligne[7]) { // voir la date $n = sscanf($ligne[7],"%02d/%02d/%04d", $d_day, $d_mon, $d_year); if ($n==3)$datef=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year); if (!$datef) $this->process_msg .= $langs->trans("ErrDateConversion", $ligne[7])."\n"; } else $datef =''; //$datef=''; $actioncomm->societe = $societe; if ($ligne[1]) $actioncomm->contact = $contact; else $actioncomm->contact = ''; $actioncomm->type_code = $ligne[3]; $actioncomm->priority = $ligne[4]; $actioncomm->location = '' ; $actioncomm->label = $ligne[5]; $actioncomm->datep = $datep; $actioncomm->datef = $datef; $actioncomm->percentage = $ligne[8]; $actioncomm->usertodo = $usertodo; $actioncomm->userdone = $userdone; $actioncomm->note =$ligne[11]; switch ($typeimport) { case 'C': $this->db->begin(); if ($actioncomm->add($this->user) < 0) { $this->process_msg .= $langs->trans("ErrActionCreate", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; case 'M': $this->db->begin(); if($actioncomm->update($user) < 0){ $this->process_msg .= $langs->trans("ErrActionUpdate", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; case 'D': $this->db->begin(); if($actioncomm->delete() < 0){ $this->process_msg .= $langs->trans("ErrActionDelete", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; } } break;*/ /*case 'ImportActions': $i=0; $contact=new Contact($this->db); $societe = new Societe($this->db); $actioncomm = new ActionComm($this->db); $actuser = new User($this->db); while ($ligne = fgetcsv($fp,1000,";")) { $i++; if ($this->firstline && $i== 1) continue; //if ($societe->fetch('',$ligne[0]) < 0 ) $this->process_msg .= "erreur lecture Société "."\n"; //else $socid = $societe->id; $socid = $this->get_socbyclientcode($ligne[0]); if ($socid < 0 ) $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ErrCompanyRequired")."\n"; else $societe->fetch($socid); $socid = $societe->id; if (!$socid) { $this->process_msg .= $langs->trans("ErrCompanyNoExist", $ligne[0])."\n"; continue; } //action sur un contact de la soc if ($ligne[1]) { $contactid = $this->get_contact_id($socid, $ligne[1], $ligne[2]) ; if ($contactid < 0) { $this->process_msg .= $langs->trans("Untreated", $i).' '.$langs->trans("ContactNoExist", $ligne[1].' '. $ligne[2])."\n"; // réinitialiser ?? continue; } else $contact->fetch($contactid); } $usertodo = ''; if ($ligne[9]) { $usertodo=new User($this->db); if ( $usertodo->fetch('',$ligne[9]) < 0 ) $this->process_msg .= $langs->trans("ErrUserNoExist", $ligne[9])."\n"; } $userdone= '' ; if ($ligne[10]) { $usertodo=new User($this->db); if ( $usertodo->fetch('',$ligne[10]) < 0 ) $this->process_msg .= $langs->trans("ErrUserNoExist", $ligne[10])."\n"; } $datep = ''; if ($ligne[6]) { // voir date $n = sscanf($ligne[6],"%02d/%02d/%04d", $d_day, $d_mon, $d_year); if ($n==3) $datep=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year); if (!$datep) $this->process_msg .= $langs->trans("ErrDateConversion", $ligne[6])."\n"; } else $datep =''; $datef=''; if ($ligne[7]) { // voir la date $n = sscanf($ligne[7],"%02d/%02d/%04d", $d_day, $d_mon, $d_year); if ($n==3)$datef=dol_mktime(12, 0, 0, $d_mon, $d_day, $d_year); if (!$datef) $this->process_msg .= $langs->trans("ErrDateConversion", $ligne[7])."\n"; } else $datef =''; //$datef=''; $actioncomm->societe = $societe; if ($ligne[1]) $actioncomm->contact = $contact; else $actioncomm->contact = ''; $actioncomm->type_code = $ligne[3]; $actioncomm->priority = $ligne[4]; $actioncomm->location = '' ; $actioncomm->label = $ligne[5]; $actioncomm->datep = $datep; $actioncomm->datef = $datef; $actioncomm->percentage = $ligne[8]; $actioncomm->usertodo = $usertodo; $actioncomm->userdone = $userdone; $actioncomm->note =$ligne[11]; switch ($typeimport) { case 'C': $this->db->begin(); if ($actioncomm->add($this->user) < 0) { $this->process_msg .= $langs->trans("ErrActionCreate", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; case 'M': $this->db->begin(); if($actioncomm->update($user) < 0){ $this->process_msg .= $langs->trans("ErrActionUpdate", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; case 'D': $this->db->begin(); if($actioncomm->delete() < 0){ $this->process_msg .= $langs->trans("ErrActionDelete", $ligne[5], $actioncomm->error)."\n"; $this->db->rollback(); } else $this->db->commit(); break; } } break;*/ case 'Importtarif': // ref four $i = 0; $this->process_msg = ''; $error = 0; /*$doliprod = new Product($this->db); $product = new ProductFournisseur($this->db); $societe = new Societe($this->db);*/ while ($ligne = fgetcsv($fp, 1000, ";")) { $doliprod->id = ''; $i++; $doliprod = new Product($this->db); $product = new ProductFournisseur($this->db); $societe = new Societe($this->db); if ($this->firstline && $i == 1) { continue; } // recherche du fournisseur if ($societe->fetch('', $ligne[2]) > 0) { $sid = $societe->id; } else { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrComppanyNoExist", $ligne[2]) . "\n"; $sid = ''; } if ($doliprod->fetch('', $ligne[0]) > 0) { $pid = $doliprod->id; } else { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrProductNoExist", $ligne[0], $doliprod->error) . "\n"; $pid = ''; } if ($sid > 0 && $pid > 0) { $result = $product->fetch($doliprod->id); if ($result > 0) { $this->db->begin(); switch ($typeimport) { case 'C': $ret = $product->add_fournisseur($this->user, $sid, $ligne[1], $ligne[3]); if ($ret < 0 && $ret != -3) { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrCreatePrice", $product->error) . "\n"; $error++; } $ret = $product->update_buyprice($ligne[3], $ligne[4], $this->user, 'HT', $supplier, '', $ligne[1], $ligne[5]); if ($ret < 0 && $ret != -3) { $this->process_msg .= $langs->trans("Untreated", $i) . " " . $langs->trans("ErrCreatePrice", $product->error) . "\n"; $error++; } break; /*case 'M': { // gestion du prix obligatoire $supplier=new Fournisseur($this->db); $result=$supplier->fetch($sid); $ret=$product->update_buyprice($ligne[3], $ligne[4] , $this->user, 'HT', $supplier, '', $ligne[1], $ligne[5] ); if ($ret < 0) { $this->process_msg .= $langs->trans("Untreated", $i)." ".$langs->trans("Qty").$ligne[3]. ", ".$langs->trans("Price").$ligne[4]." ".$langs->trans("ErrUpdatePrice", $product->error)."\n"; $error ++; } } break;*/ /*case 'M': { // gestion du prix obligatoire $supplier=new Fournisseur($this->db); $result=$supplier->fetch($sid); $ret=$product->update_buyprice($ligne[3], $ligne[4] , $this->user, 'HT', $supplier, '', $ligne[1], $ligne[5] ); if ($ret < 0) { $this->process_msg .= $langs->trans("Untreated", $i)." ".$langs->trans("Qty").$ligne[3]. ", ".$langs->trans("Price").$ligne[4]." ".$langs->trans("ErrUpdatePrice", $product->error)."\n"; $error ++; } } break;*/ case 'D': // suprresion de la ligne avec le même nb d'article et le même prix $sql = "SELECT pfp.rowid FROM " . MAIN_DB_PREFIX . "product_fournisseur_price as pfp"; $sql .= " WHERE pfp.quantity = '" . $ligne[3] . "' AND pfp.ref_fourn = '" . $ligne[1]; $sql .= "' AND pfp.fk_soc = '" . $sid . "' AND pfp.fk_product='" . $pid . "'"; $sql .= " AND pfp.entity = " . $conf->entity; $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); if ($obj->rowid > 0) { $result = $product->remove_product_fournisseur_price($obj->rowid); } else { $this->process_msg .= $langs->trans("Untreated", $i) . ' ' . $langs->trans("ErrDeletePrice", $product->error) . "\n"; $error++; } } else { $this->process_msg .= "Error SQL= " . $sql . "\n"; $error++; } break; } //switch } if (!$error) { $this->db->commit(); } else { $this->db->rollback(); } } // fournisseur trouvé } // traitement ligne // while reffour break; } // fin switch fclose($fp); } else { $this->error = $langs->trans("ErrOpenFile") . $nomfich; $error = -1; } return $error; }
public function postProcess($token = NULL) { global $currentIndex; /* Add a new product */ if (Tools::isSubmit('submitAddproduct') or Tools::isSubmit('submitAddproductAndStay')) { if ($this->tabAccess['add'] === '1') { $this->submitAddproduct($token); } elseif (Tools::getValue('id_product') and $this->tabAccess['edit'] === '1') { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete anything here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = intval(Tools::getValue($this->identifier))) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . $id . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateQuantityDiscount($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id)) { if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('an error occurred while copying images'); } else { Hook::addProduct($product); Search::indexation(false); Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('an error occurred while creating object'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } elseif ($id_image = intval(Tools::getValue('id_image')) and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); deleteImage($image->id_product, $image->id); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . intval($image->id_product)); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . intval($first_img['id_image'])); } @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $image->id_product . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm($token ? $token : $this->token); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Impossible to change the product cover'); } else { $productId = intval(Tools::getValue('id_product')); @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $productId . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage(intval(Tools::getValue('imgPosition')), intval(Tools::getValue('imgDirection'))); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!isset($_POST['attribute_quantity']) or $_POST['attribute_quantity'] == NULL) { $this->_errors[] = Tools::displayError('attribute quantity is required'); } if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('attribute price is required'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('you must add at least one attribute'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = intval(Tools::getValue('id_product_attribute'))) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('edit something here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['deleteProductAttribute'])) { if ($this->tabAccess['delete'] === '1') { if ($id_product = intval(Tools::getValue('id_product')) and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison(intval(Tools::getValue('id_product_attribute'))); $product->checkDefaultAttributes(); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . intval(Tools::getValue('id_category')) . '&tabs=2&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('impossible to delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(); foreach ($_POST as $key => $val) { if (preg_match("/^feature_([0-9]+)_value/i", $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding features'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } elseif (Tools::isSubmit('submitQuantityDiscount')) { $_POST['tabs'] = 5; if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!($id_discount_type = intval(Tools::getValue('id_discount_type')))) { $this->_errors[] = Tools::displayError('discount type not selected'); } else { if (!($quantity_discount = intval(Tools::getValue('quantity_discount')))) { $this->_errors[] = Tools::displayError('quantity is required'); } else { if (!($value_discount = floatval(Tools::getValue('value_discount')))) { $this->_errors[] = Tools::displayError('value is required'); } else { $qD = new QuantityDiscount(); $qD->id_product = $product->id; $qD->id_discount_type = $id_discount_type; $qD->quantity = $quantity_discount; $qD->value = $value_discount; if ($qD->add() and !sizeof($this->_errors) and $qD->validateFields()) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=3&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred while creating object'); } } } } else { $this->_errors[] = Tools::displayError('product must be created before adding quantity discounts'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } elseif (isset($_GET['deleteQuantityDiscount'])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (Validate::isLoadedObject($qD = new QuantityDiscount(intval(Tools::getValue('id_quantity_discount'))))) { $qD->delete(); if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('not a valid quantity discount'); } } else { $this->_errors[] = Tools::displayError('product must be created before delete quantity discounts'); } $qD = new QuantityDiscount(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$product->createLabels(intval($_POST['uploadable_files']) - intval($product->uploadable_files), intval($_POST['text_fields']) - intval($product->text_fields))) { $this->_errors[] = Tools::displayError('an error occured while creating customization fields'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('an error occured while updating customization'); } $product->uploadable_files = intval($_POST['uploadable_files']); $product->text_fields = intval($_POST['text_fields']); $product->customizable = (intval($_POST['uploadable_files']) > 0 or intval($_POST['text_fields']) > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('an error occured while updating customization configuration'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding customization possibilities'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('an error occured while updating customization'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding customization possibilities'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$this->deleteImage($product->id)) { $this->_errors[] = Tools::displayError('an error occurred during product image deletion'); } if ($product->delete()) { Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=1&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred during product deletion'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } else { parent::postProcess(true); } }
session_start(); require "../includes/checkPermission.php"; require "../../deny/connector.php"; require "class/class.Product.php"; require "../includes/injection.php"; require "../../includes/trackXML.php"; $cate = sqlInjection($_POST['CateID']); $lable = sqlInjection($_POST['Lable']); $price = sqlInjection($_POST['Price']); $artist = sqlInjection($_POST['Artist']); $producer = sqlInjection($_POST['Producer']); $year = sqlInjection($_POST['pubYear']); $disktype = sqlInjection($_POST['DiskType']); $description = sqlInjection($_POST['Description']); $tracklist = ""; $image = sqlInjection($_POST['proImage']); $status = sqlInjection($_POST['ProStatus']); $id = sqlInjection($_GET['pID']); $trck = new TrackXML(); $prod = new Product(); if (isset($_POST['trackname']) && isset($_POST['tracklength'])) { $tracklist = $trck->createXML($_POST['trackname'], $_POST['tracklength']); } /*echo $lable."<br>".$cate."<br>".$price ."<br>".$artist."<br>".$producer."<br>".$year."<br>".$disktype."<br>".$description ."<br>".$tracklist."<br>".$image."<br>".$status;*/ $prod->update($id, $lable, $cate, $price, $artist, $producer, $year, $disktype, $description, $tracklist, $image, $status); echo "<meta http-equiv='refresh' content='0;url=../admincp.php?opt=listproduct'>"; //header("location: ../admincp.php?opt=listproduct"); //exit();
} } $new_tags = implode(",", $new_tags); if (strlen($new_tags) <= 0) { $new_tags = $tags; } else { $new_tags = $new_tags . "," . $tags; } $product->description_short[1] = $new_tags; } else { $product->description_short[1] = $tags; } $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true); $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true); if (!empty($fieldError)) { $product->update(); } else { $errors[] = "<br/>{$id_product} : " . $langFieldError; } $count++; array_push($product_ids, $id_product); } fclose($f); SolrSearch::updateProducts($product_ids); echo "Total {$count} rows processed"; echo "<br/>"; echo "<a href='http://www.indusdiva.com/products/{$tagname}'>link</a>"; echo "<br/>" . "--------------------------------------------------"; echo "<br/>Errors"; echo implode("<br/>", $errors); exit;
if ($action == 'setstocklimit') { $object = new Product($db); $result = $object->fetch($id); $object->seuil_stock_alerte = $stocklimit; $result = $object->update($object->id, $user, 0, 'update'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } $action = ''; } // Set desired stock if ($action == 'setdesiredstock') { $object = new Product($db); $result = $object->fetch($id); $object->desiredstock = $desiredstock; $result = $object->update($object->id, $user, 0, 'update'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } $action = ''; } // Correct stock if ($action == "correct_stock" && !$cancel) { if (!(GETPOST("id_entrepot") > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $error++; $action = 'correction'; } if (!GETPOST("nbpiece")) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), null, 'errors'); $error++;
/** * postProcess handle every checks before saving products information * * @param mixed $token * @return void */ public function postProcess($token = null) { global $cookie, $currentIndex; // Add a new product if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) { if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')) { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitAddAttachments')) { if ($this->tabAccess['add'] === '1') { $languages = Language::getLanguages(false); $is_attachment_name_valid = false; foreach ($languages as $language) { $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']); if (strlen($attachment_name_lang) > 0) { $is_attachment_name_valid = true; } if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid Name'); } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) { $this->_errors[] = Tools::displayError('Name is too long'); } if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid description'); } } if (!$is_attachment_name_valid) { $this->_errors[] = Tools::displayError('Attachment Name Required'); } if (empty($this->_errors)) { if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) { if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) { $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb'); } else { do { $uniqid = sha1(microtime()); } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid)); if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) { $this->_errors[] = $this->l('File copy failed'); } @unlink($_FILES['attachment_file']['tmp_name']); } } elseif ((int) $_FILES['attachment_file']['error'] === 1) { $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $upload_mb = min($max_upload, $max_post); $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>'; } if (empty($this->_errors) && isset($uniqid)) { $attachment = new Attachment(); foreach ($languages as $language) { if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) { $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]); } if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) { $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]); } } $attachment->file = $uniqid; $attachment->mime = $_FILES['attachment_file']['type']; $attachment->file_name = pSQL($_FILES['attachment_file']['name']); if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 128) { $this->_errors[] = Tools::displayError('Invalid file extension'); } if (!Validate::isGenericName($attachment->file_name)) { $this->_errors[] = Tools::displayError('Invalid file name'); } if (Tools::strlen($attachment->file_name) > 128) { $this->_errors[] = Tools::displayError('File name too long'); } if (!sizeof($this->_errors)) { $attachment->add(); Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Invalid file'); } } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = (int) Tools::getValue($this->identifier)) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::addProduct($product); Search::indexation(false, $product->id); Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('An error occurred while creating object.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->toggleStatus()) { Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token); } else { $this->_errors[] = Tools::displayError('An error occurred while updating status.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; if ($this->deleted) { $object->deleteImages(); $object->deleted = 1; if ($object->update()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } } elseif ($object->delete()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } $this->_errors[] = Tools::displayError('An error occurred during deletion.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::getValue('submitDel' . $this->table)) { if ($this->tabAccess['delete'] === '1') { if (isset($_POST[$this->table . 'Box'])) { $object = new $this->className(); if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $result = true; if ($this->deleted) { foreach (Tools::getValue($this->table . 'Box') as $id) { $toDelete = new $this->className($id); $toDelete->deleted = 1; $result = $result and $toDelete->update(); } } else { $result = $object->deleteSelection(Tools::getValue($this->table . 'Box')); } if ($result) { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url); } $this->_errors[] = Tools::displayError('An error occurred while deleting selection.'); } } else { $this->_errors[] = Tools::displayError('You must select at least one element to delete.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { /* PrestaShop demo mode */ if (_PS_MODE_DEMO_) { $this->_errors[] = Tools::displayError('This functionnality has been disabled.'); return; } /* PrestaShop demo mode*/ if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $image->id_product); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . (int) $first_img['id_image']); } @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(false); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm(); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Cannot change the product cover'); } else { $productId = (int) Tools::getValue('id_product'); @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection')); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('Attribute price required.'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('You must add at least one attribute.'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) { $reason = new StockMvtReason((int) $id_reason); $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign; if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) { $this->_errors[] = Tools::displayError('An error occurred while updating qty.'); } } Hook::updateProductAttribute((int) $id_product_attribute); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } } } elseif (Tools::isSubmit('deleteProductAttribute')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute')); $product->checkDefaultAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if (!$product->hasAttributes()) { $product->cache_default_attribute = 0; $product->update(); } else { Product::updateDefaultAttribute($id_product); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('deleteAllProductAttributes')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteProductAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if ($product->cache_default_attribute) { $product->cache_default_attribute = 0; $product->update(); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attributes'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('defaultProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $product->deleteDefaultAttributes(); $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute')); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot make default attribute'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(false); foreach ($_POST as $key => $val) { if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding features.'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (Tools::isSubmit('submitPricesModification')) { $_POST['tabs'] = 5; if ($this->tabAccess['edit'] === '1') { $id_specific_prices = Tools::getValue('spm_id_specific_price'); $id_shops = Tools::getValue('spm_id_shop'); $id_currencies = Tools::getValue('spm_id_currency'); $id_countries = Tools::getValue('spm_id_country'); $id_groups = Tools::getValue('spm_id_group'); $prices = Tools::getValue('spm_price'); $from_quantities = Tools::getValue('spm_from_quantity'); $reductions = Tools::getValue('spm_reduction'); $reduction_types = Tools::getValue('spm_reduction_type'); $froms = Tools::getValue('spm_from'); $tos = Tools::getValue('spm_to'); foreach ($id_specific_prices as $key => $id_specific_price) { if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) { $specificPrice = new SpecificPrice((int) $id_specific_price); $specificPrice->id_shop = (int) $id_shops[$key]; $specificPrice->id_currency = (int) $id_currencies[$key]; $specificPrice->id_country = (int) $id_countries[$key]; $specificPrice->id_group = (int) $id_groups[$key]; $specificPrice->price = (double) $prices[$key]; $specificPrice->from_quantity = (int) $from_quantities[$key]; $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]); $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key]; $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key]; $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key]; if (!$specificPrice->update()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitPriceAddition')) { if ($this->tabAccess['add'] === '1') { $id_product = (int) Tools::getValue('id_product'); $id_shop = Tools::getValue('sp_id_shop'); $id_currency = Tools::getValue('sp_id_currency'); $id_country = Tools::getValue('sp_id_country'); $id_group = Tools::getValue('sp_id_group'); $price = Tools::getValue('sp_price'); $from_quantity = Tools::getValue('sp_from_quantity'); $reduction = (double) Tools::getValue('sp_reduction'); $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type'); $from = Tools::getValue('sp_from'); $to = Tools::getValue('sp_to'); if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) { $specificPrice = new SpecificPrice(); $specificPrice->id_product = $id_product; $specificPrice->id_shop = (int) $id_shop; $specificPrice->id_currency = (int) $id_currency; $specificPrice->id_country = (int) $id_country; $specificPrice->id_group = (int) $id_group; $specificPrice->price = (double) $price; $specificPrice->from_quantity = (int) $from_quantity; $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction); $specificPrice->reduction_type = $reduction_type; $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from; $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to; if (!$specificPrice->add()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('deleteSpecificPrice')) { if ($this->tabAccess['delete'] === '1') { if (!($obj = $this->loadObject())) { return; } if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) { $this->_errors[] = Tools::displayError('Invalid specific price ID'); } else { $specificPrice = new SpecificPrice((int) $id_specific_price); if (!$specificPrice->delete()) { $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitSpecificPricePriorities')) { if (!($obj = $this->loadObject())) { return; } if (!($priorities = Tools::getValue('specificPricePriority'))) { $this->_errors[] = Tools::displayError('Please specify priorities'); } elseif (Tools::isSubmit('specificPricePriorityToAll')) { if (!SpecificPrice::setPriorities($priorities)) { $this->_errors[] = Tools::displayError('An error occurred while updating priorities.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) { $this->_errors[] = Tools::displayError('An error occurred while setting priorities.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) { $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } $product->uploadable_files = (int) $_POST['uploadable_files']; $product->text_fields = (int) $_POST['text_fields']; $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('Label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['position'])) { if ($this->tabAccess['edit'] !== '1') { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (!Validate::isLoadedObject($object = $this->loadObject())) { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) { $this->_errors[] = Tools::displayError('Failed to update the position.'); } else { Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog')); } } else { parent::postProcess(true); } }
$name_img = $objImg->upload($_FILES, $_POST["photo_now"]); $objAttr = new AttrValue(); $data_attr = $objAttr->conbine($_POST["attr"], $_POST["val"]); if (isset($_POST["related"]) and $_POST["related"]) { $related = array_slice($_POST["related"], 0, 4); $data_related = serialize($related); } else { $data_related = ""; } require_once "classes/Product.php"; $obj = new Product(); if ($_POST["go"] == "save") { $fff = $obj->insert($obj->insertSql(), trimStr($_POST["section"]), trimStr($_POST["name"]), trimStr($_POST["nomer"]), trimStr($_POST["brand"]), trimStr($_POST["viscous"]), trimStr($_POST["type"]), trimStr($_POST["volume"]), trimStr($_POST["kol"]), trimStr($_POST["price"]), trimStr($_POST["text"]), $data_related, $data_attr, trimStr($_POST["title"]), trimStr($_POST["description"]), trimStr($_POST["keywords"]), $name_img, trimStr($_POST["img_title"]), trimStr($_POST["img_alt"])); header("Location: production.php?id=" . $_POST["section"]); } else { $obj->update($obj->updateSql(), trimStr($_POST["section"]), trimStr($_POST["name"]), trimStr($_POST["nomer"]), trimStr($_POST["brand"]), trimStr($_POST["viscous"]), trimStr($_POST["type"]), trimStr($_POST["volume"]), trimStr($_POST["kol"]), trimStr($_POST["price"]), trimStr($_POST["text"]), $data_related, $data_attr, trimStr($_POST["title"]), trimStr($_POST["description"]), trimStr($_POST["keywords"]), $name_img, trimStr($_POST["img_title"]), trimStr($_POST["img_alt"]), $_POST['go']); header("Location: production.php?id=" . $_POST["section"]); } } if (isset($_GET["delete"])) { $delete = new Delete(); $delete->del($_GET["title"], $_GET["delete"]); header("Location: production.php?id=" . $_GET["delete"]); } require_once "classes/Catalog.php"; $section = new Catalog(); require_once "classes/Product.php"; $objEdit = new Product(); $related = $objEdit->selectAll(); if (isset($_GET["edit"])) { $record = $objEdit->selectId($_GET['edit']);
/** * Updates a product on Prestashop. * * @param array $product_attributes * @param integer $id_product * @param string $url_photo * @param array $triple_cod_col_siz * @param integer $language * @param array $array_combinations * @return array * @see $this->isOldNameProductEgualToNewNameProduct * @see $this->isOldOrNewValueForProduct * @see $this->controlCategoriesForActivateTheir * @see $this->updateCombinantionsForPrestashop * */ public function updateProductForPrestashop($product_attributes = array(), $id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language = 1) { $product = new Product($id_product); $is_change_product = false; $new_name_product = trim($product_attributes["Nome"]); if (!$this->isOldNameProductEgualToNewNameProduct($product->name, $new_name_product)) { $product->name = $this->setArrayElementForLinkRewrite($new_name_product, true, $language); $product->meta_keywords = $new_name_product; $product->link_rewrite = $this->setArrayElementForLinkRewrite($new_name_product, false, $language); $is_change_product = true; } $new_price = (double) $product_attributes["Prezzo"]; if (!$this->isOldOrNewValueForProduct((double) $product->price, $new_price)) { $product->price = $new_price; $is_change_product = true; } $new_active = (int) $product_attributes["Attivo"]; $control_category = $this->isOldOrNewValueForProduct((int) $product->active, $new_active); if (!$control_category) { $product->active = $new_active; $is_change_product = true; } $new_minimal_quantity = (int) $product_attributes["Qta_min"]; if (!$this->isOldOrNewValueForProduct((int) $product->minimal_quantity, $new_minimal_quantity)) { $product->minimal_quantity = $new_minimal_quantity; $is_change_product = true; } $new_quantity = (int) $product_attributes["Qta"]; if (!$this->isOldOrNewValueForProduct((int) $product->getQuantity($id_product), $new_quantity)) { StockAvailable::setQuantity($id_product, 0, $new_quantity); } $array_old_features = $product->getFeatures(); $array_features = $product_attributes["Feature"]; $height = false; $width = false; foreach ($array_old_features as $array_old_single_features) { $feature = new FeatureCore((int) $array_old_single_features['id_feature']); $tmp_feature = $feature->name; $single_old_feature = $tmp_feature[$language]; $feature_value = new FeatureValueCore((int) $array_old_single_features["id_feature_value"]); $tmp_feature_value = $feature_value->value; $single_old_feature_value = $tmp_feature_value[$language]; if ($this->isOldOrNewValueForProduct("Altezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Altezza"] . " cm")) { $feature_value->value = array($language => $array_features["Altezza"] . " cm"); $feature_value->update(); $height = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Larghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Larghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Larghezza"] . " cm"); $feature_value->update(); $width = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Lunghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Lunghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Lunghezza"] . " cm"); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Modello", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Modello"])) { $feature_value->value = array($language => $array_features["Modello"]); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Linea", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Linea"])) { $feature_value->value = array($language => $array_features["Linea"]); $feature_value->update(); $is_change_product = true; } } } if ($height) { $product->height = (double) $array_features["Altezza"]; $is_change_product = true; } if ($width) { $product->width = (double) $array_features["Larghezza"]; $is_change_product = true; } if ($is_change_product) { $product->update(); } if (!$control_category) { $ids_categories_array = $product->getWsCategories(); $this->controlCategoriesForActivateTheir($ids_categories_array); } $change_new_image = $this->updateCombinantionsForPrestashop($id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language); $string_triple = array(); $return = array(); array_push($return, $product->id); $array_images_combinations_of_the_product = $product->getImages($language); $element = array(); foreach ($array_images_combinations_of_the_product as $array_combo_image) { $name_of_the_image = $array_combo_image['legend']; $id_image_of_the_product = $array_combo_image['id_image']; array_push($element, $id_image_of_the_product . ";" . $name_of_the_image); } array_push($return, $element); foreach ($change_new_image as $array_combo_image) { $fetch_tmp = explode(";", $array_combo_image); $fetch_jpg = explode(".jpg", $fetch_tmp[1]); $fetch_image_name = explode(",", $fetch_jpg[0]); array_push($string_triple, $fetch_image_name[2]); } array_push($return, $change_new_image); array_push($return, $string_triple); return $return; }
require_once "DataBase/Price.php"; $db_action = var_get_post("db_action", ""); $product = new Product(); $tax = new Tax(); $category = new Category(); $priceset = new Priceset(); $price = new Price(); $group = new Group(); switch ($db_action) { case "new": $product->create(var_post("product_id", ""), array(var_post("name", ""), var_post("details", ""), var_post("category_id", ""), var_post("tax_id", ""), var_post("available", ""), var_post("group_id", ""), var_post("order_number", ""), var_post("anmerkung", ""))); $priceset_list = $priceset->get(); for ($i = 0; $i < count($priceset_list); $i++) { $price->create(var_post("priceset_id_" . $i, ""), var_post("product_id", ""), array(var_post("priceset_price_" . $i, ""))); } break; case "edit": $product->update(var_post("product_id", ""), array(var_post("name", ""), var_post("details", ""), var_post("category_id", ""), var_post("tax_id", ""), var_post("available", ""), var_post("group_id", ""), var_post("order_number", ""), var_post("anmerkung", ""))); $priceset_list = $priceset->get(); for ($i = 0; $i < count($priceset_list); $i++) { if ($price->exists(var_post("priceset_id_" . $i, ""), var_post("product_id", ""))) { $price->update(var_post("priceset_id_" . $i, ""), var_post("product_id", ""), array(var_post("priceset_price_" . $i, ""))); } else { $price->create(var_post("priceset_id_" . $i, ""), var_post("product_id", ""), array(var_post("priceset_price_" . $i, ""))); } } break; case "delete": $product->delete(var_get("product_id", "")); break; }
/** * Update Product with user values */ public function updateOnPOST() { if (Tools::getValue('bettermasseditproduct')) { $POST = filter_input_array(INPUT_POST); $products = isset($POST['product']) ? $POST['product'] : array(); //there should be only one product, but in case there're more.. foreach ($products as $id_product => $product) { $product_obj = new Product($id_product); //update db and item in $items (to update form) $product_obj->price = (double) $product['price']; $product_obj->wholesale_price = (double) $product['wholesale_price']; //update combinations foreach ($product['attributes'] as $id_product_attribute => $pattr) { //update db $product_obj->updateAttribute($id_product_attribute, (double) $pattr['wholesale_price'], (double) $pattr['price'], $pattr['weight'], $pattr['unit_price_impact'], $pattr['ecotax'], array(), $pattr['reference'], $pattr['ean13'], $pattr['default_on']); } $product_obj->update(); return array('code' => 200, 'msg' => 'done'); } } else { return array('code' => 500, 'msg' => 'not POST request'); } }
public function hookadminOrder($params) { if (!$this->active) { return false; } global $currentIndex, $smarty; $table = 'order'; $token = Tools::safeOutput(Tools::getValue('token')); $errorShipping = 0; if ($currentIndex == '') { $currentIndex = 'index.php?controller=' . Tools::safeOutput(Tools::getValue('controller')); } $currentIndex .= "&id_order=" . (int) $params['id_order']; $carrierName = Db::getInstance()->getRow('SELECT c.external_module_name FROM `' . _DB_PREFIX_ . 'carrier` as c, `' . _DB_PREFIX_ . 'orders` as o WHERE c.id_carrier = o.id_carrier AND o.id_order = "' . (int) $params['id_order'] . '"'); if ($carrierName != null && $carrierName['external_module_name'] != $this->_moduleName) { return false; } if (!Configuration::get('TNT_CARRIER_LOGIN') || !Configuration::get('TNT_CARRIER_PASSWORD') || !Configuration::get('TNT_CARRIER_NUMBER_ACCOUNT')) { $var = array("error" => $this->l("You don't have a TNT account"), 'shipping_numbers' => '', 'sticker' => ''); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } if (!Configuration::get('TNT_CARRIER_SHIPPING_COMPANY') || !Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS1') || !Configuration::get('TNT_CARRIER_SHIPPING_ZIPCODE') || !Configuration::get('TNT_CARRIER_SHIPPING_CITY') || !Configuration::get('TNT_CARRIER_SHIPPING_EMAIL') || !Configuration::get('TNT_CARRIER_SHIPPING_PHONE') || !Configuration::get('TNT_CARRIER_SHIPPING_CLOSING')) { $errorShipping = 1; } if ($errorShipping) { $var = array("error" => $this->l("You didn't give a collect address in the TNT module configuration"), 'shipping_numbers' => '', 'sticker' => ''); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } $order = new Order($params['id_order']); $orderInfoTnt = new OrderInfoTnt((int) $params['id_order']); $info = $orderInfoTnt->getInfo(); if (is_array($info) && isset($info[3]) && (strlen($info[3]['option']) == 1 || substr($info[3]['option'], 1, 1) == 'S')) { $smarty->assign('weight', '30'); } else { $smarty->assign('weight', '20'); } $products = $order->getProducts(); $productWeight = array(); foreach ($products as $product) { $p = new Product($product['product_id']); if ((double) $p->weight == 0 && (!isset($_POST['product_weight_' . $product['product_id']]) || (double) $_POST['product_weight_' . $product['product_id']] <= 0)) { $productWeight[] = array('id' => $product['product_id'], 'name' => $product['product_name']); } else { if (isset($_POST['product_weight_' . $product['product_id']]) && (double) $_POST['product_weight_' . $product['product_id']] > 0) { $p->weight = (double) $_POST['product_weight_' . $product['product_id']]; $p->update(); } } } if (count($productWeight) > 0) { $var = array('currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); $smarty->assign('productWeight', $productWeight); return $this->display(__FILE__, 'tpl/weightForm.tpl'); } if (!is_array($info) && $info != false) { $var = array("error" => $info, "date" => '', "dateHidden" => '1', 'currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/formerror.tpl'); } $pack = new PackageTnt((int) $params['id_order']); if ($info[0]['shipping_number'] == '' && $pack->getOrder()->hasBeenShipped()) { $tntWebService = new TntWebService(); try { if (!isset($_POST['dateErrorOrder'])) { $orderInfoTnt->getDeleveryDate((int) $params['id_order'], $info); } $package = $tntWebService->getPackage($info); } catch (SoapFault $e) { $errorFriendly = ''; if (strrpos($e->faultstring, "shippingDate")) { $dateError = date("Y-m-d"); } if (strrpos($e->faultstring, "receiver")) { $receiverError = 1; $errorFriendly = $this->l('Can you please modify the field') . ' ' . substr($e->faultstring, strpos($e->faultstring, "receiver") + 9, strpos($e->faultstring, "'", strpos($e->faultstring, "receiver") - strpos($e->faultstring, "receiver")) + 1) . ' ' . $this->l('in the box "shipping address" below.'); } if (strrpos($e->faultstring, "sender")) { $senderError = 1; $errorFriendly = $this->l('Can you please modify the field') . ' ' . substr($e->faultstring, strpos($e->faultstring, "sender") + 7, strpos($e->faultstring, "'", strpos($e->faultstring, "sender") - strpos($e->faultstring, "sender")) + 1) . ' ' . $this->l('in your tnt module configuration.'); } $error = $this->l("Problem : ") . $e->faultstring; $var = array("error" => $error, "errorFriendly" => $errorFriendly, "date" => isset($dateError) ? $dateError : '', 'currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/formerror.tpl'); } if (isset($package->Expedition->parcelResponses->parcelNumber)) { $pack->setShippingNumber($package->Expedition->parcelResponses->parcelNumber); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'tnt_package_history` (`id_order`, `pickup_date`) VALUES ("' . (int) $params['id_order'] . '", "' . pSQL($info[2]['delivery_date']) . '")'); } else { foreach ($package->Expedition->parcelResponses as $k => $v) { $pack->setShippingNumber($v->parcelNumber); } } file_put_contents("../modules/" . $this->_moduleName . '/pdf/' . $pack->getOrder()->shipping_number . '.pdf', $package->Expedition->PDFLabels); } if ($pack->getShippingNumber() != '') { $var = array('error' => '', 'shipping_numbers' => $pack->getShippingNumber(), 'sticker' => "../modules/" . $this->_moduleName . '/pdf/' . $pack->getOrder()->shipping_number . '.pdf', 'date' => Db::getInstance()->getValue('SELECT `pickup_date` FROM `' . _DB_PREFIX_ . 'tnt_package_history` WHERE `id_order` = "' . (int) $params['id_order'] . '"'), 'relay' => isset($info[4]) ? $info[4]['name'] . '<br/>' . $info[4]['address'] . '<br/>' . $info[4]['zipcode'] . ' ' . $info[4]['city'] : '', 'place' => Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS1') . " " . Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS2') . "<br/>" . Configuration::get('TNT_CARRIER_SHIPPING_ZIPCODE') . " " . $this->putCityInNormeTnt(Configuration::get('TNT_CARRIER_SHIPPING_CITY'))); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } return false; }
/** * testProductUpdate * * @param Product $localobject Product * @return void * * @depends testProductFetch * The depends says test is run only if previous is ok */ public function testProductUpdate($localobject) { global $conf, $user, $langs, $db; $conf = $this->savconf; $user = $this->savuser; $langs = $this->savlangs; $db = $this->savdb; $localobject->note = 'New note after update'; $result = $localobject->update($localobject->id, $user); print __METHOD__ . " id=" . $localobject->id . " result=" . $result . "\n"; $this->assertLessThan($result, 0); return $localobject; }
public function setPayment($type) { $address_invoice = new Address((int) $this->context->cart->id_address_invoice); $country = new Country((int) $address_invoice->id_country); $currency = new Currency((int) $this->context->cart->id_currency); if (!$this->verifCountryAndCurrency($country, $currency)) { return false; } $klarna = new Klarna(); $klarnaInt = new KlarnaIntegration($klarna); $klarna->config(Configuration::get('KLARNA_STORE_ID_' . $this->countries[$country->iso_code]['name']), Configuration::get('KLARNA_SECRET_' . $this->countries[$country->iso_code]['name']), $this->countries[$country->iso_code]['code'], $this->countries[$country->iso_code]['langue'], $this->countries[$country->iso_code]['currency'], Configuration::get('KLARNA_MOD'), 'mysql', $this->_getDb()); if ($type == 'invoice' && Configuration::get('KLARNA_INVOICE_FEE_' . $this->countries[$country->iso_code]['name']) > 0 && !$this->isInCart($this->context->cart, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']))) { $this->context->cart->updateQty(1, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); $productInvoicefee = new Product((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); $productInvoicefee->addStockMvt(1, 1); $productInvoicefee->update(); } $this->initReservation($klarna, $this->context->cart, $this->context->customer, isset($_POST['klarna_house_number']) ? htmlentities($_POST['klarna_house_number'], ENT_QUOTES, 'ISO-8859-1') : null, isset($_POST['klarna_house_ext']) ? htmlentities($_POST['klarna_house_ext'], ENT_QUOTES, 'ISO-8859-1') : null); if (Tools::isSubmit('klarna_pno')) { $pno = Tools::safeOutput(Tools::getValue('klarna_pno')); } else { $day = $_POST['klarna_pno_day'] < 10 ? '0' . (int) $_POST['klarna_pno_day'] : (int) $_POST['klarna_pno_day']; $month = $_POST['klarna_pno_month'] < 10 ? '0' . (int) $_POST['klarna_pno_month'] : (int) $_POST['klarna_pno_month']; $pno = Tools::safeOutput($day . $month . Tools::getValue('klarna_pno_year')); } $pclass = $type == 'invoice' ? KlarnaPClass::INVOICE : (int) Tools::getValue('paymentAccount'); try { if ($country->iso_code == 'DE' || $country->iso_code == 'NL') { if ($this->context->customer->id_gender != 1 && $this->context->customer->id_gender != 2 && $this->context->customer->id_gender != 3) { $gender = (int) $_POST['klarna_gender']; $customer = new Customer($this->context->customer->id); $customer->id_gender = (int) $_POST['klarna_gender']; $Customer->birthday = (int) $_POST['klarna_pno_year'] . '-' . $month . '-' . $day; $customer->update(); } else { $gender = $this->context->customer->id_gender == 1 ? 1 : 0; } } else { $gender = null; } $result = $klarnaInt->reserve($pno, $gender, -1, KlarnaFlags::NO_FLAG, (int) $pclass); // Here we get the reservation number or invoice number $rno = $result[0]; Db::getInstance()->autoExecute(_DB_PREFIX_ . 'klarna_rno', array('id_cart' => (int) $this->context->cart->id, 'rno' => pSQL($rno), 'pno' => pSQL($pno), 'house_number' => isset($_POST['klarna_house_number']) ? pSQL($_POST['klarna_house_number']) : null, 'house_ext' => isset($_POST['klarna_house_ext']) ? pSQL($_POST['klarna_house_ext']) : null, 'state' => self::RESERVED, 'type' => pSQL($type), 'pclass' => $type == 'invoice' ? null : (int) Tools::getValue('paymentAccount')), 'INSERT'); $updateResult = $klarnaInt->updateOrderNo($rno, (int) $this->context->cart->id); if ($result[1] == KlarnaFlags::PENDING) { $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_PENDING'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key); } else { if ($result[1] == KlarnaFlags::ACCEPTED) { $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_ACCEPTED'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key); } } $redirect = __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $this->context->cart->secure_key; header('Location: ' . $redirect); exit; } catch (Exception $e) { /*remove invoiceFee if existe*/ $this->context->cart->deleteProduct((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); return array('error' => true, 'message' => Tools::safeOutput(utf8_encode($e->getMessage()))); } }
public function handleConfirm($update = false) { global $currentIndex, $cookie, $smarty; $products_to_import = array(); $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT'); $file_path = Tools::getValue('current_file'); $overwrite_imgs = Tools::getValue("overwrite_imgs"); //$file_path = '/Users/rohit/webroot/indusdiva/admin12/product-uploads/upload_sheet_1.csv'; $f = fopen($file_path, 'r'); $file_error = false; if ($f) { //discard header $line = fgetcsv($f); while ($line = fgetcsv($f)) { //ignore empty lines if (empty($line)) { continue; } //trim data foreach ($line as $key => $value) { $line[$key] = trim($value); } $id_product = $line[0]; $images = $line[1]; $product_name = $line[2]; $fabric = $line[3]; $color = $line[4]; $mrp = $line[5]; $supplier_code = $line[6]; $reference = $line[7]; $location = $line[8]; $length = $line[9]; $width = $line[10]; $blouse_length = $line[11]; $garment_type = $line[12]; $work_type = $line[13]; $weight = $line[14]; $description = $line[15]; $other_info = $line[16]; $wash_care = $line[17]; $shipping_estimate = $line[18]; $supplier_price = $line[19]; $manufacturer = $line[20]; $categories = explode(",", $line[21]); $tax_rule = $line[22]; $quantity = $line[23]; $active = $line[24]; $discount = $line[25]; $tags = $line[26]; $kameez_style = $line[27]; $salwar_style = $line[28]; $sleeves = $line[29]; $customizable = $line[30]; $generic_color = $line[31]; $skirt_length = $line[32]; $dupatta_length = $line[33]; $stone = $line[34]; $plating = $line[35]; $material = $line[36]; $dimensions = $line[37]; $look = $line[38]; $as_shown = isset($line[39]) && !empty($line[39]) ? intval($line[39]) : 0; $id_sizechart = isset($line[40]) && !empty($line[40]) ? intval($line[40]) : 0; $is_exclusive = isset($line[41]) && !empty($line[41]) ? intval($line[41]) : 0; $handbag_occasion = isset($line[42]) && !empty($line[42]) ? $line[42] : null; $handbag_style = isset($line[43]) && !empty($line[43]) ? $line[43] : null; $handbag_material = isset($line[44]) && !empty($line[44]) ? $line[44] : null; $images = explode(",", $images); $error = false; //validate fields if (!Validate::isFloat($mrp)) { $error = 'MRP should be a number: ' . trim($reference); } elseif (!Validate::isFloat($supplier_price)) { $error = 'Supplier Price should be a number: ' . trim($reference); } $importCategories = array(); if (is_array($categories)) { $categories = array_unique($categories); foreach ($categories as $category) { $category = intval(trim($category)); if (empty($category)) { continue; } if (!is_numeric($category) || !Category::categoryExists($category)) { $error = 'Category does not exist: ' . $category; } $importCategories[] = $category; } } else { $error = 'Atleast one category required: ' . trim($reference); } if (!Validate::isFloat($weight)) { $error = 'Weight has to be a number: ' . trim($reference); } if (!empty($manufacturer) && (!is_numeric($manufacturer) || !Manufacturer::manufacturerExists((int) $manufacturer))) { $error = 'Manufacturer does not exist'; } if ($quantity && !is_numeric($quantity) || $discount && !is_numeric($discount)) { $error = 'Quantity and discount should be numbers: ' . trim($reference); } if (!Validate::isLoadedObject(new TaxRulesGroup($tax_rule))) { $error = 'Tax rate invalid: ' . trim($reference); } if (!$update) { $sql = "SELECT `reference`\n\t\t\t\t\t\t\tFROM " . _DB_PREFIX_ . "product p\n\t\t\t\t\t\t\tWHERE p.`reference` = '" . $reference . "'"; $row = Db::getInstance()->getRow($sql); if (isset($row['reference'])) { $error = "Duplicate indusdiva code : " . trim($reference); } } //check for souring price if ($supplier_price > $mrp / 1.2) { $error = "MRP too low : " . trim($reference); } //check for images if (!$update || $overwrite_imgs == "on") { foreach ($images as $image_name) { $image_name = trim($image_name); $image_path = IMAGE_UPLOAD_PATH . $image_name; if (!empty($image_name) && !file_exists($image_path)) { $error = "Image not found for: " . trim($reference) . ", Image Name: " . $image_name; break; } } } $vendor_code = substr($reference, 0, 6); $sql = "select id_supplier from ps_supplier where code = '{$vendor_code}'"; $row = Db::getInstance()->getRow($sql); if (!isset($row['id_supplier'])) { $error = "Vendor Details not found for : " . trim($reference); } else { $id_supplier = $row['id_supplier']; } //For sudarshan, supplier_code (vendor product code) is mandatory if (false) { //(int) $id_supplier === 2 ) { if (empty($supplier_code)) { $error = "Reference: {$reference} -- Supplier Code is Mandatory for Vendor {$vendor_code}"; } else { if (strpos("::", ${$supplier_code}) === false) { $error = "Reference: {$reference} -- Supplier Code:{$supplier_code} is not in DESIGN_NO::ITEM_CODE format for Vendor {$vendor_code}"; } } } if (!$error) { if ($update && !empty($id_product)) { $product = new Product((int) $id_product); if (!Validate::isLoadedObject($product)) { $error = "Error loading the product: " . $id_product; return; } } elseif (!$update) { $product = new Product(); } $product->id_tax_rules_group = $tax_rule; $product->reference = $reference; $product->id_supplier = $id_supplier; $product->location = $location; $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0); if (isset($manufacturer) and is_numeric($manufacturer) and Manufacturer::manufacturerExists((int) $manufacturer)) { $product->id_manufacturer = $manufacturer; } $product->price = (double) $mrp; $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', ''); $product->id_category = $importCategories; $product->id_category_default = 1; $product->name = array(); $product->name[$defaultLanguageId] = $product_name; $product->description_short = array(); $product->description_short[$defaultLanguageId] = $style_tips; $product->description = array(); $product->description[$defaultLanguageId] = $description; $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]); $product->link_rewrite = array(); $product->link_rewrite[$defaultLanguageId] = $link_rewrite; $product->quantity = $quantity ? intval($quantity) : 0; if ($discount && is_numeric($discount)) { $product->discount = $discount; } if (!empty($tags)) { $product->tags = $tags; } $product->weight = is_numeric($weight) ? $weight : 0; $product->width = is_numeric($width) ? $width : 0; $product->height = is_numeric($length) ? $length : 0; $product->supplier_reference = $supplier_code; $product->wholesale_price = $supplier_price ? (double) $supplier_price : 0; $product->active = $active == 1 ? 1 : 0; $product->images = $images; $product->fabric = $fabric; $product->color = $color; $product->generic_color = $generic_color; $product->garment_type = $garment_type; $product->work_type = $work_type; $product->blouse_length = $blouse_length ? $blouse_length : ' '; $product->wash_care = $wash_care ? $wash_care : ' '; $product->other_info = $other_info ? $other_info : ' '; $product->shipping_estimate = $shipping_estimate ? $shipping_estimate : ' '; $product->is_customizable = $customizable == 1 ? 1 : 0; $product->kameez_style = $kameez_style; $product->salwar_style = $salwar_style; $product->sleeves = $sleeves; $product->skirt_length = $skirt_length; $product->dupatta_length = $dupatta_length; $product->stone = $stone; $product->plating = $plating; $product->material = $material; $product->dimensions = $dimensions; $product->look = $look; $product->as_shown = $as_shown; $product->id_sizechart = $id_sizechart; $product->is_exclusive = $is_exclusive; $product->handbag_occasion = $handbag_occasion; $product->handbag_style = $handbag_style; $product->handbag_material = $handbag_material; $product->indexed = 0; $products_to_import[] = $product; } else { $smarty->assign('error', $error); return; $file_error = true; } } if (!$file_error) { $added_product_ids = array(); foreach ($products_to_import as $product) { $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true); $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($fieldError === true and $langFieldError === true) { // check quantity if ($product->quantity == NULL) { $product->quantity = 0; } // If no id_product or update failed if ($update && $product->id) { $res = $product->update(); } else { $res = $product->add(); } $added_product_ids[] = $product->id; } if (isset($product->discount) && $product->discount > 0) { SpecificPrice::deleteByProductId((int) $product->id); $specificPrice = new SpecificPrice(); $specificPrice->id_product = (int) $product->id; $specificPrice->id_shop = (int) Shop::getCurrentShop(); $specificPrice->id_currency = 0; $specificPrice->id_country = 0; $specificPrice->id_group = 0; $specificPrice->from_quantity = 1; $specificPrice->reduction = $product->discount / 100; $specificPrice->reduction_type = 'percentage'; $specificPrice->from = '2012-01-01 00:00:00'; $specificPrice->to = '2016-01-01 00:00:00'; $specificPrice->price = $product->price; $specificPrice->add(); } if (isset($product->tags) and !empty($product->tags)) { // Delete tags for this id product, for no duplicating error Tag::deleteTagsForProduct($product->id); $tag = new Tag(); $tag->addTags($defaultLanguageId, $product->id, $tags); } if (isset($product->images) and is_array($product->images) and sizeof($product->images) and !$update || $overwrite_imgs == "on") { $product->deleteImages(); $first_image = true; foreach ($product->images as $image_name) { $image_name = trim($image_name); $image_path = IMAGE_UPLOAD_PATH . $image_name; if (!empty($image_name)) { $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = $first_image; $image->legend[$defaultLanguageId] = $product->name[$defaultLanguageId]; if (($fieldError = $image->validateFields(false, true)) === true and ($langFieldError = $image->validateFieldsLang(false, true)) === true and $image->add()) { if (!self::copyImg($product->id, $image->id, $image_path)) { $_warnings[] = Tools::displayError('Error copying image: ') . $image_path; } else { //delete the original image @unlink($image_path); } } else { $_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } $first_image = false; } } if (isset($product->id_category)) { $product->updateCategories(array_map('intval', $product->id_category)); } $this->addFeature($product->id, 'fabric', $product->fabric); $this->addFeature($product->id, 'color', $product->color); $this->addFeature($product->id, 'garment_type', $product->garment_type); $this->addFeature($product->id, 'work_type', $product->work_type); $this->addFeature($product->id, 'blouse_length', $product->blouse_length); $this->addFeature($product->id, 'wash_care', $product->wash_care); $this->addFeature($product->id, 'other_info', $product->other_info); // to avoid type errors in the catalog sheet - construct the string here again $shipping_sla = (int) preg_replace('/\\D/', '', $product->shipping_estimate); $shipping_estimate_str = ""; if ($shipping_sla > 0) { $shipping_estimate_str = $shipping_sla === 1 ? "Ready to be shipped in 1 day" : "Ready to be shipped in {$shipping_sla} days"; } $this->addFeature($product->id, 'shipping_estimate', $shipping_estimate_str); $this->addFeature($product->id, 'kameez_style', $product->kameez_style); $this->addFeature($product->id, 'salwar_style', $product->salwar_style); $this->addFeature($product->id, 'sleeves', $product->sleeves); $this->addFeature($product->id, 'generic_color', $product->generic_color); $this->addFeature($product->id, 'skirt_length', $product->skirt_length); $this->addFeature($product->id, 'dupatta_length', $product->dupatta_length); $this->addFeature($product->id, 'stone', $product->stone); $this->addFeature($product->id, 'plating', $product->plating); $this->addFeature($product->id, 'material', $product->material); $this->addFeature($product->id, 'dimensions', $product->dimensions); $this->addFeature($product->id, 'look', $product->look); $this->addFeature($product->id, 'handbag_occasion', $product->handbag_occasion); $this->addFeature($product->id, 'handbag_style', $product->handbag_style); $this->addFeature($product->id, 'handbag_material', $product->handbag_material); } $smarty->assign("products_affected", $products_to_import); //reindex the products SolrSearch::updateProducts($added_product_ids); $smarty->assign("is_update", $update); } else { $smarty->assign('file_error', 1); } } else { $smarty->assign('error_reading', 1); } }
$result=$product->update($product->id,$user,1,0,1); if ($result < 0) { $mesg=join(',',$product->errors); } $action=""; $id=$_POST["id"]; $_GET["id"]=$_POST["id"]; } if ($action == 'setproductaccountancycodesell') { $product = new Product($db); $result=$product->fetch($id); $product->accountancy_code_sell=$_POST["productaccountancycodesell"]; $result=$product->update($product->id,$user,1,0,1); if ($result < 0) { $mesg=join(',',$product->errors); } $action=""; } if ($action == 'fastappro') { $product = new Product($db); $product->fetch($id); $result = $product->fastappro($user); Header("Location: fiche.php?id=".$id); exit; }
/** * Validates data submitted in the edit form. If the validation fails, * displays the edit page. Otherwise, updates the information in the * database and redirects back to the edit page. * * @param int $id id of the edited product */ public static function edit($id) { $params = $_POST; $attributes = array('id' => $id, 'product_name' => $params['product_name'], 'price' => $params['price'], 'category' => $params['category'], 'description' => $params['description']); if (isset($params['ingredients'])) { $attributes['ingredients'] = $params['ingredients']; } if (isset($params['customizable'])) { $attributes['customizable'] = 'TRUE'; } else { $attributes['customizable'] = 'FALSE'; } $validator = self::product_validator($attributes); if ($validator->validate()) { $product = new Product($attributes); $product->update(); if (isset($params['ingredients'])) { self::set_product_ingredients($product, $params['ingredients']); } Redirect::to($params['redirect'], array('message' => 'Tuotetta muokattu!')); } else { $ingredients = Ingredient::findByCategory($attributes['category']); View::make('product/edit.html', array('ingredients' => $ingredients, 'errors' => $validator->errors(), 'product' => $attributes)); } }
/** * Update product */ private function eeweeProductUpdate() { $p = new Product(59); // LANG $langs = $this->getLang(); foreach ($langs as $lang) { // INFORMATIONS $p->name[$lang['id_lang']] = 'Nom du produit'; // REFERENCEMENT - SEO $p->link_rewrite[$lang['id_lang']] = 'nom-du-produit'; } // INFORMATIONS $p->reference = '5510'; // Reference $p->active = false; // Active $p->description_short = 'Resume du produit.'; // Resume $p->description = 'Description longue du produit.'; // Description // PRIX $p->price = 18; // Prix de vente HT // UPDATE $p->update(); }
public function handleUpload($file, $uploadDir, $uploadType, $id) { $fileName = $this->f3->get('POST.name'); $fileBaseName = pathinfo($fileName, PATHINFO_FILENAME); $fileType = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $slugName = basename($file['name']); $slugBaseName = pathinfo($slugName, PATHINFO_FILENAME); $uploadDirFull = $this->docRoot . $uploadDir; $fileFullPath = $uploadDir . $slugName; if (!file_exists($uploadDirFull)) { $cmd = 'mkdir -p ' . $uploadDirFull; $output = shell_exec($cmd); } if ($this->debug) { $this->utils->debug(__METHOD__, $fileFullPath); $this->utils->debug(__METHOD__, $cmd); $this->utils->debug(__METHOD__, $output); } switch ($uploadType) { case "track": $track = new AlbumTrack($this->db); // Extract ID3 tags using getID3 engine $fileTypes = array("mp3", "flac"); if (in_array($fileType, $fileTypes)) { $getID3 = new getID3(); // Currently using tmp_name, actual file gets created after handler runs $tags = $getID3->analyze($file['tmp_name']); if ($this->debug) { $this->utils->debug(__METHOD__, $tags); } // See https://raw.githubusercontent.com/JamesHeinrich/getID3/master/structure.txt if (isset($tags['playtime_seconds'])) { $track->Length = $tags['playtime_seconds']; } if (isset($tags['audio'])) { $tag = $tags['audio']; $track->Bitrate = $tag['bitrate']; $track->BitrateMode = $tag['bitrate_mode']; $track->Codec = $tag['codec']; $track->Format = $tag['dataformat']; $track->Encoder = $tag['encoder']; $track->Lossless = $tag['lossless']; } if (isset($tags['tags']['id3v1'])) { $tag = $tags['tags']['id3v1']; $track->TrackName = $tag['title'][0]; $track->TrackNumber = $tag['track'][0]; } if (isset($tags['tags']['id3v2'])) { $tag = $tags['tags']['id3v2']; $track->TrackName = $tag['title'][0]; $track->TrackNumber = $tag['track_number'][0]; $track->DiscNumber = $tag['part_of_a_set'][0]; $track->Date = $tag['year'][0]; $track->Genre = $tag['genre'][0]; } if (isset($tags['tags']['vorbiscomment'])) { $tag = $tags['tags']['vorbiscomment']; $track->TrackName = $tag['title'][0]; $track->TrackNumber = $tag['tracknumber'][0]; $track->DiscNumber = $tag['discnumber'][0]; $track->Date = $tag['date'][0]; $track->Genre = $tag['genre'][0]; } if ($track->TrackName == null) { $track->TrackName = $fileBaseName; } } $track->ProductID = $id; $track->FileName = $fileFullPath; $track->Size = $file['size']; if ($this->debug) { $this->utils->debug(__METHOD__, $track->cast()); } $track->save(); echo $this->utils->successResponse($track, null); break; case "cover": // Currently using tmp_name, actual file gets created after handler runs $product = new Product($this->db); $product->getByUser($this->userID, $id); $product->ProductImage = $fileFullPath; if ($this->debug) { $this->utils->debug(__METHOD__, $product->cast()); } $product->update(); $source = $file['tmp_name']; $dest = $uploadDirFull . $slugBaseName . '_small' . '.' . $fileType; // Set WxH //$size = "400x250"; // Set width only $size = "400"; $output = $this->resizeImage($source, $dest, $size); if ($output == "") { echo $this->utils->successResponse($dest, null); } break; default: break; } }
/** * Create the Buyer Protection application by the web service. * Applications are saved by Trusted Shops and are processed at regular intervals. * * @uses TSBuyerProtection::_getClient() * @uses TSBuyerProtection::_requestForProtectionV2ParamsValidator() * to check required params * @see TSBuyerProtection::cronTasks() * @param array $params */ private function _requestForProtectionV2($params) { $client = $this->_getClient(TSBuyerProtection::WEBSERVICE_FO); $testing_params = $this->_requestForProtectionV2ParamsValidator($params); $code = 0; $sql = ' SELECT * FROM `' . _DB_PREFIX_ . TSBuyerProtection::DB_APPLI . '` WHERE `id_order` = "' . (int) $params['shopOrderID'] . '" '; $order = Db::getInstance()->ExecuteS($sql); // If an order was already added, no need to continue. // Otherwise a new application is created by TrustedShops. // this can occurred when order confirmation page is reload. if (isset($order[0])) { return false; } if ($testing_params) { try { $code = $client->requestForProtectionV2($params['tsID'], $params['tsProductID'], $params['amount'], $params['currency'], $params['paymentType'], $params['buyerEmail'], $params['shopCustomerID'], $params['shopOrderID'], $params['orderDate'], $params['shopSystemVersion'], $params['wsUser'], $params['wsPassword']); if ($code < 0) { throw new TSBPException($code, TSBPException::FRONT_END); } } catch (SoapFault $fault) { $this->errors[] = $this->l('Code #') . $fault->faultcode . ',<br />' . $this->l('message:') . $fault->faultstring; } catch (TSBPException $e) { $this->errors[] = $e->getMessage(); } if ($code > 0) { $date = date('Y-m-d H:i:s'); $sql = ' INSERT INTO `' . _DB_PREFIX_ . TSBuyerProtection::DB_APPLI . '` ( `id_application`, `ts_id`, `id_order`, `creation_date`, `last_update` ) VALUES ( "' . pSQL($code) . '", "' . pSQL($params['tsID']) . '", "' . pSQL($params['shopOrderID']) . '", "' . $date . '", "' . $date . '" ) '; Db::getInstance()->Execute($sql); // To reset product quantity in database. $sql = ' SELECT `id_product` FROM `' . _DB_PREFIX_ . TSBuyerProtection::DB_ITEMS . '` WHERE `ts_product_id` = "' . (int) $params['tsProductID'] . '" '; $ts_product = Db::getInstance()->ExecuteS($sql); $product = new Product($ts_product[0]['id_product']); $product->quantity = 1000; $product->update(); } } else { $this->errors[] = $this->l('Some parameters sending to "requestForProtectionV2" method are wrong or missing.'); } }
/** * Update a product or service * * @param array $authentication Array of authentication information * @param Product $product Product * @return array Array result */ function updateProductOrService($authentication, $product) { global $db, $conf, $langs; $now = dol_now(); dol_syslog("Function: updateProductOrService login="******"You must choose between price or price_net to provide price."; } if ($product['barcode'] && !$product['barcode_type']) { $errror++; $errorcode = 'KO'; $errorlabel = "You must set a barcode type when setting a barcode."; } if (!$error) { include_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; $newobject = new Product($db); $newobject->fetch($product['id']); if (isset($product['ref'])) { $newobject->ref = $product['ref']; } if (isset($product['ref_ext'])) { $newobject->ref_ext = $product['ref_ext']; } $newobject->type = $product['type']; $newobject->libelle = $product['label']; // @deprecated $newobject->label = $product['label']; $newobject->description = $product['description']; $newobject->note = $product['note']; $newobject->status = $product['status_tosell']; $newobject->status_buy = $product['status_tobuy']; $newobject->price = $product['price_net']; $newobject->price_ttc = $product['price']; $newobject->tva_tx = $product['vat_rate']; $newobject->price_base_type = $product['price_base_type']; $newobject->date_creation = $now; if ($product['barcode']) { $newobject->barcode = $product['barcode']; $newobject->barcode_type = $product['barcode_type']; } $newobject->stock_reel = $product['stock_real']; $newobject->pmp = $product['pmp']; $newobject->seuil_stock_alert = $product['stock_alert']; $newobject->country_id = $product['country_id']; if ($product['country_code']) { $newobject->country_id = getCountry($product['country_code'], 3); } $newobject->customcode = $product['customcode']; $newobject->canvas = $product['canvas']; /*foreach($product['lines'] as $line) { $newline=new FactureLigne($db); $newline->type=$line['type']; $newline->desc=$line['desc']; $newline->fk_product=$line['fk_product']; $newline->total_ht=$line['total_net']; $newline->total_vat=$line['total_vat']; $newline->total_ttc=$line['total']; $newline->vat=$line['vat_rate']; $newline->qty=$line['qty']; $newline->fk_product=$line['product_id']; }*/ //var_dump($product['ref_ext']); //var_dump($product['lines'][0]['type']); $extrafields = new ExtraFields($db); $extralabels = $extrafields->fetch_name_optionals_label('product', true); foreach ($extrafields->attribute_label as $key => $label) { $key = 'options_' . $key; $newobject->array_options[$key] = $product[$key]; } $db->begin(); $result = $newobject->update($newobject->id, $fuser); if ($result <= 0) { $error++; } else { // Update stock if stock count is provided and differs from database after creation or update if (isset($product['stock_real']) && $product['stock_real'] != '' && !empty($conf->global->stock->enabled)) { require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php'; $savstockreal = $newobject->stock_reel; $newobject->load_stock(); // This overwrite ->stock_reel $getstockreal = $newobject->stock_reel; if ($savstockreal != $getstockreal) { $warehouse = new Entrepot($this->db); $warehouse->fetch(0, $product['warehouse_ref']); if ($warehouse->id > 0) { if ($savstockreal - $getstockreal > 0) { $result = $newobject->correct_stock($fuser, $warehouse->id, $savstockreal - $getstockreal, 0, 'Correction from external call (Web Service)', 0, 'WS' . dol_print_date($now, 'dayhourlog')); } if ($savstockreal - $getstockreal > 0) { $result = $newobject->correct_stock($fuser, $warehouse->id, $savstockreal - $getstockreal, 1, 'Correction from external call (Web Service)', 0, 'WS' . dol_print_date($now, 'dayhourlog')); } if ($result <= 0) { $error++; $newobject->error = 'You set a different value for stock, but correction of stock count (before=' . $getstockreal . ', after=' . $savstockreal . ') fails with error ' . $newobject->error; } } else { $error++; $newobject->error = 'You set a different value for stock but we failed to find warehouse ' . $product['warehouse_ref'] . ' to make correction.'; } } } } if (!$error) { if ($newobject->price_base_type == 'HT') { $result = $newobject->updatePrice($newobject->price, $newobject->price_base_type, $fuser); if ($result <= 0) { $error++; } } elseif ($newobject->price_base_type == 'TTC') { $result = $newobject->updatePrice($newobject->price_ttc, $newobject->price_base_type); if ($result <= 0) { $error++; } } } if (!$error) { $db->commit(); $objectresp = array('result' => array('result_code' => 'OK', 'result_label' => ''), 'id' => $newobject->id, 'ref' => $newobject->ref); } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $newobject->error; } } if ($error) { $objectresp = array('result' => array('result_code' => $errorcode, 'result_label' => $errorlabel)); } return $objectresp; }
* that were distributed with this source code. */ require_once __DIR__ . '/../../init.php'; $tpl = new Template_Helper(); $tpl->setTemplate('manage/products.tpl.html'); Auth::checkAuthentication(); $role_id = Auth::getCurrentRole(); if ($role_id < User::ROLE_MANAGER) { Misc::setMessage('Sorry, you are not allowed to access this page.', Misc::MSG_ERROR); $tpl->displayTemplate(); exit; } if (@$_POST['cat'] == 'new') { $res = Product::insert($_POST['title'], $_POST['version_howto'], $_POST['rank'], @$_POST['removed'], @$_POST['email']); Misc::mapMessages($res, array(1 => array('Thank you, the product was added successfully.', Misc::MSG_INFO), -1 => array('An error occurred while trying to add the product.', Misc::MSG_ERROR))); } elseif (@$_POST['cat'] == 'update') { $res = Product::update($_POST['id'], $_POST['title'], $_POST['version_howto'], $_POST['rank'], @$_POST['removed'], @$_POST['email']); Misc::mapMessages($res, array(1 => array('Thank you, the product was updated successfully.', Misc::MSG_INFO), -1 => array('An error occurred while trying to update the product.', Misc::MSG_ERROR))); } elseif (@$_POST['cat'] == 'delete') { Product::remove($_POST['items']); } if (@$_GET['cat'] == 'edit') { $info = Product::getDetails($_GET['id']); $tpl->assign('info', $info); $user_options = User::getActiveAssocList(Auth::getCurrentProject(), User::ROLE_CUSTOMER, false, $_GET['id']); } else { $user_options = User::getActiveAssocList(Auth::getCurrentProject(), User::ROLE_CUSTOMER, true); } $tpl->assign('list', Product::getList()); $tpl->assign('project_list', Project::getAll()); $tpl->displayTemplate();
if (empty($sku)) { $error[] = 'No import candidate for item number: ' . $importable['POSItemNumber'] . ' missing SKU.'; continue; } if (productExistsLocally($sku, STN::getPDO())) { $alreadyImported[] = $sku; $importCount += 1; continue; } try { $product = $provider->getProductBySTNSKU($sku); if (!empty($product)) { $product_id = importProduct($product, $provider, $categories); $changes = array('sku' => $importable['POSItemNumber'], 'quantity' => $importable['QOH']); $failed = array(); Product::update($product_id, $changes, $failed); if (!empty($failed)) { throw new Exception('Saving product data failed.'); } Product::setPrice($product_id, $importable['RegularPrice']); } else { $errorSkus[$sku] = "Product not found on master database: " . $sku; continue; } } catch (Exception $e) { $errorSkus[$sku] = $e->getMessage(); continue; } $markImported->execute(array(':id' => $importable['ID'])); $processedSkus[] = $sku; $importCount += 1;
if ($action == 'setstocklimit') { $product = new Product($db); $result = $product->fetch($id); $product->seuil_stock_alerte = $stocklimit; $result = $product->update($product->id, $user, 0, 'update'); if ($result < 0) { setEventMessage($product->error, 'errors'); } $action = ''; } // Set desired stock if ($action == 'setdesiredstock') { $product = new Product($db); $result = $product->fetch($id); $product->desiredstock = $desiredstock; $result = $product->update($product->id, $user, 0, 'update'); if ($result < 0) { setEventMessage($product->error, 'errors'); } $action = ''; } // Correct stock if ($action == "correct_stock" && !$cancel) { if (!(GETPOST("id_entrepot") > 0)) { setEventMessage($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Warehouse")), 'errors'); $error++; $action = 'correction'; } if (!GETPOST("nbpiece")) { setEventMessage($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumberOfUnit")), 'errors'); $error++;
} else { if (!isset($param)) { $errors[] = 'Image is required'; $wasError = 1; } } if (!$wasError) { if (isset($param) && !empty($param)) { // ha van kep, akkor regit toroljuk, uj elmentodik if (isset($_POST['image'])) { $theProduct = $product->find((int) $param); @unlink(FOTO_UPLOAD_DIR . $theProduct['image']); @unlink(THUMB_UPLOAD_DIR . $theProduct['image']); } //update $product->update($_POST, (int) $param); $theProduct = $product->find((int) $param); } else { //insert $product->insert($_POST); Redirect::to(BASE_URL . 'products/'); } } else { $theProduct = $_POST; } } //$template = 'products_edit'; break; case 'delete': if (isset($param) && !empty($param)) { $p = $product->find((int) $param);
/** * Post treatment for suppliers */ public function processSuppliers() { if ((int) Tools::getValue('supplier_loaded') === 1 && Validate::isLoadedObject($product = new Product((int) 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 suppliers $suppliers = Supplier::getSuppliers(); // Get already associated suppliers $associated_suppliers = ProductSupplier::getSupplierCollection($product->id); $suppliers_to_associate = array(); $new_default_supplier = 0; if (Tools::isSubmit('default_supplier')) { $new_default_supplier = (int) Tools::getValue('default_supplier'); } // Get new associations foreach ($suppliers as $supplier) { if (Tools::isSubmit('check_supplier_' . $supplier['id_supplier'])) { $suppliers_to_associate[] = $supplier['id_supplier']; } } // Delete already associated suppliers if needed foreach ($associated_suppliers as $key => $associated_supplier) { if (!in_array($associated_supplier->id_supplier, $suppliers_to_associate)) { $associated_supplier->delete(); unset($associated_suppliers[$key]); } } // Associate suppliers foreach ($suppliers_to_associate as $id) { $to_add = true; foreach ($associated_suppliers as $as) { if ($id == $as->id_supplier) { $to_add = false; } } if ($to_add) { $product_supplier = new ProductSupplier(); $product_supplier->id_product = $product->id; $product_supplier->id_product_attribute = 0; $product_supplier->id_supplier = $id; if ($this->context->currency->id) { $product_supplier->id_currency = (int) $this->context->currency->id; } else { $product_supplier->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); } $product_supplier->save(); $associated_suppliers[] = $product_supplier; } } // Manage references and prices foreach ($attributes as $attribute) { foreach ($associated_suppliers as $supplier) { if (Tools::isSubmit('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier) || Tools::isSubmit('product_price_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier) && Tools::isSubmit('product_price_currency_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier)) { $reference = pSQL(Tools::getValue('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, '')); $price = (double) str_replace(array(' ', ','), array('', '.'), Tools::getValue('product_price_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, 0)); $price = Tools::ps_round($price, 6); $id_currency = (int) Tools::getValue('product_price_currency_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, 0); if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) { $this->errors[] = Tools::displayError('The selected currency is not valid'); } // Save product-supplier data $product_supplier_id = (int) ProductSupplier::getIdByProductAndSupplier($product->id, $attribute['id_product_attribute'], $supplier->id_supplier); if (!$product_supplier_id) { $product->addSupplierReference($supplier->id_supplier, (int) $attribute['id_product_attribute'], $reference, (double) $price, (int) $id_currency); if ($product->id_supplier == $supplier->id_supplier) { if ((int) $attribute['id_product_attribute'] > 0) { $data = array('supplier_reference' => pSQL($reference), 'wholesale_price' => (double) Tools::convertPrice($price, $id_currency)); $where = ' a.id_product = ' . (int) $product->id . ' AND a.id_product_attribute = ' . (int) $attribute['id_product_attribute']; ObjectModel::updateMultishopTable('Combination', $data, $where); } else { $product->wholesale_price = (double) Tools::convertPrice($price, $id_currency); //converted in the default currency $product->supplier_reference = pSQL($reference); $product->update(); } } } else { $product_supplier = new ProductSupplier($product_supplier_id); $product_supplier->id_currency = (int) $id_currency; $product_supplier->product_supplier_price_te = (double) $price; $product_supplier->product_supplier_reference = pSQL($reference); $product_supplier->update(); } } elseif (Tools::isSubmit('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier)) { //int attribute with default values if possible if ((int) $attribute['id_product_attribute'] > 0) { $product_supplier = new ProductSupplier(); $product_supplier->id_product = $product->id; $product_supplier->id_product_attribute = (int) $attribute['id_product_attribute']; $product_supplier->id_supplier = $supplier->id_supplier; $product_supplier->save(); } } } } // Manage defaut supplier for product if ($new_default_supplier != $product->id_supplier) { $this->object->id_supplier = $new_default_supplier; $this->object->update(); } } }
<?php require_once "/etc/apache2/capstone-mysql/encrypted-config.php"; require_once "product.php"; $pdo = connectToEncryptedMySQL("/etc/apache2/data-design/jfindley2.ini"); $product = new Product(null, "imagefile", 10, "Info", "Detail", "Tech", "Name"); $product->insert($pdo); $product->setProductName("This is the new name"); $product->update($pdo); $product->delete($pdo);
/** * Update a product or service * * @param array $authentication Array of authentication information * @param Product $product Product * @return array Array result */ function updateProductOrService($authentication, $product) { global $db, $conf, $langs; $now = dol_now(); dol_syslog("Function: updateProductOrService login="******"You must choose between price or price_net to provide price."; } if ($product['barcode'] && !$product['barcode_type']) { $errror++; $errorcode = 'KO'; $errorlabel = "You must set a barcode type when setting a barcode."; } if (!$error) { include_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; $newobject = new Product($db); $newobject->fetch($product['id']); if (isset($product['ref'])) { $newobject->ref = $product['ref']; } if (isset($product['ref_ext'])) { $newobject->ref_ext = $product['ref_ext']; } $newobject->type = $product['type']; $newobject->libelle = $product['label']; // TODO deprecated $newobject->label = $product['label']; $newobject->description = $product['description']; $newobject->note = $product['note']; $newobject->status = $product['status_tosell']; $newobject->status_buy = $product['status_tobuy']; $newobject->price = $product['price_net']; $newobject->price_ttc = $product['price']; $newobject->tva_tx = $product['vat_rate']; $newobject->price_base_type = $product['price_base_type']; $newobject->date_creation = $now; if ($product['barcode']) { $newobject->barcode = $product['barcode']; $newobject->barcode_type = $product['barcode_type']; } $newobject->stock_reel = $product['stock_real']; $newobject->pmp = $product['pmp']; $newobject->seuil_stock_alert = $product['stock_alert']; $newobject->country_id = $product['country_id']; if ($product['country_code']) { $newobject->country_id = getCountry($product['country_code'], 3); } $newobject->customcode = $product['customcode']; $newobject->canvas = $product['canvas']; /*foreach($product['lines'] as $line) { $newline=new FactureLigne($db); $newline->type=$line['type']; $newline->desc=$line['desc']; $newline->fk_product=$line['fk_product']; $newline->total_ht=$line['total_net']; $newline->total_vat=$line['total_vat']; $newline->total_ttc=$line['total']; $newline->vat=$line['vat_rate']; $newline->qty=$line['qty']; $newline->fk_product=$line['product_id']; }*/ //var_dump($product['ref_ext']); //var_dump($product['lines'][0]['type']); $extrafields = new ExtraFields($db); $extralabels = $extrafields->fetch_name_optionals_label('product', true); foreach ($extrafields->attribute_label as $key => $label) { $key = 'options_' . $key; $newobject->array_options[$key] = $product[$key]; } $db->begin(); $result = $newobject->update($newobject->id, $fuser); if ($result <= 0) { $error++; } if (!$error) { $db->commit(); $objectresp = array('result' => array('result_code' => 'OK', 'result_label' => ''), 'id' => $newobject->id, 'ref' => $newobject->ref); } else { $db->rollback(); $error++; $errorcode = 'KO'; $errorlabel = $newobject->error; } } if ($error) { $objectresp = array('result' => array('result_code' => $errorcode, 'result_label' => $errorlabel)); } return $objectresp; }
} else { $product->color = $_SESSION['product']['color']; echo " color default,"; } if (isset($_POST['quantity'])) { $product->quantity = $_POST['quantity']; } else { $product->quantity = $_SESSION['product']['quantity']; echo " quantity default,"; } $d = mktime(11, 14, 54, 8, 12, 2014); $product->add_date = date("Y-m-d h:i:sa", $d); if (isset($_POST['status'])) { $product->status = $_POST['status']; } else { $product->status = $_SESSION['product']['status']; echo " status default,"; } //echo $product->insert(); $product_id = $product->update($id); echo $product_id; if ($product_id) { $_SESSION['Psuccess'] = "Product add has updated success"; header('location:../controle.php#tabs-5'); } else { echo " error on update"; } echo "error3,"; } echo "error4"; }