Speedinfo_Opensi - Version 0.3.1

Version Notes

Mise à jour du module vers la version 0.3.1
Pour plus d'informations, se référer à la documentation.

Download this release

Release Info

Developer Magento Core Team
Extension Speedinfo_Opensi
Version 0.3.1
Comparing to
See all releases


Code changes from version 0.3.0 to 0.3.1

app/code/community/Speedinfo/Opensi/Model/Cron.php CHANGED
@@ -63,7 +63,7 @@ class Speedinfo_Opensi_Model_Cron extends Mage_Core_Model_Abstract {
63
  $webservice->setStartedAt($now->format('Y-m-d H:i:s'));
64
  $webservice->save();
65
  }
66
- if ($webserviceName == 'createArticle' || $webserviceName == 'updateArticle') {
67
  $storeId = 0;
68
  $webservice->setStartedAt($now->format('Y-m-d H:i:s'));
69
  $webservice->save();
63
  $webservice->setStartedAt($now->format('Y-m-d H:i:s'));
64
  $webservice->save();
65
  }
66
+ if ($webserviceName == 'createArticle' || $webserviceName == 'updateArticle' || $webserviceName == 'getEtatCommande') {
67
  $storeId = 0;
68
  $webservice->setStartedAt($now->format('Y-m-d H:i:s'));
69
  $webservice->save();
app/code/community/Speedinfo/Opensi/Model/Webservices.php CHANGED
@@ -34,7 +34,11 @@ class Speedinfo_Opensi_Model_Webservices extends Mage_Core_Model_Abstract {
34
 
35
  $httpRequest = $this->create_Zend_Http_Client();
36
  $httpRequest->setAuth($client->webservice_user, $client->webservice_pwd);
37
- $httpRequest->setUri('https://webservices.opensi.eu/cows/Gateway');
 
 
 
 
38
  $httpRequest->resetParameters();
39
  $httpRequest->setParameterGet(array('service_id' => $client->opensi_id, 'action' => $action));
40
 
@@ -279,6 +283,7 @@ class Speedinfo_Opensi_Model_Webservices extends Mage_Core_Model_Abstract {
279
  // ->addAttributeToSelect('*');
280
  // }else{
281
  // $startedAt = new DateTime('1970-01-01');
 
282
  $productCollection = Mage::getModel('catalog/product')->getCollection()
283
  ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
284
  ->addFieldToFilter('type_id', array('nin' => array('configurable', 'grouped')))
@@ -533,14 +538,14 @@ class Speedinfo_Opensi_Model_Webservices extends Mage_Core_Model_Abstract {
533
  unset($stockArticle2);
534
  continue;
535
  }
536
- if ($qty > 0) {
 
537
  $stockArticle2->setQty($qty);
538
  $stockArticle2->setIsInStock(true);
539
- } else {
540
  $stockArticle2->setQty(0);
541
  $stockArticle2->setIsInStock(false);
542
  }
543
-
544
  $stockArticle2->setStoreId($storeId);
545
  $stockArticle2->save();
546
  unset($product);
34
 
35
  $httpRequest = $this->create_Zend_Http_Client();
36
  $httpRequest->setAuth($client->webservice_user, $client->webservice_pwd);
37
+
38
+ $url = 'https://webservices.opensi.eu/cows/Gateway';
39
+ if($client->test_mode)
40
+ $url = 'https://webservices-test.opensi.eu/cows/Gateway';
41
+ $httpRequest->setUri($url);
42
  $httpRequest->resetParameters();
43
  $httpRequest->setParameterGet(array('service_id' => $client->opensi_id, 'action' => $action));
44
 
283
  // ->addAttributeToSelect('*');
284
  // }else{
285
  // $startedAt = new DateTime('1970-01-01');
286
+
287
  $productCollection = Mage::getModel('catalog/product')->getCollection()
288
  ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
289
  ->addFieldToFilter('type_id', array('nin' => array('configurable', 'grouped')))
538
  unset($stockArticle2);
539
  continue;
540
  }
541
+ $stockNegatif = Mage::getStoreConfig('cataloginventory/item_options/backorders', $storeId);
542
+ if ($qty > 0 || $stockNegatif != 0) {
543
  $stockArticle2->setQty($qty);
544
  $stockArticle2->setIsInStock(true);
545
+ }else {
546
  $stockArticle2->setQty(0);
547
  $stockArticle2->setIsInStock(false);
548
  }
 
549
  $stockArticle2->setStoreId($storeId);
550
  $stockArticle2->save();
551
  unset($product);
app/code/community/Speedinfo/Opensi/Model/Webservices.php.bak-2011-04-05 ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Communication des donnees entre opensi et magento
5
+ *
6
+ * @Author Speedinfo
7
+ * http://wwww.speedinfo.fr | http://www.opensi.fr
8
+ */
9
+ class Speedinfo_Opensi_Model_Webservices extends Mage_Core_Model_Abstract {
10
+
11
+ private $error = "";
12
+
13
+ /** Crée l'objet Zend_Http_Client, qu'une fois pour éviter de faire sauter la mémoire **/
14
+ private static $zHttpClient;
15
+
16
+ private function create_Zend_Http_Client(){
17
+ if (!isset(self::$zHttpClient)) {
18
+ self::$zHttpClient = new Zend_Http_Client();
19
+ }
20
+
21
+ return self::$zHttpClient;
22
+ }
23
+
24
+ /**
25
+ * Envoie des donnees au serveur OpenSI
26
+ * @param String $method POST / GET / PUT
27
+ * @param String $action action a effectuer
28
+ * @param String $xmlData donnees a envoyer format XML
29
+ * @param Array $client les infos sur le client opensi
30
+ * @param Array $params liste des parametres a envoyer au serveur
31
+ * @return String $response reponse du serveur
32
+ */
33
+ protected function sendData($method, $action, $xmlData, $client, $params = '') {
34
+
35
+ $httpRequest = $this->create_Zend_Http_Client();
36
+ $httpRequest->setAuth($client->webservice_user, $client->webservice_pwd);
37
+ $httpRequest->setUri('https://webservices.opensi.eu/cows/Gateway');
38
+ $httpRequest->resetParameters();
39
+ $httpRequest->setParameterGet(array('service_id' => $client->opensi_id, 'action' => $action));
40
+
41
+ $log = '';
42
+ if (!empty($xmlData)) {
43
+ $httpRequest->setRawData($xmlData, 'text/xml');
44
+ $log .= $xmlData . ' - ';
45
+ }
46
+ if (!empty($params))
47
+ $httpRequest->setParameterGet($params);
48
+
49
+ //On tente 10 fois de se connecter au serveur
50
+ for ($i = 0; $i < 10; $i++){
51
+ try{
52
+ $response = $httpRequest->request($method);
53
+ }
54
+ catch (Exception $e){
55
+ Mage::log('Exception levée :' . $e->getMessage().'\n'.$xmlData, null, 'opensi.log');
56
+ $response = null;
57
+ }
58
+ //si on a une requête on sort des tentatives
59
+ if(isset($response) && is_object($response)){
60
+ break;
61
+ }else{
62
+ //on attend deux secondes avant de refaire une requete
63
+ sleep(2);
64
+ $response = null;
65
+ }
66
+ }
67
+ //Si reponse pas defini, on leve une exception
68
+ try{
69
+ if(!isset($response)){
70
+ throw new Exception('Pas de reponse renvoyée par httpRequest');
71
+ }
72
+ }
73
+ catch(Exception $e){
74
+ Mage::log('Exception levée : ' . $e->getMessage().'\n'.$xmlData, null, 'opensi.log');
75
+ return null;
76
+ }
77
+
78
+ $log .= $response->getStatus();
79
+ //on gere les logs / erreurs
80
+ if ($response->isError() && $response->getStatus() != '409') {
81
+ $this->setLogs($response, $client, $action);
82
+ Mage::log($log, null, 'opensi.log');
83
+ }
84
+
85
+ $this->_error = $response->getStatus();
86
+
87
+ return $response->getRawBody();
88
+ }
89
+
90
+ protected function createXml() {
91
+ $docXml = new DomDocument('1.0', 'UTF-8');
92
+ $docXml->formatOutput = true;
93
+
94
+ return $docXml;
95
+ }
96
+
97
+ /**
98
+ * Envoie des nouvelles commandes vers OpenSI
99
+ */
100
+ public function createCommandeWeb($startedAt, $client, $storeId) {
101
+ $orderCollection = Mage::getModel('sales/order')->getCollection()
102
+ ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
103
+ ->addFieldToFilter('store_id', $storeId);
104
+ if ($orderCollection->count() > 0) {
105
+ $this->createArticle($startedAt, $client, $storeId);
106
+ $this->createClientWeb($startedAt, $client, $storeId);
107
+ }
108
+
109
+ foreach ($orderCollection as $order) {
110
+ $docXml = $this->createXml();
111
+ $request = $docXml->createElement("request");
112
+
113
+ $docXml->appendChild($request);
114
+ $commandeWeb = $docXml->createElement("Commande_Web");
115
+
116
+ $orderDate = new Datetime($order->getCreatedAt());
117
+ $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
118
+
119
+ // Informations de commande
120
+ $commandeWeb->setAttribute('Num_Com_Web', $order->getIncrementId());
121
+ $commandeWeb->setAttribute('Code_Site_Web', $client->web_site_code);
122
+ if($customer->getId()){
123
+ $commandeWeb->setAttribute('Login', $customer->getId());
124
+ }else{
125
+ $commandeWeb->setAttribute('Login', "Invité");
126
+ }
127
+ $commandeWeb->setAttribute('Date_Commande', $orderDate->format('d-m-Y H:i:s'));
128
+ $shippingDesc = $order->getShippingDescription();
129
+ if (strlen($shippingDesc) > 30) {
130
+ $shippingDesc = explode(' - ', $shippingDesc);
131
+ if (strlen($shippingDesc[1]) > 30){
132
+ $shippingDesc = substr($shippingDesc[1], 0, 29);
133
+ } else {
134
+ $shippingDesc = $shippingDesc[1];
135
+ }
136
+ }
137
+ !empty($shippingDesc) ? $commandeWeb->setAttribute('Mode_Expedition',$shippingDesc) : "";
138
+ $commandeWeb->setAttribute('Edition_TTC', "true");
139
+ // recuperation du taux de tva sur les frais de port
140
+ $taxClassId = Mage::getStoreConfig('tax/classes/shipping_tax_class', $storeId);
141
+ if ($taxClassId != 0) {
142
+ // $taxRequest = Mage::getSingleton('tax/calculation')->getRateRequest($order->getShippingAddress(), $order->getBillingAddress(), "", $storeId);
143
+ $taxRequest = Mage::getSingleton('tax/calculation')->getRateRequest();
144
+ if ($taxRequest->getCustomerClassId()) {
145
+ $percent = Mage::getSingleton('tax/calculation')->getRate($taxRequest->setProductClassId($taxClassId));
146
+ } else if ($taxRequest->getProductClassId()) {
147
+ $percent = Mage::getSingleton('tax/calculation')->getRate($taxRequest->setCustomerClassId($taxClassId));
148
+ } else {
149
+ $percent = 0;
150
+ }
151
+ } else {
152
+ $percent = 0;
153
+ }
154
+ $commandeWeb->setAttribute('Frais_Port', $order->getShippingAmount() * (1 + $percent / 100));
155
+ $commandeWeb->setAttribute('Taux_Tva_Port', $percent);
156
+ $totalTTC = $order->getSubtotal() + $order->getBaseTaxAmount();
157
+ //$commandeWeb->setAttribute('Remise_Pourc', ((($totalTTC - ($order->getBaseGrandTotal() - $order->getBaseShippingAmount())) / $totalTTC) * 100));
158
+ $commandeWeb->setAttribute('Remise_Pourc', '0');
159
+ $commandeWeb->setAttribute('Mode_Reglement', $order->getPayment()->getMethod());
160
+
161
+ // Informations de facturation
162
+ $commandeWeb->setAttribute('Civ_Fact', 0);
163
+ $commandeWeb->setAttribute('Nom_Fact', $order->getBillingAddress()->getLastname());
164
+ $commandeWeb->setAttribute('Prenom_Fact', $order->getBillingAddress()->getFirstname());
165
+ $billingCompany = $order->getBillingAddress()->getCompany();
166
+ if (!empty($billingCompany))
167
+ $commandeWeb->setAttribute('Societe_Fact', $billingCompany);
168
+ $commandeWeb->setAttribute('Adresse_1_Fact', $order->getBillingAddress()->getStreet1());
169
+ $billingStreet2 = $order->getBillingAddress()->getStreet2();
170
+ $billingStreet3 = $order->getBillingAddress()->getStreet3();
171
+ if (!empty($billingStreet2))
172
+ $commandeWeb->setAttribute('Adresse_2_Fact', $billingStreet2);
173
+ if (!empty($billingStreet3))
174
+ $commandeWeb->setAttribute('Adresse_3_Fact', $billingStreet3);
175
+ $commandeWeb->setAttribute('Code_Postal_Fact', $order->getBillingAddress()->getPostcode());
176
+ $commandeWeb->setAttribute('Ville_Fact', $order->getBillingAddress()->getCity());
177
+ $commandeWeb->setAttribute('Code_Pays_Fact', $order->getBillingAddress()->getCountry());
178
+ $billingPhone = $order->getBillingAddress()->getTelephone();
179
+ if (!empty($billingPhone))
180
+ $commandeWeb->setAttribute('Tel_Fact', $billingPhone);
181
+ $billingFax = $order->getBillingAddress()->getFax();
182
+ if (!empty($billingFax))
183
+ $commandeWeb->setAttribute('Fax_Fact', $billingFax);
184
+ $commandeWeb->setAttribute('Email_Fact', $customer->getEmail());
185
+
186
+ //Informations de livraison
187
+ $commandeWeb->setAttribute('Civ_Liv', 0);
188
+ $commandeWeb->setAttribute('Nom_Liv', $order->getShippingAddress()->getLastname());
189
+ $commandeWeb->setAttribute('Prenom_Liv', $order->getShippingAddress()->getFirstname());
190
+ $shippingCompany = $order->getShippingAddress()->getCompany();
191
+ if (!empty($shippingCompany))
192
+ $commandeWeb->setAttribute('Societe_Liv', $shippingCompany);
193
+ $commandeWeb->setAttribute('Adresse_1_Liv', $order->getShippingAddress()->getStreet1());
194
+ $shippingStreet2 = $order->getShippingAddress()->getStreet2();
195
+ $shippingStreet3 = $order->getShippingAddress()->getStreet3();
196
+ if (!empty($shippingStreet2))
197
+ $commandeWeb->setAttribute('Adresse_2_Liv', $shippingStreet2);
198
+ if (!empty($shippingStreet3))
199
+ $commandeWeb->setAttribute('Adresse_3_Liv', $shippingStreet3);
200
+ $commandeWeb->setAttribute('Code_Postal_Liv', $order->getShippingAddress()->getPostcode());
201
+ $commandeWeb->setAttribute('Ville_Liv', $order->getShippingAddress()->getCity());
202
+ $commandeWeb->setAttribute('Code_Pays_Liv', $order->getShippingAddress()->getCountry());
203
+ $shippingPhone = $order->getShippingAddress()->getTelephone();
204
+ if (!empty($shippingPhone))
205
+ $commandeWeb->setAttribute('Tel_Liv', $shippingPhone);
206
+ $shippingFax = $order->getShippingAddress()->getFax();
207
+ if (!empty($shippingFax))
208
+ $commandeWeb->setAttribute('Fax_Liv', $shippingFax);
209
+ $commandeWeb->setAttribute('Email_Liv', $customer->getEmail());
210
+
211
+ $request->appendChild($commandeWeb);
212
+ // Informations du contenu de la commande
213
+ foreach ($order->getAllVisibleItems() as $item) {
214
+ $ligneCommandeClient = $docXml->createElement("Ligne_Commande_Client");
215
+
216
+ if($item->getProductType() == "configurable"){
217
+ $ligneCommandeClient->setAttribute('Reference', substr($item->getProductOptionByCode('simple_sku'),0,39));
218
+ $ligneCommandeClient->setAttribute('Designation', substr($item->getProductOptionByCode('simple_name'),0,99));
219
+ }else{
220
+ $ligneCommandeClient->setAttribute('Reference', substr($item->getSku(),0,39));
221
+ $ligneCommandeClient->setAttribute('Designation', substr($item->getName(),0,99));
222
+ }
223
+ $ligneCommandeClient->setAttribute('Quantite', $item->getQtyOrdered());
224
+
225
+ //TTC
226
+ $rowTotal = $item->getRowTotal() + $item->getTaxAmount();
227
+ $itemTotal = $rowTotal / $item->getQtyOrdered();
228
+ $ligneCommandeClient->setAttribute('Prix_Unitaire', $itemTotal );
229
+
230
+ $discountAmount = $item->getDiscountAmount();
231
+
232
+ //Si il existe une remise en valeur
233
+ if (!empty($discountAmount) && $itemTotal != 0) {
234
+ $discount = (1 - (($itemTotal - $item->getDiscountAmount()) / $itemTotal)) * 100;
235
+ $discount = round($discount, 2);
236
+ }
237
+
238
+ // $discountPourcent = $item->getDiscountPercent();
239
+ // //Si il existe un poucentage de remise.
240
+ // if ($discountPourcent != 0) {
241
+ // $discount = $discountPourcent;
242
+ // }
243
+ // Mage::log($discount, null, 'opensi.log');
244
+ //
245
+ // //Si il existe les 2 types de remise % et montant
246
+ // if (!empty($discountAmount) && !empty($discountPourcent)) {
247
+ // $discountValeurDepuisPourcentage = ($itemTotal * $discountPourcent) / 100;
248
+ // $discountTotalValue = $discountAmount + $discountValeurDepuisPourcentage;
249
+ // $discountPourcent = (1 - (($itemTotal - $discountTotalValue) / $itemTotal)) * 100;
250
+ // $discount = $discountPourcent;
251
+ // Mage::log($discount, null, 'opensi.log');
252
+ // }
253
+
254
+ $ligneCommandeClient->setAttribute('Remise_Pourc', $discount);
255
+ $ligneCommandeClient->setAttribute('Taux_Tva', $item->getTaxPercent());
256
+
257
+ $commandeWeb->appendChild($ligneCommandeClient);
258
+ }
259
+
260
+ // Mage::log($docXml->saveXml(), null, 'opensi.log');
261
+ $this->sendData('POST', 'create_commande_web', $docXml->saveXml(), $client);
262
+ } // endforeach $ordercollection
263
+
264
+ if ($orderCollection->count() > 0) {
265
+ $this->createTransactionBancaire($startedAt, $client, $storeId);
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Envoie des nouveaux produits vers OpenSI
271
+ */
272
+ public function createArticle($startedAt, $client, $storeId) {
273
+ // if(Mage::getVersion() < '1.4.0.0'){
274
+ // $productCollection = Mage::getModel('catalog/product')->getCollection()
275
+ // ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
276
+ // ->addFieldToFilter('type_id', array('nin' => array('configurable', 'grouped')))
277
+ // //->addFieldToFilter('category_ids', array('gteq' => NULL))
278
+ // ->addStoreFilter($storeId)
279
+ // ->addAttributeToSelect('*');
280
+ // }else{
281
+ // $startedAt = new DateTime('1970-01-01');
282
+ $productCollection = Mage::getModel('catalog/product')->getCollection()
283
+ ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
284
+ ->addFieldToFilter('type_id', array('nin' => array('configurable', 'grouped')))
285
+ ->addStoreFilter($storeId)
286
+ ->addAttributeToSelect('*');
287
+ ini_set('max_execution_time', 50 );
288
+ // $time_start = microtime(true);
289
+ foreach ($productCollection as $product) {
290
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
291
+ if (ini_get('max_execution_time') == 100)
292
+ ini_set('max_execution_time', 50 );
293
+ if(!$this->verfiSku($product)){
294
+ continue;
295
+ }
296
+ $articleData = $this->articleData($product, $storeId, 'create', $client);
297
+ if (!empty($articleData))
298
+ $this->sendData('POST', 'create_article', $articleData, $client);
299
+ //Vérifier si 409 ne pas lancer
300
+ if($this->_error != "409")
301
+ $this->setStockArticle($product,$client);
302
+ } // endforeach $productCollection
303
+ // $time_end = microtime(true);
304
+ // $time = $time_end - $time_start;
305
+ // Mage::log("CREATE ARTICLE",null,'opensiTimer.log');
306
+ // Mage::log($time,null,'opensiTimer.log');
307
+ // Mage::log("END CREATE ARTICLE",null,'opensiTimer.log');
308
+ if ($productCollection->count() > 0)
309
+ $this->setPubwebArticle($startedAt, $client, $storeId);
310
+ }
311
+
312
+ /**
313
+ * Envoie des produits modifies vers OpenSI
314
+ */
315
+ public function updateArticle($startedAt, $client, $storeId) {
316
+ $productCollection = Mage::getModel('catalog/product')->getCollection()
317
+ ->addFieldToFilter('updated_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
318
+ ->addFieldToFilter('created_at', array('lteq' => $startedAt->format('Y-m-d H:i:s')))
319
+ ->addFieldToFilter('type_id', array('nin' => array('configurable', 'grouped')))
320
+ ->addStoreFilter($storeId)
321
+ ->addAttributeToSelect('*');
322
+ ini_set('max_execution_time', 50 );
323
+ foreach ($productCollection as $product) {
324
+ if(!$this->verfiSku($product)){
325
+ continue;
326
+ }
327
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
328
+ if (ini_get('max_execution_time') == 100)
329
+ ini_set('max_execution_time', 50 );
330
+ $articleData = $this->articleData($product, $storeId, 'update', $client);
331
+ $params = array('reference' => $product->getSku());
332
+ if (!empty($articleData))
333
+ $this->sendData('PUT', 'update_article', $articleData, $client, $params);
334
+
335
+ //Si le produit ne marche pas en update alors on essai de le créer
336
+ if(!empty($articleData) && $this->_error == "404"){
337
+ $articleData = $this->articleData($product, $storeId, 'create', $client);
338
+ if (!empty($articleData))
339
+ $this->sendData('POST', 'create_article', $articleData, $client);
340
+ //Vérifier si 409 ne pas lancer
341
+ if($this->_error != "409")
342
+ $this->setStockArticle($product,$client);
343
+ }
344
+ } // endforeach $productCollection
345
+ if ($productCollection->count() > 0)
346
+ $this->setPubwebArticle($startedAt, $client, $storeId);
347
+ }
348
+
349
+ /**
350
+ * Creation du XML pour la creation / modification de produits
351
+ */
352
+ public function articleData($product, $storeId, $type, $client) {
353
+ $docXml = $this->createXml();
354
+ $request = $docXml->createElement("request");
355
+
356
+ $docXml->appendChild($request);
357
+ $article = $docXml->createElement('Article');
358
+ try{
359
+ // Informations du produit
360
+ $article->setAttribute('Reference', $product->getSku());
361
+ $article->setAttribute('Designation', substr($product->getName(), 0, 99));
362
+ $article->setAttribute('Description_1', $product->getDescription());
363
+ $shortDescription = $product->getShortDescription();
364
+ if (!empty($shortDescription))
365
+ $article->setattribute('Description_2', $shortDescription);
366
+ $brand = $product->getAttributeText('manufacturer');
367
+ if (!empty($brand))
368
+ $article->setAttribute('Marque', substr($brand, 0, 39));
369
+
370
+ // Gestion des familles
371
+ $fam1 = $this->getSimpleAttributes($product, $client->famille1);
372
+ if (!empty($client->famille1) && !empty($fam1)) {
373
+ $article->setAttribute('Famille_1', substr($this->getSimpleAttributes($product, $client->famille1), 0, 39));
374
+ } else {
375
+ $article->setAttribute('Famille_1', 'NC');
376
+ }
377
+ !empty($client->famille2) && $this->getSimpleAttributes($product, $client->famille2) ? $article->setAttribute('Famille_2', substr($this->getSimpleAttributes($product, $client->famille2), 0, 39)) : false;
378
+ !empty($client->famille3) && $this->getSimpleAttributes($product, $client->famille3) ? $article->setAttribute('Famille_3', substr($this->getSimpleAttributes($product, $client->famille3), 0, 39)) : false;
379
+
380
+ // Gestion des attributs
381
+ !empty($client->attribut1) && $this->getSimpleAttributes($product, $client->attribut1) ? $article->setAttribute('Attribut_1', substr($this->getSimpleAttributes($product, $client->attribut1), 0, 39)) : false;
382
+ !empty($client->attribut2) && $this->getSimpleAttributes($product, $client->attribut2) ? $article->setAttribute('Attribut_2', substr($this->getSimpleAttributes($product, $client->attribut2), 0, 39)) : false;
383
+ !empty($client->attribut3) && $this->getSimpleAttributes($product, $client->attribut3) ? $article->setAttribute('Attribut_3', substr($this->getSimpleAttributes($product, $client->attribut3), 0, 39)) : false;
384
+ !empty($client->attribut4) && $this->getSimpleAttributes($product, $client->attribut4) ? $article->setAttribute('Attribut_4', substr($this->getSimpleAttributes($product, $client->attribut4), 0, 39)) : false;
385
+ !empty($client->attribut5) && $this->getSimpleAttributes($product, $client->attribut5) ? $article->setAttribute('Attribut_5', substr($this->getSimpleAttributes($product, $client->attribut5), 0, 39)) : false;
386
+ !empty($client->attribut6) && $this->getSimpleAttributes($product, $client->attribut6) ? $article->setAttribute('Attribut_6', substr($this->getSimpleAttributes($product, $client->attribut6), 0, 39)) : false;
387
+ !empty($client->code_barre) && $this->getSimpleAttributes($product, $client->code_barre) ? $article->setAttribute('Code_Barre', substr($this->getSimpleAttributes($product, $client->code_barre), 0, 14)) : false;
388
+ !empty($client->volume) && is_numeric($this->getSimpleAttributes($product, $client->volume)) && $this->getSimpleAttributes($product, round($client->volume,2)) ? $article->setAttribute('Volume',$this->getSimpleAttributes($product, round($client->volume,2) )) : false;
389
+ !empty($client->hauteur) && is_numeric($this->getSimpleAttributes($product, $client->hauteur)) && $this->getSimpleAttributes($product, round($client->hauteur,2)) ? $article->setAttribute('Hauteur',$this->getSimpleAttributes($product, round($client->hauteur,2))) : false;
390
+ !empty($client->longueur) && is_numeric($this->getSimpleAttributes($product, $client->longueur)) && $this->getSimpleAttributes($product, round($client->longueur,2)) ? $article->setAttribute('Longueur',$this->getSimpleAttributes($product, round($client->longueur,2))) : false;
391
+ !empty($client->largeur) && is_numeric($this->getSimpleAttributes($product, $client->largeur)) && $this->getSimpleAttributes($product, round($client->largeur,2)) ? $article->setAttribute('Largeur',$this->getSimpleAttributes($product, round($client->largeur,2))) : false;
392
+
393
+ $weight = $product->getWeight();
394
+ if (!empty($weight))
395
+ $article->setAttribute('Poids', $weight);
396
+
397
+ if ($type == 'create') {
398
+ $includeTax = Mage::getStoreConfig('tax/calculation/price_includes_tax', $storeId);
399
+ if ($includeTax) {
400
+ $article->setAttribute('Tarif_TTC_1', $product->getFinalPrice());
401
+ } else {
402
+
403
+ $article->setAttribute('Tarif_HT_1', $product->getFinalPrice());
404
+ }
405
+ $product->getCost() != "" ? $article->setAttribute('Prix_Achat', $product->getCost()) : false;
406
+ // $taxRequest = Mage::getSingleton('tax/calculation');
407
+ // Mage::log(Mage::getSingleton('tax/calculation')->getRate($taxRequest->setProductClassId($product->getTaxClassId())),null,'opensi.log');
408
+ // $product->getTaxPercent() != "" ? $article->setAttribute('Taux_Tva', $product->getTaxPercent()) : false;
409
+ }
410
+ $updatedAt = new Datetime($product->getUpdatedAt());
411
+ $createdAt = new Datetime($product->getCreatedAt());
412
+ $article->setAttribute('Date_M', $updatedAt->format('d-m-Y H:i:s'));
413
+ $article->setAttribute('Date_C', $createdAt->format('d-m-Y H:i:s'));
414
+
415
+ $active = "true";
416
+ $article->setAttribute('Actif', $active);
417
+ }
418
+ catch(Exception $e){
419
+ Mage::log("Erreur ".$e->getMessage(),null,"opensi.log");
420
+ return null;
421
+ }
422
+ $request->appendChild($article);
423
+
424
+ return $docXml->saveXML();
425
+ }
426
+
427
+ /**
428
+ * Envoie des nouveaux clients vers OpenSI
429
+ */
430
+ public function createClientWeb($startedAt, $client, $storeId) {
431
+ $customerCollection = Mage::getModel('customer/customer')->getCollection()
432
+ ->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
433
+ ->addAttributeToSelect('*')
434
+ ->addAttributeToFilter('website_id', Mage::getModel('core/store')->load($storeId)->getWebsiteId());
435
+ ini_set('max_execution_time', 50 );
436
+ foreach ($customerCollection as $customer) {
437
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
438
+ if (ini_get('max_execution_time') == 100)
439
+ ini_set('max_execution_time', 50 );
440
+ $clientData = $this->clientData($customer, $client);
441
+ $this->sendData('POST', 'create_client_web', $clientData, $client);
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Envoie des clients modifies vers OpenSI
447
+ */
448
+ public function updateClientWeb($startedAt, $client, $storeId) {
449
+ $customerCollection = Mage::getModel('customer/customer')->getCollection()
450
+ ->addFieldToFilter('updated_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
451
+ ->addFieldToFilter('created_at', array('lteq' => $startedAt->format('Y-m-d H:i:s')))
452
+ ->addAttributeToSelect('*')
453
+ ->addAttributeToFilter('website_id', Mage::getModel('core/store')->load($storeId)->getWebsiteId());
454
+ ini_set('max_execution_time', 50 );
455
+ foreach ($customerCollection as $customer) {
456
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
457
+ if (ini_get('max_execution_time') == 100)
458
+ ini_set('max_execution_time', 50 );
459
+ $clientData = $this->clientData($customer, $client);
460
+ $params = array('code_site_web' => $client->web_site_code, 'login' => $customer->getId());
461
+ $this->sendData('PUT', 'update_client_web', $clientData, $client, $params);
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Creation du XML pour la creation / modification de clients
467
+ */
468
+ public function clientData($customer, $client) {
469
+ $docXml = $this->createXml();
470
+ $request = $docXml->createElement("request");
471
+
472
+ $docXml->appendChild($request);
473
+ $clientWeb = $docXml->createElement('Client_Web');
474
+
475
+ // Informations du client
476
+ $clientWeb->setAttribute('Code_Site_Web', $client->web_site_code);
477
+ $clientWeb->setAttribute('Login', $customer->getId());
478
+ $clientWeb->setAttribute('Civilite', '0');
479
+ $clientWeb->setAttribute('Nom', $customer->getLastname());
480
+ $clientWeb->setAttribute('Prenom', $customer->getFirstname());
481
+ $address = Mage::getModel('customer/address')->load((int)$customer->getDefaultBilling());
482
+ $streets = $address->getStreet();
483
+ $postCode = $address->getPostcode();
484
+ $countryId= $address->getCountryId();
485
+ $city = $address->getCity();
486
+ $telephone = $address->getTelephone();
487
+ $fax = $address->getFax();
488
+ $company = $address->getCompany();
489
+
490
+ if(!empty($streets)){
491
+ isset($streets[0]) ? $clientWeb->setAttribute('Adresse_1', $streets[0] ? $streets[0] : 'NC') : 'NC';
492
+ isset($streets[1]) ? $clientWeb->setAttribute('Adresse_2', $streets[1] ? $streets[1] : '') : '';
493
+ }else{
494
+ $clientWeb->setAttribute('Adresse_1', 'NC');
495
+ }
496
+ $clientWeb->setAttribute('Ville', $city ? $city : 'NC');
497
+ $clientWeb->setAttribute('Code_Pays', $countryId ? $countryId : 'FR');
498
+ $clientWeb->setAttribute('Code_Postal', $postCode ? $postCode : '');
499
+ $clientWeb->setAttribute('Telephone', $telephone ? $telephone : '');
500
+ $clientWeb->setAttribute('Fax', $fax ? $fax : '');
501
+ $clientWeb->setAttribute('Societe', $company ? substr($company,0,49) : '');
502
+ $clientWeb->setAttribute('Email', $customer->getEmail());
503
+
504
+ $request->appendChild($clientWeb);
505
+
506
+ return $docXml->saveXML();
507
+ }
508
+
509
+ /**
510
+ * Recuperation des stocks depuis OpenSI et mise a jour du site
511
+ */
512
+ public function getStockArticle($startedAt, $client, $storeId) {
513
+ $params = array('code_depot' => $client->deposit, 'date_debut' => $startedAt->format('d-m-Y'));
514
+ $resultXML = $this->sendData("GET", "get_stock_article", "", $client, $params);
515
+ ini_set('max_execution_time', 50 );
516
+
517
+ $xmlDomDocument = new DomDocument();
518
+ $result = $xmlDomDocument->loadXML($resultXML);
519
+ $stockArticles = $xmlDomDocument->getElementsByTagName("Stock_Article");
520
+ //$time_start = microtime(true);
521
+ foreach ($stockArticles as $stockArticle) {
522
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
523
+ if (ini_get('max_execution_time') == 100)
524
+ ini_set('max_execution_time', 50 );
525
+ try{
526
+ $sku = $stockArticle->getAttribute('Reference');
527
+ $qty = $stockArticle->getAttribute('Stock_Dispo');
528
+ $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
529
+ if ($product && $product->getTypeId() != "bundle") {
530
+ $stockArticle2 = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
531
+ if($stockArticle2->getQty() == $qty){
532
+ unset($product);
533
+ unset($stockArticle2);
534
+ continue;
535
+ }
536
+ if ($qty > 0) {
537
+ $stockArticle2->setQty($qty);
538
+ $stockArticle2->setIsInStock(true);
539
+ } else {
540
+ $stockArticle2->setQty(0);
541
+ $stockArticle2->setIsInStock(false);
542
+ }
543
+
544
+ $stockArticle2->setStoreId($storeId);
545
+ $stockArticle2->save();
546
+ unset($product);
547
+ unset($stockArticle2);
548
+ }
549
+ }catch(Exception $e){
550
+ Mage::log($e,null,'opensi.log');
551
+ }
552
+ }
553
+ // $time_end = microtime(true);
554
+ // $time = $time_end - $time_start;
555
+ // Mage::log("GET STOCK",null,'opensiTimer.log');
556
+ // Mage::log($time,null,'opensiTimer.log');
557
+ // Mage::log("END GET STOCK",null,'opensiTimer.log');
558
+ }
559
+
560
+ /**
561
+ * Envoi des stocks depuis le site à Opensi
562
+ */
563
+ public function setStockArticle($product, $client) {
564
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId())->getQty();
565
+
566
+ $docXml = $this->createXml();
567
+ $request = $docXml->createElement("request");
568
+
569
+ $docXml->appendChild($request);
570
+ $stockArticle = $docXml->createElement("Invperm_Article");
571
+ $stockArticle->setAttribute('Code_Depot', $client->deposit);
572
+ $stockArticle->setAttribute('Reference', $product->getSku());
573
+ $stockArticle->setAttribute('Stock_Reel', $stock ? round($stock,3) : 0);
574
+ $request->appendChild($stockArticle);
575
+
576
+ $this->sendData('POST', 'create_invperm_article', $docXml->saveXml(), $client);
577
+ }
578
+
579
+ /**
580
+ * Envoie des infos de paiement a OpenSI
581
+ */
582
+ public function createTransactionBancaire($startedAt, $client, $storeId) {
583
+ //recuperation des commandes
584
+ $orderCollection = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('created_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))->addFieldToFilter('store_id', $storeId);
585
+ ini_set('max_execution_time', 50 );
586
+ foreach ($orderCollection as $order) {
587
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
588
+ if (ini_get('max_execution_time') == 100)
589
+ ini_set('max_execution_time', 50 );
590
+
591
+ $numOrder = $order->getIncrementId();
592
+
593
+ //Test pour savoir si la commande est déjà payée
594
+ $params = array('code_site_web' => $client->web_site_code, 'num_com_web' => $numOrder, 'date_debut' => "01-01-1970");
595
+ $resultXML = $this->sendData("GET", "get_etat_commande", "", $client, $params);
596
+
597
+ $xmlDomDocument = new DomDocument();
598
+ $xmlDomDocument->loadXML($resultXML);
599
+ $etatCommande = $xmlDomDocument->getElementsByTagName("Etat_Commande")->item(0);
600
+ if ($etatCommande->getAttribute('Statut_Paiement') == 'T')
601
+ continue;
602
+
603
+
604
+ $methodPayment = $order->getPayment()->getMethod();
605
+ $numeroTransaction = $numOrder;
606
+
607
+ $invoiceCollection = Mage::getResourceModel('sales/order_invoice_collection')
608
+ ->addAttributeToSelect('order_id')
609
+ ->addAttributeToSelect('increment_id')
610
+ ->addAttributeToSelect('created_at')
611
+ ->addAttributeToSelect('state')
612
+ ->addAttributeToSelect('base_grand_total')
613
+ ->setOrderFilter($order);
614
+
615
+ $dateTransaction = "";
616
+ $montant = 0;
617
+ $bool = false;
618
+ foreach ($invoiceCollection as $invoice) {
619
+ //On vérifie que la facture est payé
620
+ if ($invoice->getState() == 2) {
621
+ $bool = true;
622
+ $dateTransaction = $invoice->getCreatedAt();
623
+ $montant += $invoice->getBaseGrandTotal();
624
+ }
625
+ }
626
+
627
+ if ($bool) {
628
+ $dateTransaction = new Datetime($dateTransaction);
629
+
630
+ $docXml = $this->createXml();
631
+ $request = $docXml->createElement("request");
632
+
633
+ $docXml->appendChild($request);
634
+ $transactionComWeb = $docXml->createElement("Transaction_Com_Web");
635
+
636
+ $transactionComWeb->setAttribute('Code_Site_Web', $client->web_site_code);
637
+ $transactionComWeb->setAttribute('Num_Com_Web', $numOrder);
638
+ $transactionComWeb->setAttribute('Num_Transaction', $numeroTransaction);
639
+ $transactionComWeb->setAttribute('Mode_Reglement', $methodPayment);
640
+ $transactionComWeb->setAttribute('Date_Transaction', $dateTransaction->format('d-m-Y'));
641
+ $transactionComWeb->setAttribute('Montant', $montant);
642
+
643
+ $request->appendChild($transactionComWeb);
644
+
645
+ $this->sendData('POST', 'create_transaction_bancaire', $docXml->saveXml(), $client);
646
+ }
647
+ }
648
+ }
649
+
650
+ /**
651
+ * Recuperation des etats de commande depuis OpenSI et mise a jour du site
652
+ */
653
+ public function getEtatCommande($startedAt, $client, $storeId) {
654
+ $params = array('code_site_web' => $client->web_site_code, 'date_debut' => $startedAt->format('d-m-Y'));
655
+ $resultXML = $this->sendData("GET", "get_etat_commande", "", $client, $params);
656
+
657
+ $xmlDomDocument = new DomDocument();
658
+ $xmlDomDocument->loadXML($resultXML);
659
+ $listEtatCommande = $xmlDomDocument->getElementsByTagName("Etat_Commande");
660
+ ini_set('max_execution_time', 50 );
661
+ foreach ($listEtatCommande as $etatCommande) {
662
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
663
+ if (ini_get('max_execution_time') == 100)
664
+ ini_set('max_execution_time', 50 );
665
+ $order = Mage::getModel('sales/order')->loadByIncrementId($etatCommande->getAttribute('Num_Com_Web'));
666
+
667
+ if (!$order->getId()) {
668
+ continue;
669
+ }
670
+
671
+ $status = $order->getStatus();
672
+ //Mage::log($order->getIncrementId()." ".$order->getStatus()." ".$etatCommande->getAttribute('Statut_Paiement')." ".$etatCommande->getAttribute('Statut_Logistique')." ".$etatCommande->getAttribute('Etat') ,null,'opensi.log');
673
+ //recup du statut de paiement = si termine on facture pour considerer la commande paye
674
+ if ($etatCommande->getAttribute('Statut_Paiement') == 'T') {
675
+
676
+ if ($order->canInvoice()) {
677
+ // $invoiceCollection = $order->getInvoiceCollection();
678
+ // $invoiceId = '';
679
+ // foreach ($invoiceCollection as $invoice) {
680
+ // $invoiceId = $invoice->getIncrementId();
681
+ // }
682
+ //
683
+ // if (empty($invoiceId))
684
+ // $invoiceId = Mage::getModel('sales/order_invoice_api')->create($order->getIncrementId(), array());
685
+ //
686
+ // $invoice = Mage::getModel('sales/order_invoice')->loadByIncrementId($invoiceId);
687
+ // if ($invoice->canCapture()) {
688
+ // $invoice->capture();
689
+ // }
690
+ $invoiceCollection = $order->getInvoiceCollection();
691
+ $invoiceId = '';
692
+ foreach ($invoiceCollection as $invoice) {
693
+ $invoiceId = $invoice->getIncrementId();
694
+ }
695
+
696
+ if (empty($invoiceId)){
697
+ $convertor = Mage::getModel('sales/convert_order');
698
+
699
+ $invoice = $convertor->toInvoice($order);
700
+
701
+ foreach ($order->getAllItems() as $orderItem) {
702
+ if (!$orderItem->getQtyToInvoice()) {
703
+ continue;
704
+ }
705
+
706
+ $item = $convertor->itemToInvoiceItem($orderItem);
707
+ $item->setQty($orderItem->getQtyToInvoice());
708
+ $invoice->addItem($item);
709
+ }
710
+ $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
711
+ $invoice->collectTotals();
712
+ $invoice->register()->pay();
713
+
714
+ $invoice->save();
715
+ }
716
+ }
717
+ $order->save();
718
+ }
719
+
720
+ //recup du statut de livraison | E = Expediée
721
+ if ($etatCommande->getAttribute('Statut_Logistique') == 'E') {
722
+
723
+ if ($order->canShip()) {
724
+ $shipmentCollection = $order->getShipmentsCollection();
725
+ $shipmentId = '';
726
+ foreach ($shipmentCollection as $shipment) {
727
+ $shipmentId = $shipment->getIncrementId();
728
+ }
729
+ if (empty($shipmentId))
730
+ $shipmentId = Mage::getModel('sales/order_shipment_api')->create($order->getIncrementId(), array());
731
+ }
732
+ $order->save();
733
+ }
734
+
735
+ //passer derniere valeur a true pour envoyer mail au client
736
+ switch ($etatCommande->getAttribute('Etat')) {
737
+ case 'N': //Non validée
738
+ if ($status != 'pending' && $status != 'processing')
739
+ $order->setState('pending', true, 'changement de statut OpenSI (Pending)', true);
740
+ break;
741
+
742
+ case 'T': // En cours mais validée
743
+ if ($status != 'processing')
744
+ $order->setState('processing', true, 'changement de statut OpenSI (Processing)', true);
745
+ break;
746
+
747
+ case 'A': // Annulée
748
+ if ($status != 'canceled')
749
+ $order->setState('canceled', true, 'changement de statut OpenSI (Canceled)', true);
750
+ break;
751
+
752
+ case 'C': // Cloturée expédiée et facturée
753
+ if ($status != 'complete' && Mage::getVersion() < '1.4.0.0'){
754
+ $order->setState('complete', true, 'changement de statut OpenSI (Complete)', true);
755
+ }
756
+ break;
757
+ }
758
+ $order->save();
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Recuperation des infos de suivi de colis depuis OpenSI et mise a jour du site
764
+ */
765
+ public function getTrackingColis($startedAt, $client, $storeId) {
766
+ $now = new Datetime();
767
+ $params = array('code_site_web' => $client->web_site_code, 'date_debut' => $startedAt->format('d-m-Y'), 'date_fin' => $now->format('d-m-Y'));
768
+ $resultXML = $this->sendData("GET", "get_tracking_colis", "", $client, $params);
769
+
770
+ $xmlDomDocument = new DomDocument();
771
+ $xmlDomDocument->loadXML($resultXML);
772
+ $listExpedition = $xmlDomDocument->getElementsByTagName("Colis_Expedition");
773
+ ini_set('max_execution_time', 50 );
774
+ foreach ($listExpedition as $expedition) {
775
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
776
+ if (ini_get('max_execution_time') == 100)
777
+ ini_set('max_execution_time', 50 );
778
+ $order = Mage::getModel('sales/order')->loadByIncrementId($expedition->getAttribute('Num_Com_Web'));
779
+ /**
780
+ * Check order existing
781
+ */
782
+ if (!$order->getId()) {
783
+ continue;
784
+ }
785
+ /**
786
+ * Check shipment create availability
787
+ */
788
+ if (!$order->canShip()) {
789
+ continue;
790
+ }
791
+ $shipmentCollection = $order->getShipmentsCollection();
792
+ $shipmentId = '';
793
+ foreach ($shipmentCollection as $shipment) {
794
+ $shipmentId = $shipment->getIncrementId();
795
+ }
796
+ if (empty($shipmentId))
797
+ $shipmentId = Mage::getModel('sales/order_shipment_api')->create($order->getIncrementId(), array());
798
+ $track = Mage::getModel('sales/order_shipment_api')->addTrack($shipmentId, "custom", $expedition->getAttribute('Transporteur') . ' - ' . $expedition->getAttribute('Mode_Expedition'), $expedition->getAttribute('Num_Colis'));
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Recuperation des publications de produits depuis OpenSI et mise a jour du site
804
+ */
805
+ public function getPubwebArticle($startedAt, $client, $storeId) {
806
+ $params = array('code_site_web' => $client->web_site_code, 'date_debut' => $startedAt->format('d-m-Y'));
807
+ $resultXML = $this->sendData("GET", "get_pubweb_article", "", $client, $params);
808
+
809
+ $xmlDomDocument = new DomDocument();
810
+ $xmlDomDocument->loadXML($resultXML);
811
+ $listPublicationArticle = $xmlDomDocument->getElementsByTagName("Pubweb_Article");
812
+ ini_set('max_execution_time', 50 );
813
+ foreach ($listPublicationArticle as $publicationArticle) {
814
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
815
+ if (ini_get('max_execution_time') == 100)
816
+ ini_set('max_execution_time', 50 );
817
+ $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $publicationArticle->getAttribute('Reference'));
818
+ if ($product) {
819
+ if ($publicationArticle->getAttribute('Publication') == "true") {
820
+ $product->setStatus('1');
821
+ } else {
822
+ $product->setStatus('2');
823
+ }
824
+
825
+ $product->setStoreId($storeId);
826
+ $product->save();
827
+ }
828
+ }
829
+ }
830
+
831
+ /**
832
+ * Envoie des publications a OpenSI
833
+ */
834
+ public function setPubwebArticle($startedAt, $client, $storeId) {
835
+ $productCollection = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter('updated_at', array('gteq' => $startedAt->format('Y-m-d H:i:s')))
836
+ ->addStoreFilter($storeId)
837
+ ->addAttributeToSelect(array('sku', 'status'));
838
+ ini_set('max_execution_time', 50 );
839
+ foreach ($productCollection as $product) {
840
+ if(!$this->verfiSku($product)){
841
+ continue;
842
+ }
843
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
844
+ if (ini_get('max_execution_time') == 100)
845
+ ini_set('max_execution_time', 50 );
846
+ $docXml = $this->createXml();
847
+ $request = $docXml->createElement("request");
848
+
849
+ $docXml->appendChild($request);
850
+ $pubWebArticle = $docXml->createElement("Pubweb_Article");
851
+
852
+ $pubWebArticle->setAttribute('Reference', $product->getSku());
853
+ $pubWebArticle->setAttribute('Code_Site_Web', $client->web_site_code);
854
+ if ($product->getStatus() == 2) {
855
+ $pubWebArticle->setAttribute('Publication', "false");
856
+ } else {
857
+ $pubWebArticle->setAttribute('Publication', "true");
858
+ }
859
+
860
+ $request->appendChild($pubWebArticle);
861
+
862
+ $params = array('reference' => $product->getSku());
863
+ $this->sendData('PUT', 'update_pubweb_article', $docXml->saveXml(), $client, $params);
864
+ } // endforeach $productCollection
865
+ }
866
+
867
+ /**
868
+ * Recuperation des prix produits depuis OpenSI et mise a jour du site
869
+ */
870
+ public function getPrixArticle($startedAt, $client, $storeId) {
871
+ $params = array('code_site_web' => $client->web_site_code, 'date_debut' => $startedAt->format('d-m-Y'));
872
+ $resultXML = $this->sendData("GET", "get_prix_article", "", $client, $params);
873
+ $xmlDomDocument = new DomDocument();
874
+ $xmlDomDocument->loadXML($resultXML);
875
+ $listPrixArticle = $xmlDomDocument->getElementsByTagName("Prix_Article");
876
+ //Verif si dans la configuration le prix est TTC ou HT
877
+ $includeTax = Mage::getStoreConfig('tax/calculation/price_includes_tax', $storeId);
878
+ ini_set('max_execution_time', 50 );
879
+ foreach ($listPrixArticle as $prixArticle) {
880
+ ini_set('max_execution_time', ini_get('max_execution_time')+1 );
881
+ if (ini_get('max_execution_time') == 100)
882
+ ini_set('max_execution_time', 50 );
883
+ $reference = $prixArticle->getAttribute('Reference');
884
+ $tarifHT = $prixArticle->getAttribute('Tarif_HT_1');
885
+ $tarifTTC = $prixArticle->getAttribute('Tarif_TTC_1');
886
+ $prixAchat = $prixArticle->getAttribute('Prix_Achat');
887
+ $product = Mage::getModel('catalog/product')->loadByAttribute("sku", $reference);
888
+ if ($product && $product->getTypeId() != "bundle") {
889
+ if ($includeTax) {
890
+ if($product->getPrice() == $tarifTTC && $product->getCost() == $prixAchat)
891
+ continue;
892
+ $product->setPrice($tarifTTC);
893
+ } else {
894
+ if($product->getPrice() == $tarifHT && $product->getCost() == $prixAchat)
895
+ continue;
896
+ $product->setPrice($tarifHT);
897
+ }
898
+ $product->setCost($prixAchat);
899
+ $product->setStoreId($storeId);
900
+ $product->save();
901
+ }
902
+ }
903
+ }
904
+
905
+ /**
906
+ * On log les erreurs pour les afficher dans l'interface
907
+ */
908
+ public function setLogs($response, $client, $action) {
909
+ $errorLogs = Mage::getModel("opensi/errorlog");
910
+ $errorLogs->setErrorCode($response->getStatus());
911
+ $errorLogs->setErrorMessage(utf8_encode($response->getMessage()));
912
+ $errorLogs->setOpensiId($client->opensi_id);
913
+ $errorLogs->setOpensiAction($action);
914
+ $createdAt = new dateTime();
915
+ $errorLogs->setCreatedAt($createdAt->format('Y-m-d H:i:s'));
916
+ $errorLogs->setStoreId($client->store_id);
917
+ $errorLogs->save();
918
+ }
919
+
920
+ protected function getSimpleAttributes($product, $idAttribute) {
921
+ $attribute = Mage::getModel('eav/entity_attribute')->load($idAttribute);
922
+ if ($product->getData($attribute->getAttributeCode())) {
923
+ return $product->getResource()->getAttribute($attribute->getAttributeCode())->getFrontend()->getValue($product);
924
+ } else {
925
+ return '';
926
+ }
927
+ }
928
+
929
+ protected function verfiSku($product){
930
+ $sku = $product->getSku();
931
+ $designation = $product->getName();
932
+ if($sku[0] == " "){
933
+ Mage::log('Error espace avant référence '.$sku,null,'opensi.log');
934
+ return false;
935
+ }elseif(strlen($sku) > 40){
936
+ Mage::log('Référence trop longue '.$sku,null,'opensi.log');
937
+ return false;
938
+ }elseif(strlen($designation) > 100){
939
+ Mage::log('Le nom est trop long '.$designation,null,'opensi.log');
940
+ return false;
941
+ }elseif(empty($sku)){
942
+ Mage::log('Pas de référence',null,'opensi.log');
943
+ return false;
944
+ }
945
+ return true;
946
+ }
947
+
948
+ }
app/code/community/Speedinfo/Opensi/etc/config.xml CHANGED
@@ -2,7 +2,7 @@
2
  <config>
3
  <modules>
4
  <Speedinfo_Opensi>
5
- <version>0.3.0</version>
6
  </Speedinfo_Opensi>
7
  </modules>
8
  <global>
2
  <config>
3
  <modules>
4
  <Speedinfo_Opensi>
5
+ <version>0.3.1</version>
6
  </Speedinfo_Opensi>
7
  </modules>
8
  <global>
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Speedinfo_Opensi</name>
4
- <version>0.3.0</version>
5
  <stability>stable</stability>
6
  <license>GPL</license>
7
  <channel>community</channel>
@@ -10,12 +10,12 @@
10
  <description>Le module OpenSi Connect vous permet de coupler Magento au logiciel de gestion commerciale et de comptabilit&#xE9; OpenSi E-Commerce.
11
  Speedinfo a con&#xE7;u un connecteur pour OpenSi E-Commerce et Magento sous la forme du module OpenSi Connect
12
  OpenSi E-Commerce, est un logiciel de gestion commerciale et de comptabilit&#xE9; d&#xE9;di&#xE9; &#xE0; l'e-commerce.</description>
13
- <notes>Mise &#xE0; jour du module vers la version 0.3.0
14
  Pour plus d'informations, se r&#xE9;f&#xE9;rer &#xE0; la documentation.</notes>
15
  <authors><author><name>Dray</name><user>auto-converted</user><email>rony.dray@speedinfo.fr</email></author></authors>
16
- <date>2011-03-17</date>
17
- <time>10:02:04</time>
18
- <contents><target name="mage"><dir name="app"><dir name="design"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="opensi"><dir name="tab"><file name="webservices.phtml" hash="44197706123f54d5c2e17475cd64b9f1"/></dir></dir></dir></dir></dir></dir></dir><dir name="etc"><dir name="modules"><file name="Speedinfo_Opensi.xml" hash="16cc3fbf8e32ce7b8add016bfbc89c5f"/></dir></dir><dir name="locale"><dir name="fr_FR"><file name="Speedinfo_OpenSi.csv" hash="51f46b50056059d178766fa9111fe072"/></dir></dir></dir></target><target name="magecommunity"><dir name="Speedinfo"><dir name="Opensi"><dir name="Block"><dir name="Adminhtml"><dir name="Edit"><dir name="Tab"><file name="Attributs.php" hash="562e895af0d5f2a1cffa1be63d0b5fa4"/><file name="Familles.php" hash="317e2361f1dcb6c494ca9ab6bf0d5cae"/><file name="General.php" hash="485e888e215dde1762a42d147cced3e1"/><file name="Webservices.php" hash="09ccc564f6ba4e7cbb58e0357c43e035"/></dir><file name="Form.php" hash="3ce2dc7af0ec4c5a44178ac46d6178a8"/></dir><file name="Edit.php" hash="b91602dd06e9432d879db352fa2aaeaa"/><file name="Grid.php" hash="6ace416ae5264fed2bbc57aa5d152e6e"/><file name="Tabs.php" hash="4383dd11c3e1fffe43868e489f6b977f"/></dir></dir><dir name="controllers"><file name="IndexController.php" hash="9754ad25b294a0306d4e28090bf9e4cb"/></dir><dir name="etc"><file name="config.xml" hash="60f8666ee77ff7ffcebed04fc9b898f4"/></dir><dir name="Helper"><file name="Data.php" hash="b5798cdae9319b34ada4c3de5964c0b4"/></dir><dir name="Model"><dir name="Mysql4"><dir name="Errorlog"><file name="Collection.php" hash="ad19bb95ad5e56f0dcaeff4db10cf52f"/></dir><dir name="Webservice"><file name="Collection.php" hash="3a5e5d973ffb834d4eadec4f9335b36e"/></dir><file name="Client.php" hash="0b47754c6aace0dc54340dfd807eb17a"/><file name="Errorlog.php" hash="9a8c882377bbdeada65c7c5d8346af35"/><file name="Webservice.php" hash="781eb93e76ba8bffe881f091904d0f98"/></dir><file name="Client.php" hash="f89aeb3dda8d8a27bf6a05e5082a945e"/><file name="Cron.php" hash="3f231dd81c71238d7e7efaa144ded9af"/><file name="Errorlog.php" hash="d269ec20ae481684a1daa2c515848252"/><file name="Webservice.php" hash="c77708c3507d79a83e64a1801ea255c2"/><file name="Webservices.php" hash="ea0b1c8dd9dd778e864c7cafc69e37e5"/></dir><dir name="sql"><dir name="opensi_setup"><file name="mysql4-install-0.1.0.php" hash="ce8cef17aac76ccfadf09d7d84d23841"/><file name="mysql4-upgrade-0.2.0-0.2.1.php" hash="f207b0704a6cad542dced6b40ac25341"/><file name="mysql4-upgrade-0.2.4-0.2.5.php" hash="99fcd03734f514441005dd8af5c22809"/></dir></dir></dir></dir></target></contents>
19
  <compatible/>
20
  <dependencies/>
21
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Speedinfo_Opensi</name>
4
+ <version>0.3.1</version>
5
  <stability>stable</stability>
6
  <license>GPL</license>
7
  <channel>community</channel>
10
  <description>Le module OpenSi Connect vous permet de coupler Magento au logiciel de gestion commerciale et de comptabilit&#xE9; OpenSi E-Commerce.
11
  Speedinfo a con&#xE7;u un connecteur pour OpenSi E-Commerce et Magento sous la forme du module OpenSi Connect
12
  OpenSi E-Commerce, est un logiciel de gestion commerciale et de comptabilit&#xE9; d&#xE9;di&#xE9; &#xE0; l'e-commerce.</description>
13
+ <notes>Mise &#xE0; jour du module vers la version 0.3.1
14
  Pour plus d'informations, se r&#xE9;f&#xE9;rer &#xE0; la documentation.</notes>
15
  <authors><author><name>Dray</name><user>auto-converted</user><email>rony.dray@speedinfo.fr</email></author></authors>
16
+ <date>2011-04-05</date>
17
+ <time>08:31:48</time>
18
+ <contents><target name="mage"><dir name="app"><dir name="design"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="opensi"><dir name="tab"><file name="webservices.phtml" hash="44197706123f54d5c2e17475cd64b9f1"/></dir></dir></dir></dir></dir></dir></dir><dir name="etc"><dir name="modules"><file name="Speedinfo_Opensi.xml" hash="16cc3fbf8e32ce7b8add016bfbc89c5f"/></dir></dir><dir name="locale"><dir name="fr_FR"><file name="Speedinfo_OpenSi.csv" hash="51f46b50056059d178766fa9111fe072"/></dir></dir></dir></target><target name="magecommunity"><dir name="Speedinfo"><dir name="Opensi"><dir name="Block"><dir name="Adminhtml"><dir name="Edit"><dir name="Tab"><file name="Attributs.php" hash="562e895af0d5f2a1cffa1be63d0b5fa4"/><file name="Familles.php" hash="317e2361f1dcb6c494ca9ab6bf0d5cae"/><file name="General.php" hash="485e888e215dde1762a42d147cced3e1"/><file name="Webservices.php" hash="09ccc564f6ba4e7cbb58e0357c43e035"/></dir><file name="Form.php" hash="3ce2dc7af0ec4c5a44178ac46d6178a8"/></dir><file name="Edit.php" hash="b91602dd06e9432d879db352fa2aaeaa"/><file name="Grid.php" hash="6ace416ae5264fed2bbc57aa5d152e6e"/><file name="Tabs.php" hash="4383dd11c3e1fffe43868e489f6b977f"/></dir></dir><dir name="controllers"><file name="IndexController.php" hash="9754ad25b294a0306d4e28090bf9e4cb"/></dir><dir name="etc"><file name="config.xml" hash="fd89cf2560305e2e2e3aa5ad5e4d2b4c"/></dir><dir name="Helper"><file name="Data.php" hash="b5798cdae9319b34ada4c3de5964c0b4"/></dir><dir name="Model"><dir name="Mysql4"><dir name="Errorlog"><file name="Collection.php" hash="ad19bb95ad5e56f0dcaeff4db10cf52f"/></dir><dir name="Webservice"><file name="Collection.php" hash="3a5e5d973ffb834d4eadec4f9335b36e"/></dir><file name="Client.php" hash="0b47754c6aace0dc54340dfd807eb17a"/><file name="Errorlog.php" hash="9a8c882377bbdeada65c7c5d8346af35"/><file name="Webservice.php" hash="781eb93e76ba8bffe881f091904d0f98"/></dir><file name="Client.php" hash="f89aeb3dda8d8a27bf6a05e5082a945e"/><file name="Cron.php" hash="c2dccdfb120a3d8639ff88523c1e655e"/><file name="Errorlog.php" hash="d269ec20ae481684a1daa2c515848252"/><file name="Webservice.php" hash="c77708c3507d79a83e64a1801ea255c2"/><file name="Webservices.php" hash="6eabfe23f27a81dbd4af0330fe61e0ba"/><file name="Webservices.php.bak-2011-04-05" hash="ea0b1c8dd9dd778e864c7cafc69e37e5"/></dir><dir name="sql"><dir name="opensi_setup"><file name="mysql4-install-0.1.0.php" hash="ce8cef17aac76ccfadf09d7d84d23841"/><file name="mysql4-upgrade-0.2.0-0.2.1.php" hash="f207b0704a6cad542dced6b40ac25341"/><file name="mysql4-upgrade-0.2.4-0.2.5.php" hash="99fcd03734f514441005dd8af5c22809"/></dir></dir></dir></dir></target></contents>
19
  <compatible/>
20
  <dependencies/>
21
  </package>