· 4 years ago · Apr 18, 2021, 03:44 AM
1<?php
2include 'json.bk.php';
3
4add_filter('woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4);
5function my_woocommerce_rest_check_permissions($permission, $context, $object_id, $post_type)
6{
7 return true;
8}
9
10function get_wc_product_by_title($title, $sku)
11{
12 global $wpdb;
13 global $postTitle;
14
15 $post_title = trim(urldecode(strval($title)));
16 //$title_name_marca = $post_title . ", ". $post_marca;
17 echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
18 //var_dump();
19 $post_table = $wpdb->prefix . "posts";
20 /*
21 $result = $wpdb->get_col(
22 "SELECT
23 posts.ID, posts.post_title
24 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
25 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
26 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
27 INNER JOIN wp_terms AS terms
28 ON term_taxonomy.term_id = terms.term_id
29 WHERE term_taxonomy.taxonomy = 'product_type'
30 AND posts.post_title = $title_name_marca'
31 AND posts.post_type = 'product'"
32 );*/
33
34 //var_dump($post_title);
35 //var_dump($result);
36 // We exit if title doesn't match
37 $sql1 = "SELECT DISTINCT post.ID
38 FROM wp_posts AS post
39 LEFT JOIN wp_postmeta AS metaSku ON post.ID = metaSku.post_id
40 AND metaSku.meta_key = '_sku'
41 LEFT JOIN wp_postmeta AS metaPrice ON post.ID = metaPrice.post_id
42 AND metaPrice.meta_key = '_price'
43 LEFT JOIN wp_postmeta AS metaPriceRegular ON post.ID = metaPriceRegular.post_id
44 WHERE post.post_type = 'product'
45 AND post.post_status NOT IN('trash')
46 AND metaSku.meta_key = '_sku'
47 AND metaSku.meta_value = '{$sku}'";
48
49 $result2 = $wpdb->get_col($sql1);
50
51 /*
52 $sq2 = "SELECT
53 posts.ID
54 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
55 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
56 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
57 INNER JOIN wp_terms AS terms
58 ON term_taxonomy.term_id = terms.term_id
59 WHERE term_taxonomy.taxonomy = 'product_type'
60 AND posts.post_status NOT IN('trash')
61 AND posts.post_title = '$title_name_marca'
62 AND posts.post_type = 'product'";
63 */
64 echo $sql1;
65 var_dump($result2);
66
67 if (empty($result2[0])) return;
68 else
69 //print_r(wc_get_product( intval( $result[0])));
70 return wc_get_product($result2[0]);
71}
72
73function getProdutosForWikiWs()
74{
75 /*
76 $ch = curl_init();
77 curl_setopt_array($ch, array(
78 //CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=392&guid=4c6e6dab-6d6d-43d9-8f71-7f12158f8f85&estoquePositivo=0",
79 CURLOPT_URL => "http://52.6.107.225/script.php?wikiProducts=true",
80 CURLOPT_RETURNTRANSFER => true,
81 CURLOPT_ENCODING => "",
82 CURLOPT_MAXREDIRS => 10,
83 CURLOPT_TIMEOUT => 30,
84 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
85 CURLOPT_CUSTOMREQUEST => "GET",
86 CURLOPT_SSL_VERIFYPEER=> false,
87
88 CURLOPT_HTTPHEADER => array(
89 "Authorization: Basic *****************",
90 "Cache-Control: no-cache"
91 ),
92 ));
93
94 $result = curl_exec($ch);
95 //var_dump($result);*/
96 $collection = json_decode(_getJson());
97 //$collection = json_decode($result);
98 return $collection;
99 //curl_close($ch);
100}
101
102/*
103//usage
104$parent_id = 746; // Or get the variable product id dynamically
105
106//The variation data
107$variation_data = array(
108 'attributes' => array(
109 'size' => 'M',
110 'color' => 'Green',
111 ),
112 'sku' => '',
113 'regular_price' => '22.00',
114 'sale_price' => '',
115 'stock_qty' => 10,
116);
117
118// The function to be run
119create_product_variation( $parent_id, $variation_data );
120*/
121
122function insertSimpleProduct()
123{
124 $post = array(
125 'post_author' => $user_id,
126 'post_content' => '',
127 'post_status' => "publish",
128 'post_title' => $product->part_num,
129 'post_parent' => '',
130 'post_type' => "product",
131 );
132
133 //Create post
134 $post_id = wp_insert_post($post, $wp_error);
135 if ($post_id)
136 {
137 $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
138 add_post_meta($post_id, '_thumbnail_id', $attach_id);
139 }
140
141 wp_set_object_terms($post_id, 'Races', 'product_cat');
142 wp_set_object_terms($post_id, 'simple', 'product_type');
143
144 update_post_meta($post_id, '_visibility', 'visible');
145 update_post_meta($post_id, '_stock_status', 'instock');
146 update_post_meta($post_id, 'total_sales', '0');
147 update_post_meta($post_id, '_downloadable', 'yes');
148 update_post_meta($post_id, '_virtual', 'yes');
149 update_post_meta($post_id, '_regular_price', "1");
150 update_post_meta($post_id, '_sale_price', "1");
151 update_post_meta($post_id, '_purchase_note', "");
152 update_post_meta($post_id, '_featured', "no");
153 update_post_meta($post_id, '_weight', "");
154 update_post_meta($post_id, '_length', "");
155 update_post_meta($post_id, '_width', "");
156 update_post_meta($post_id, '_height', "");
157 update_post_meta($post_id, '_sku', "");
158 update_post_meta($post_id, '_product_attributes', array());
159 update_post_meta($post_id, '_sale_price_dates_from', "");
160 update_post_meta($post_id, '_sale_price_dates_to', "");
161 update_post_meta($post_id, '_price', "1");
162 update_post_meta($post_id, '_sold_individually', "");
163 update_post_meta($post_id, '_manage_stock', "no");
164 update_post_meta($post_id, '_backorders', "no");
165 update_post_meta($post_id, '_stock', "");
166}
167
168//add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
169function initMigration()
170{
171 //logs
172 FavelaMigration::logger("Iniciando uma nova Importação");
173 /*
174 for($i=0;$i<=186;$i++){
175 //FavelaMigration::init($prodPosition=185);
176 echo "no loop: {$i}";
177 FavelaMigration::init($i);
178 }
179 return;*/
180 //pega todos os dados do WS
181 $collection = getProdutosForWikiWs();
182 //cria um array de nomes remotos
183 $totalRemoteP = count($collection);
184
185 for ($i = 0;$i <= count($collection);$i++)
186 {
187 //FavelaMigration::init($prodPosition=185);
188 echo "no loop: {$i} [{$totalRemoteP}]";
189 FavelaMigration::init($i);
190 }
191
192 $remoteName = [];
193 foreach ($collection as $cln => $coll)
194 {
195 $remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
196 }
197
198 #inicializa variáveis de operacao
199 //variaveis locais
200 $localProducts = FavelaMigration::getAllLocalProducts();
201 //var_dump($localProducts);
202 $notExistsProduct = [];
203 //total de ids (local/remoto)
204 $totalIds = [];
205 $idsQDiferetem = [];
206 $idsQBatem = [];
207 $totalNames = [];
208 $remoteSlug = new stdClass;
209 $remoteProductSku = new stdClass;
210 $localSlugs = new stdClass;
211 $localProductName = new stdClass;
212 $rmNames = [];
213 $lcNames = [];
214 $localProductName->name = [];
215 $countIdsQDiferem = 0;
216
217 foreach ($localProducts as $k => $lp)
218 {
219 foreach ($collection as $c => $cl)
220 {
221 $resultSearch = FavelaMigration::searchProduct($cl);
222
223 if (empty($resultSearch))
224 {
225 $notExistsProduct[] = $resultSearch;
226 }
227 else
228 {
229
230 if ($resultSearch->get_sku() != $cl->produtoId)
231 {
232 return false;
233 }
234 //Se existe na base local um produto correspondente ao remoto.
235 $produtoName[$c] = $resultSearch->get_name();
236 $productSlug[$c] = $resultSearch->get_slug();
237
238 $totalIds[] = $resultSearch->get_id();
239
240 $productAux = wc_get_product($resultSearch->get_id());
241 $RemoteSku[] = $productAux->get_sku();
242 $remoteSlug->slug[] = $resultSearch->get_slug();
243 $localSlugs->slug[] = $lp->get_slug();
244 $remoteProductSku->sku[] = $resultSearch->get_sku();
245 $localProductName->name[] = $lp->get_name();
246 }
247 // && $remoteProductSku->sku[$c] == $lp->get_sku()
248 if ($lp->get_slug() == $remoteSlug->slug[$c])
249 {
250 var_dump($lp->get_slug() == $remoteSlug->slug[$c]);
251 echo ("Comparação: {$lp->get_slug() } == {$remoteSlug->slug[$c]} [c:{$c}] [k:{$k}]<br>");
252 echo "*Produto(Local) Nome:{$lp->get_name() }, id:{$lp->get_id() }, slug:{$lp->get_slug() },
253 c:({$c}), sku:{$lp->get_sku() } <br> Produto(Remoto): Nome:{$produtoName[$x]},
254 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:<b>[#Bate com o WS
255 id:{$totalIds[$c]}]</b> <br>";
256
257 echo "(Slugs iguais)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id() }<br>";
258 $idsQBatem[] = $lp->get_id();
259 $slugsQBatem[] = $lp->get_slug();
260 //$totalNames[] = $resultSearch->get_name();
261 $rmNames[] = ['name' => $remoteName[$c], 'slug' => $remoteSlug->slug[$c], 'id' => $totalIds[$c], 'sku' => $remoteProductSku->sku];
262 $lcNames[] = ['name' => $lp->get_name() , 'slug' => $lp->get_slug() , 'id' => $lp->get_id() , 'sku' => $lp->get_sku() ];
263 }
264
265 if ($lp->get_slug() != $remoteSlug->slug[$c])
266 {
267 echo "-Produto(Local) Nome:{$lp->get_name() }, id:{$lp->get_id() }, slug:{$lp->get_slug() },
268 c:({$c}), sku:{$lp->get_sku() } Produto(Remoto): Nome:{$produtoName[$c]},
269 slug:{$productSlug[$c]} ,sku:{$RemoteSku[$c]}
270 status:[<b>Não Bate com o WS id:{$totalIds[$c]}]</b><br>";
271
272 echo "(ids Diferem)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id() }<br>";
273 $idsQDiferetem[] = $lp->get_id();
274 $slugsQDiferem[] = $lp->get_slug();
275 }
276 }
277 }
278
279 echo "<br><b>ids Que Batem</b><br>";
280 var_dump(count($idsQBatem));
281 print_r($idsQBatem);
282
283 echo "<b>Total Ids do WebService</b><br>";
284 //var_dump(count($totalIds));
285 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
286 var_dump(count($notExistsProduct));
287
288 echo "<b>Ids que diferem</b><br>";
289 $result = array_unique($idsQDiferetem);
290 //print_r($result);
291 var_dump(count($result));
292 print_r($result);
293
294 echo "<b>Diff dos 2 arrays(ids)</b><br>";
295 //Ids que diferem | ids que batem
296 $diffResult = array_diff($result, $idsQBatem);
297
298 var_dump(count($diffResult));
299 //var_dump($diffResult);
300 echo "<b>Produtos do Diff</b><br>";
301 print_r($diffResult);
302 $deletedIds = $diffResult;
303
304 /***/
305
306 echo "<br><b>Slugs Que Batem</b><br>";
307
308 if (isset($slugsQBatem))
309 {
310 var_dump(count($slugsQBatem));
311 }
312
313 //print_r($slugsQBatem);
314 echo "<b>Total Ids do WebService</b><br>";
315 //var_dump(count($totalIds));
316 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
317 var_dump(count($notExistsProduct));
318
319 echo "<b>Slugs que diferem</b><br>";
320 if (isset($slugsQDiferem))
321 {
322 $resultSlug = array_unique($slugsQDiferem);
323 }
324 //print_r($result);
325 if (isset($resultSlug) && isset($slugsQBatem))
326 {
327 var_dump(count($resultSlug));
328
329 echo "<b>Diff dos 2 arrays(slugs)</b><br>";
330 //Ids que diferem | ids que batem
331 $diffResultSlug = array_diff($resultSlug, $slugsQBatem);
332
333 if (isset($diffResultSlug))
334 {
335 var_dump(count($diffResultSlug));
336 }
337 }
338
339 //var_dump($diffResult);
340 echo "<b>Produtos do Diff</b><br>";
341 print_r($diffResultSlug);
342 //$deletedIds = $diffResult;
343 /*
344 echo "<b>Diff das Slugs</b><br>";
345 $diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
346 $resultSlug = array_unique($diffResultSlugs);
347
348 var_dump(count($diffResultSlugs));
349 //print_r($diffResultSlugs);
350 echo "<b>Slug processado excluido os Repetidos</b><br>";
351 var_dump(count($resultSlug));
352 //var_dump($resultSlug);
353 //var_dump($diffResultSlugs);
354
355
356 echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
357 $diffResultNames = array_diff($totalNames, $remoteName);
358 var_dump(count($diffResultNames));
359 //print_r($diffResultNames);
360 echo "<b>Total de nomes que Batem</b><br>";
361 var_dump(count($totalNames));
362
363 echo "<b>Total de nomes do Ws</b><br>";
364 var_dump(count($remoteName));
365
366 echo "<b>Remote Info Produtcs{names}</b><br>";
367 var_dump(count($rmNames));
368 //print_r($rmNames);
369
370 echo "<b>Local Info Produtcs{names}</b><br>";
371 var_dump(count($lcNames));
372 //print_r($lcNames);
373 //print_r($diffResultNames);
374 */
375 if (isset($deletedIds))
376 {
377 $productNameDelIds = [];
378 foreach ($deletedIds as $d => $pDelete)
379 {
380 $product = wc_get_product($pDelete);
381 $productNameDelIds[] = ['name' => $product->get_name() , 'id' => $product->get_id() , 'sku' => $product->get_sku() ];
382 //echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$x]}]<br>";
383 //wh_deleteProduct($pDelete);
384 //$product = wc_get_product($pDelete);
385 //$product->delete();
386 //$result = 'trash' === $product->get_status();
387 /*
388 if (!$result)
389 {
390 //return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
391 }
392 $x++;*/
393 }
394 }
395 echo "<i>Lista de objetos a serem destruidos</i><br>";
396 var_dump($productNameDelIds);
397
398 //$u = 0;
399 foreach ($collection as $ck => $coll)
400 {
401 echo "no loop de collection {$ck}<br>";
402 //stristr($string, 'earth') === FALSE
403 foreach ($productNameDelIds as $pk => $pDeIds)
404 {
405 $product = wc_get_product($pDeIds['id']);
406 //var_dump($pDeIds);
407 echo "no loop de namedIds {$pk}<br>";
408 if (is_string($pDeIds['name']))
409 {
410 $pname = explode(",", $pDeIds['name']);
411 //"/{$pname[0]}/i", $coll->produtoNome) && $pDeIds['sku']
412 if ($pDeIds['sku'] == $coll->produtoId || $coll->produtoRef == $pDeIds['sku'] || $product->get_image_id() != '')
413 {
414 var_dump($product->get_image_id());
415 echo "Existe na base Remota e Banco Local como Objeto Legado e Objeto (Nova API): [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:[{$pk}-{$ck}] [Não Deletar]<br>";
416 //unset($pname[0]);
417 unset($productNameDelIds[$pk]);
418 //unset($collection[$ck]);
419 unset($pDeIds['id']);
420 }
421 else
422 {
423 //se for o último registro do Ws, exclui.
424 //if((count($collection)-1) == $ck){
425 //sku remoto é igual ao sku de ids deletados?
426 //$product = wc_get_product();
427 //var_dump($product->get_sku());
428 $totalRemoteColl = count($collection);
429 if ($pDeIds['sku'] == '' || $pDeIds['sku'] != $coll->produtoRef)
430 {
431 echo "<br>Produto Não Corresponde a API Enviado para a Lixeira id[{$pDeIds['id']}
432 | nome: {$pname[0]}]|{$coll->produtoNome} collection-k:[{$pk}-{$ck}[$totalRemoteColl - 1) == {$ck}]] (remote SKU: {{$coll->produtoRef})<br>";
433 //wh_deleteProduct($pDelete);
434
435 //$product->delete();
436 $deletedsIds[] = $pDeIds['id'];
437 if ((count($collection) - 1) == $ck && $product->get_image_id() == '')
438 {
439
440 echo "*Produto Não tem uma imagem cadastrada<br>
441 *sku vazio<br>
442 * sku local não bate com sku remoto<br>
443 * sku local não bate com produtoId remoto [<b>deletado</b>]<br>";
444 //$product->delete();
445 }
446
447 echo "Produto Não Existe na base Remota ou Local:[{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']}, remoteSKU:{$coll->produtoRef} | collection-k:[{$pk}-{$ck}] |<br>";
448 }
449 else
450 {
451
452 echo $product->get_name() . "<br>";
453
454 }
455
456 //}
457
458 }
459
460 }
461
462 }
463 }
464
465 //print_r($collection);
466
467
468 //61
469 //FavelaMigration::init($prodPosition=61);
470 //186
471 /*
472 $bate = 0;
473 foreach($collection as $k=> $coll){
474
475 //FavelaMigration::init($prodPosition=185);
476 //echo "no loop: {$i}";
477 //$productsOp[] = FavelaMigration::init($i);
478
479 $productTeste = $coll;
480 $resultSearch = FavelaMigration::searchProduct($productTeste);
481 if(empty($resultSearch)){
482 echo "<h4>Produto não existe na base Local</h4>";
483
484 }else{
485 $totalIds[] = $resultSearch->get_id();
486 //echo "<h4>Produto existe na base Local</h2>";
487 //var_dump($resultSearch);
488 }
489
490 $produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
491
492 foreach($totalIds as $t=>$tIds){
493 if($localProducts[$t]->get_id() == $tIds){
494 echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$k]->get_id()} ({$k}) Produto(Remoto)Nome:$produtoName [Bate com o WS (id:{$tIds})] Bate: [{$bate}]<br>";
495 $bate++;
496 //echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";
497 echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
498 //unset($lp);
499 //$listVerify['produtoBate'] = $localProducts[$prodPosition];
500 //$listNoExists = $lp;
501 }else{
502
503 //echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$i]->get_id()}[c:{$i}] ({$i}) Produto(Remoto)Nome:$produtoName [Não Bate com o WS (id:{$totalIds[0]})]<br>";
504
505 //unset($localProducts);
506 echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
507 }
508 }
509
510 //echo "<h4>Total de produtos Locais</h4>";
511
512
513 }*/
514
515 //print_r($listVerify);
516 //print_r($totalIds);
517
518
519 //return $listVerify;
520
521
522 //echo "<h4>Produtos Operacionais</h4>";
523 //print_r($productsOp);
524 //var_dump($productsOp["produtoBate"]);
525
526}
527
528class MigrationRules
529{
530
531 private static $lproduct, $rproduct, $collection, $postId, $prodPosition, $productTeste, $remoteAttr;
532
533 private static $tamanhoUpdated = false;
534 private static $isUpdated = false;
535
536 static function filterVariations($post_id, $meta_key, $meta_value)
537 {
538 $query = new \WP_Query(array(
539 'post_parent' => $post_id,
540 'post_status' => 'publish',
541 'post_type' => 'product_variation',
542 'posts_per_page' => - 1,
543 'meta_query' => array(
544 array(
545 'key' => $meta_key,
546 'value' => $meta_value,
547 )
548 ) ,
549 ));
550 $result = array();
551 if ($query->have_posts())
552 {
553 while ($query->have_posts())
554 {
555 $query->next_post();
556 $result[] = $query->post;
557 }
558 wp_reset_postdata();
559 }
560 wp_reset_query();
561
562 return $result;
563 }
564 /*
565 *
566
567 **/
568 static function _filterVariations($post_id, array $properties)
569 {
570 $query = new \WP_Query(array(
571 'post_parent' => $post_id,
572 'post_status' => 'publish',
573 'post_type' => 'product_variation',
574 'posts_per_page' => - 1,
575 'meta_query' => array(
576 'relation' => 'AND',
577 'cor_clause' => array(
578 'key' => $properties['cor_key'],
579 'value' => $properties['cor_value'],
580 ) ,
581 'tamanho_clause' => array(
582 'key' => $properties['tamanho_key'],
583 'value' => $properties['tamanho_value'],
584 ) ,
585 ) ,
586 ));
587 $result = array();
588 if ($query->have_posts())
589 {
590 while ($query->have_posts())
591 {
592 $query->next_post();
593 $result[] = $query->post;
594 }
595 wp_reset_postdata();
596 }
597 wp_reset_query();
598
599 return $result;
600 }
601
602 static function storeStock($listCorT, $x)
603 {
604 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
605 if (strlen($listCorT->produtoQtdeEstoque) <= 4)
606 {
607 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque, 0, 1);
608 }
609 else
610 {
611 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque, 0, 2);
612 }
613 echo "Attr com problema<br>";
614 var_dump($listCorT->produtoCor);
615
616 echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
617 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'sku' => MigrationRules::getProductTeste()->produtoId, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
618 // The function to be run
619 _create_product_variation(MigrationRules::getPostId() , $variation_data);
620 }
621
622 static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts)
623 {
624
625 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
626 $totalL = self::getTotalLocalProducts();
627 $diffProducts = $rtotal - $totalL;
628
629 if (strlen($listCorT->produtoQtdeEstoque) <= 4)
630 {
631 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque, 0, 1);
632 }
633 else
634 {
635 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque, 0, 2);
636 }
637
638 $pcor = strtolower(tirarAcentos($listCorT->produtoCor));
639 $acor = strtolower(tirarAcentos($attrCor));
640
641 $corFragment = explode(" ", $pcor);
642
643 if (isset($corFragment[0]))
644 {
645 $pcor = $corFragment[0];
646 }
647
648 if (isset($corFragment[1]))
649 {
650 $pcor = $corFragment[0] . "-" . $corFragment[1];
651 }
652
653 $rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
654 $atTamanho = strtolower(tirarAcentos($attrTamanho));
655
656 $product = wc_get_product($cproducts);
657 //se o preço local é diferente do remoto, prevalece o do remoto
658 echo "comparação de preço remoto com preço local<br>";
659 //var_dump($product);
660 $remotePrice = (int)MigrationRules::getProductTeste()->produtoPrecoBase;
661
662 $localPrice = (int)$product->get_price();
663
664 echo "preço local = {$localPrice} || preço remoto: {$remotePrice}<br>";
665
666 if (MigrationRules::getProductTeste()->produtoPrecoBase != $localPrice)
667 {
668 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'ID' => $cproducts, 'sku' => MigrationRules::getProductTeste()->produtoId, 'update' => true, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
669 // The function to be run
670 echo "Alteração do preco do produto de id:{$cproducts} atualizado";
671 _create_product_variation(MigrationRules::getPostId() , $variation_data);
672
673 }
674
675 if ($pcor == $acor)
676 {
677 //atualiza
678 echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
679 //se o tamanho do produto for igual
680 if ($rTamanho == $attrTamanho)
681 {
682 //atualiza
683 echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
684
685 //se o estoque remoto for igual ao estoque local (Não atualiza)
686 if ($_stockRemote == $attrStock)
687 {
688 //não atualiza
689 echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
690 echo "<hr><hr>";
691 //self::$isUpdated = true;
692
693 }
694
695 //se estoque remoto for maior que o estoque local (Atualiza)
696 if ($_stockRemote > $attrStock)
697 {
698 //atualiza
699 //var_dump(self::$isUpdated);
700 echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
701 ,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
702 $result = MigrationRules::filterVariations(MigrationRules::getPostId() , 'attribute_pa_tamanho', $rTamanho);
703
704 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'ID' => $cproducts, 'sku' => MigrationRules::getProductTeste()->produtoId, 'update' => true, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
705 // The function to be run
706 _create_product_variation(MigrationRules::getPostId() , $variation_data);
707 //self::$isUpdated = true;
708
709
710
711 }
712 if ($_stockRemote < $attrStock)
713 { //se for diferente, atualiza com base no valor do estoque remoto
714 //atualiza
715 echo "produtoQtdeEstoque(Remoto):[{$_stockRemote}] {Menor do que Estoque Local - Ação: Incrementa Sobre o Stock Local o Estoque Remoto} -> attrStock(Estoque Local):[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} < {{$attrStock}}] <br>";
716 echo "<hr><hr>";
717 $localStk = (int)get_post_meta($cproducts, '_stock', true);
718 //var_dump($localStk);
719 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'ID' => $cproducts, 'sku' => MigrationRules::getProductTeste()->produtoId, 'update' => true, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote + $localStk];
720 // The function to be run
721 _create_product_variation(MigrationRules::getPostId() , $variation_data);
722 //self::$isUpdated = true;
723
724 }
725 }//se total local é maior ou igual que o total de produtos remotos
726 elseif (($totalL) - 1 == $c && $totalL >= $rtotal)
727 { //se tamanhos são diferentes
728 // [se a quantidade de produtos com cores iguais e tamanhos diferentes
729 // _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
730 echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
731 $result = MigrationRules::_filterVariations(MigrationRules::getPostId() , ['cor_key' => 'attribute_pa_cor', 'cor_value' => $pcor, 'tamanho_key' => 'attribute_pa_tamanho', 'tamanho_value' => $rTamanho]);
732
733 //var_dump($result);
734 if (empty($result))
735 {
736 //var_dump($result);
737 // The variation data
738 echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
739 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'sku' => MigrationRules::getProductTeste()->produtoId, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
740 // The function to be run
741 _create_product_variation(MigrationRules::getPostId() , $variation_data);
742 }
743 else
744 {
745
746 echo "{Tamanho remoto existe na base [{$rTamanho}] Não Será atualizada} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | {$result[0]->ID} | STock:{$_stockRemote}<br>";
747 /*$variation_data = [
748 'attributes' => [
749 'cor' => $listCorT->produtoCor,
750 'tamanho' => $listCorT->produtoTamanho,
751 ],
752 'ID' => $cproducts,
753 'sku' => MigrationRules::getProductTeste()->produtoId,
754 'update' => true,
755 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
756 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
757 'stock_qty' => $_stockRemote
758 ];
759 */
760 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
761
762
763
764 }
765 }
766 //se a quantidade do estoque for igual
767 //var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
768
769 }
770 else
771 { //atualiza $c (contador do loop das variacoes remotas)
772 $totalL = self::getTotalLocalProducts();
773
774 if($rtotal >= $totalL || $totalL >= $rtotal){
775 $diffProducts = $totalL - $rtotal;
776 }
777
778 //$rtotal - $totalL;
779 echo "#produtoCor:[{$pcor},{$rTamanho}] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total:{$rtotal}, diffP:{$diffProducts}) - variable_id:[$cproducts] | {Cor remota não existe em cores locais}<br>";
780 echo "<p><i>Total de atributos locais:($totalL) == contador:{{$c}}{{$x}} && totalLocal:{$totalL} == totalRemoto:{$rtotal}</i></p>";
781 //se total de variacoes locais é menor que o total de variacoes remotas
782 //insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
783 //remotas
784 //enquanto 29 <= 52 { execulta }
785 // $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
786 //$z = $c;
787 //30 == $c
788 //se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
789 //e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
790 //if (($totalL) - 1 == $c && $totalL < $rtotal)
791 if (($totalL)-1 == $c && $totalL >= $rtotal)
792 {
793
794 //if($z <= $rtotal){
795 //$pID = MigrationRules::getPostId();
796 //$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
797 //$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
798 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
799 $result = MigrationRules::_filterVariations(MigrationRules::getPostId() , ['cor_key' => 'attribute_pa_cor', 'cor_value' => $pcor, 'tamanho_key' => 'attribute_pa_tamanho', 'tamanho_value' => $rTamanho]);
800
801 echo "-produtoCor:[{$pcor}|[$rTamanho]] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c}[Último Produto Local],total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor remota não existe em cores locais} |<br>";
802
803 //var_dump($result);
804 if (empty($result))
805 {
806 //var_dump($result);
807 // The variation data
808 echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
809 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'sku' => MigrationRules::getProductTeste()->produtoId, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
810 // The function to be run
811 _create_product_variation(MigrationRules::getPostId() , $variation_data);
812 //$z++;
813
814 }
815 else
816 {
817 echo "*produtoCor:[{$pcor}|[$rTamanho]] existe como variacao local na base AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor/Tamanho remota existe em cores/tamanhos locais(Operacão: Não atualiza)} |<br>";
818 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
819 $result = MigrationRules::_filterVariations(MigrationRules::getPostId() , ['cor_key' => 'attribute_pa_cor', 'cor_value' => $pcor, 'tamanho_key' => 'attribute_pa_tamanho', 'tamanho_value' => $rTamanho]);
820 //var_dump($result[0]->ID);
821 //if(empty($result)){
822 //var_dump($result);
823 // The variation data
824 echo "{Variaçao de tamanho Existe para a cor:{$pcor} ->{Tamanho:{$listCorT->produtoTamanho}} - Variação de cor:[{$pcor}] Não Será Criada, pois já existe} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
825 $variation_data = ['attributes' => ['cor' => $listCorT->produtoCor, 'tamanho' => $listCorT->produtoTamanho, ], 'sku' => MigrationRules::getProductTeste()->produtoId, 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase, 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo, 'stock_qty' => $_stockRemote];
826 // The function to be run
827 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
828 #
829 //echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
830 /*
831 $variation_data = [
832 'attributes' => [
833 'cor' => $listCorT->produtoCor,
834 'tamanho' => $listCorT->produtoTamanho,
835 ],
836 'ID' => $cproducts,
837 'sku' => MigrationRules::getProductTeste()->produtoId,
838 'update' => true,
839 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
840 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
841 'stock_qty' => $_stockRemote
842 ];
843 // The function to be run
844 _create_product_variation(MigrationRules::getPostId(), $variation_data );
845 */
846 }
847
848 }
849 elseif($diffProducts > 0 || $diffProducts == -1)
850 {
851 //echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
852
853 }
854
855 }
856 //exit;
857
858 }
859
860 static function setTotalLocalProducts($lproduct)
861 {
862 self::$lproduct = $lproduct;
863 }
864
865 static function setTotalRemoteProducts($rproduct)
866 {
867 self::$rproduct = $rproduct;
868 }
869
870 static function getTotalLocalProducts()
871 {
872 return self::$lproduct;
873 }
874
875 static function getTotalRemoteProducts()
876 {
877 return self::$rproduct;
878 }
879
880 static function setCollection($collection)
881 {
882 self::$collection = $collection;
883 }
884
885 static function getCollection()
886 {
887 return self::$collection;
888 }
889
890 static function setPostId($postId)
891 {
892 self::$postId = $postId;
893 }
894
895 static function getPostId()
896 {
897 return self::$postId;
898 }
899
900 static function setProdPosition($prodPosition)
901 {
902 self::$prodPosition = $prodPosition;
903 }
904
905 static function getProdPosition()
906 {
907 return self::$prodPosition;
908 }
909
910 static function setProductTeste($productTeste)
911 {
912 self::$productTeste = $productTeste;
913 }
914 //qualquer coisa excerto o numero 0.
915 public static function onlyNumbers($str)
916 {
917 $str = preg_replace('/[^0-9]+/', '', $str);
918 return $str;
919 }
920
921 static function getProductTeste()
922 {
923 //self::$productTeste->produtoPrecoPromo = number_format(self::$productTeste->produtoPrecoPromo,2,",",".");
924 //self::$productTeste->produtoPrecoBase = number_format(self::onlyNumbers(self::$productTeste->produtoPrecoBase),2,",",".");
925 /*$wsprice = self::$productTeste->produtoPrecoBase;
926 echo "<h3>preço literal do Ws: {$wsprice}</h3>";
927
928 $precoBase = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoBase, "0"));
929 echo "<h3>preço base Manipulado: {$precoBase}</h3>";
930 $precoBase = number_format((int)$precoBase,2,",",".");
931
932 $precoPromo = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoPromo,"0"));
933 $precoPromo = number_format((int)$precoPromo,2,",",".");
934
935 self::$productTeste->produtoPrecoBase = $precoBase;
936 self::$productTeste->produtoPrecoPromo = $precoPromo;
937
938 //$precoBase = substr(self::$productTeste->produtoPrecoBase,0,-2);
939 echo "<h3>Preço final{$precoBase}</h3>";
940
941 //var_dump($precoBase);
942 //exit;
943 */
944 return self::$productTeste;
945 }
946
947 static function setRemoteAttr($remoteAttr)
948 {
949 self::$remoteAttr = $remoteAttr;
950 }
951
952 static function getRemoteAttr()
953 {
954 return self::$remoteAttr;
955 }
956
957}
958
959class ProductProperties
960{
961
962 static $author, $name;
963
964 static function setName(stdClass $productWs)
965 {
966 echo "id manipulado para setName(referencias de produtoId para sku local";
967 var_dump($productWs->produtoId);
968 if ($productWs->produtoId)
969 {
970 $id = wc_get_product_id_by_sku($productWs->produtoId);
971 //var_dump($id);
972 if ($id != 0)
973 {
974 $product = wc_get_product($id);
975 self::$name = $product->get_title();
976 if (isset(self::$name) && self::$name == trim($product->produtoNome))
977 {
978 return self::$name;
979 }
980 else
981 {
982 return false;
983 }
984 }
985 }
986
987 echo "id manipulado para setName(referencias de produtoRef para sku local";
988 var_dump($productWs->produtoRef);
989 if ($productWs->produtoRef)
990 {
991
992 $_id = wc_get_product_id_by_sku($productWs->produtoRef);
993 var_dump($_id);
994 if ($_id != 0)
995 {
996 $product = wc_get_product($_id);
997 self::$name = $product->get_title();
998 var_dump(self::$name);
999 if (isset(self::$name) && self::$name == trim($product->produtoNome))
1000 {
1001 return self::$name;
1002 }
1003 else
1004 {
1005 return false;
1006 }
1007 }
1008 }
1009 }
1010
1011 static function getName()
1012 {
1013 return self::$name;
1014 }
1015
1016 static function setAuthor($author)
1017 {
1018 self::$author = $author;
1019 }
1020
1021 static function getAuthor()
1022 {
1023 return self::$name;
1024 }
1025}
1026
1027class FavelaMigration
1028{
1029
1030 static function listAllVariableProducts($post_id)
1031 {
1032 //cria uma instancia do produto
1033 $product = wc_get_product($post_id);
1034
1035 //pega todas as variacoes do produto (só os ids)
1036 if (!empty($product))
1037 {
1038 $current_products = $product->get_children();
1039 return (count($current_products));
1040 }
1041 }
1042
1043 static function getAllVariableProduct($post_id)
1044 {
1045 //cria uma instancia do produto
1046 $product = wc_get_product($post_id);
1047 if (!empty($product))
1048 {
1049 $current_products = $product->get_children();
1050 return $current_products;
1051 }
1052 }
1053
1054 static function getAllRemoteVariableProduct(stdClass $collection)
1055 {
1056 return (count($collection->listaCorTamanho));
1057 }
1058
1059 static function getAllRemoteVariableProductList(stdClass $collection)
1060 {
1061 return $collection->listaCorTamanho;
1062 }
1063
1064 static function getAllRemoteVariableProductNames(stdClass $collection)
1065 {
1066 foreach ($collection->listaCorTamanho as $k => $coll)
1067 {
1068 echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1069 }
1070 }
1071
1072 static function getAttributesForProduct(stdClass $product)
1073 {
1074 foreach ($product->listaCorTamanho as $p => $prop)
1075 {
1076 $cores[] = $prop->produtoCor;
1077 $tamanho[] = $prop->produtoTamanho;
1078 $stock[] = $prop->produtoQtdeEstoque;
1079 }
1080
1081 return array(
1082 'cores' => $cores,
1083 'tamanho' => $tamanho,
1084 'estoque' => $stock
1085 );
1086 }
1087
1088 static function _getAttributesForProduct(stdClass $product)
1089 {
1090 //echo "<h1>Objeto Remoto como stdClass: </h1>";
1091 //var_dump($product->listaCorTamanho);
1092 $c = 0;
1093 foreach ($product->listaCorTamanho as $p => $prop)
1094 {
1095 //$object = $object[$k];
1096 foreach ($prop as $k => $value)
1097 {
1098 //$attributeMeta[] = $prop->$k;
1099 //$object[] = ["{$k}"=>[$prop->$k]];
1100 //echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1101 $attribute = substr($k, 7); //produto{AttrName}elimina produto da str
1102 if ("QtdeEstoque" != $attribute && "CorHex" != $attribute && "CorId" != $attribute)
1103 {
1104 $object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1105 }
1106
1107 }
1108 //echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";
1109 $c++;
1110 }
1111
1112 //var_dump($object);
1113 return $object;
1114 //return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1115
1116 }
1117
1118 static function getAllAttributes($post_id)
1119 {
1120 //exibe os atributos do produto
1121 $prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true);
1122 echo "<h2>Atributos do produto</h2>";
1123 var_dump($prodAttrGlobal);
1124 }
1125
1126 static function getAllAttrForTaxonomy($tax, $post_id)
1127 {
1128 echo "<h2>termos dos atributos dos produtos(pa_tamanho)tax:{$tax}| id:{$post_id}</h2>";
1129 $result = wc_get_product_terms($post_id, $tax, 'names');
1130 var_dump($result);
1131 }
1132
1133 static function updateVariableProduct(stdClass $productTeste, array $current_products)
1134 {
1135 //counters
1136 MigrationRules::setTotalLocalProducts(count($current_products));
1137 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1138
1139 $x = 0;
1140 $c = 0;
1141 //loop (produto remoto / produtos variavies)
1142 foreach ($productTeste->listaCorTamanho as $l => $listCorT)
1143 {
1144 foreach ($current_products as $c => $cproducts)
1145 {
1146 $attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true);
1147 var_dump($attrCor);
1148 $attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true);
1149 $attrStock = get_post_meta($cproducts, '_stock', true);
1150 //atualiza estoque
1151 MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1152 $x++; //no loop das variacoes locais ($current_products)
1153
1154 }
1155 $c++; //no loop das variacoes remotas ($productTest)
1156
1157 }
1158 }
1159
1160 static function storeVariableProduct(stdClass $productTeste)
1161 {
1162 //counters
1163 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1164 $c = 0;
1165 //loop (produto remoto / produtos variavies)
1166 foreach ($productTeste->listaCorTamanho as $l => $listCorT)
1167 {
1168 MigrationRules::storeStock($listCorT, $c);
1169 $c++; //no loop das variacoes remotas ($productTest)
1170
1171 }
1172 }
1173
1174 static function deleteVariableProduct(stdClass $productTeste, $pRemotos, array $current_products)
1175 {
1176 //counters
1177
1178 echo "stdClass de produtos Remotos:<br>";
1179 var_dump($pRemotos);
1180 echo "stdClass de produtos remotos convertido em Array";
1181 $newArray = [];
1182
1183 $pRemotosArray = json_decode(json_encode($pRemotos), true);
1184 foreach($pRemotosArray as $pkey =>$pTransform){
1185 $newArray[] = ['produtoCor'=>$pTransform['produtoCor'], 'produtoTamanho'=>$pTransform['produtoTamanho']];
1186 }
1187
1188 var_dump($newArray);
1189
1190 echo "Array de produtos Locais:<br>";
1191 var_dump($current_products);
1192 //$diff = array_diff($pRemotos, $current_products);
1193 echo "Diff para deletar:<br>";
1194 //var_dump($diff);
1195 $c = 0;
1196 //loop (produto remoto / produtos variavies)
1197 $currentProductsTransforme = [];
1198 foreach($current_products as $cp=>$id){
1199 $product = wc_get_product($id);
1200 $attributes = $product->get_attributes();
1201 //var_dump($attributes['pa_cor']);
1202 $pa_cor = strtoupper($attributes['pa_cor']);
1203 $pa_tamanho = strtoupper($attributes['pa_tamanho']);
1204 $currentProductsTransforme[] = ['produtoCor'=>$pa_cor, 'produtoTamanho'=>$pa_tamanho];
1205 }
1206
1207 echo "Array Transformado (produto local)<br>";
1208 var_dump($currentProductsTransforme);
1209
1210
1211 $newArray2 = array();
1212
1213 foreach($currentProductsTransforme as $item){ // Loop the teacher_array
1214 if(!in_array($item,$newArray2)){ // If the teach_array value doesn't exist in the lang_array, add the value
1215 $newArray2[] = $item;
1216 }
1217 }
1218
1219 echo "Diff Manual";
1220 var_dump($newArray);
1221
1222 $arrayResultDiff = array_diff_assoc($currentProductsTransforme, $newArray );
1223 echo "Array Diff<br>";
1224 var_dump($arrayResultDiff);
1225/*
1226 foreach ($diff as $d => $deletedVariableProducts)
1227 {
1228 echo "Produto variável a ser deletado: {$d} ";
1229 echo $deletedVariableProducts;
1230 //MigrationRules::storeStock($listCorT, $c);
1231 $c++; //no loop das variacoes remotas ($productTest)
1232 }*/
1233 }
1234
1235 static function searchProduct($productTeste)
1236 {
1237 $result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoId);
1238 return $result;
1239 }
1240
1241 static function getAllLocalProducts()
1242 {
1243 // Get 10 most recent product IDs in date descending order.
1244 $query = new WC_Product_Query(array(
1245 'limit' => 209,
1246 'orderby' => 'date',
1247 'order' => 'ASC',
1248 ));
1249
1250 //echo "query aqui";
1251 //var_dump($query);
1252 $products = $query->get_products();
1253 //var_dump($products);
1254 return $products;
1255 }
1256
1257 static function logger($message)
1258 {
1259 $time = date("Y-m-d H:i:s");
1260 //monta string
1261 $text = "$time :: {$message}\n";
1262 //adiciona ao final do arquivo
1263 $handler = fopen("importer.log.txt", 'a+');
1264 fwrite($handler, $text);
1265 fclose($handler);
1266 }
1267
1268 static function init($prodPosition)
1269 {
1270 //recebe uma coleção remota
1271 $collection = getProdutosForWikiWs();
1272 $productTeste = $collection[$prodPosition];
1273 //se colecao for vazia sai do funcao
1274 if (empty($productTeste))
1275 {
1276 return;
1277 }
1278
1279 //Busca com base no {titulo}, {nomeDaMarca} na base da loja
1280 //caso exista um produto local com o mesmo nome de um produto remoto.
1281 $resultSearch = self::searchProduct($productTeste);
1282
1283 if (empty($resultSearch))
1284 {
1285 echo "<h4>Produto não existe na base Local</h4>";
1286 $pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
1287 }
1288 else
1289 {
1290 $totalIds[] = $resultSearch->get_id();
1291 echo "<h4>Produto existe na base Local</h2>";
1292 //var_dump($resultSearch);
1293
1294 }
1295
1296 $pRemotos = self::getAllRemoteVariableProduct($productTeste);
1297 echo "<h2>Total de produtos Variáveis Remotos: {updated}<i>[{$pRemotos}]</i></h2>";
1298 //todos os nomes das variáveis remotas
1299 self::getAllRemoteVariableProductNames($productTeste);
1300
1301 //busca os produtos locais baseados no sku = WebService.produtoTest.id
1302 $post_id = wc_get_product_id_by_sku($productTeste->produtoId);
1303
1304 $bkSku = wc_get_product_id_by_sku($productTeste->produtoRef);
1305 //se existir um produtoRef que bate com o SKU local não executa operação de Insert e Update
1306 echo "<h3>Verifica se o campo produtoRef tem um sku igual, se tiver não opera sobre o produto</h3>";
1307
1308 //product name
1309 ProductProperties::setName($productTeste);
1310 $productName = ProductProperties::getName();
1311 //author
1312 ProductProperties::setAuthor($productTeste);
1313 $author = ProductProperties::getAuthor();
1314
1315 //var_dump($productName);
1316 //produto tem um sku que bate com algum produto local e um id também
1317 echo "Tratando somente dados da BK<br>";
1318
1319 if ($bkSku != 0)
1320 {
1321 var_dump($post_id);
1322 echo "Manipulando somente BK<br>";
1323 echo "nome: {$productTeste->produtoNome} | sku:{$productTeste->produtoRef}<br>";
1324 var_dump($bkSku);
1325 //return false;
1326 $remoteAttributes = self::_getAttributesForProduct($productTeste);
1327 echo "<h1>Array de atributos remotos construido:</h1>";
1328 var_dump($remoteAttributes);
1329
1330 if ($bkSku != 0)
1331 {
1332 update_product_variation(array(
1333 'ID' => $bkSku,
1334 'author' => '', // optional
1335 'title' => $productName,
1336 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}",
1337 'excerpt' => $productTeste->produtoDescricao,
1338 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1339 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1340 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1341 'manager_stock' => '0',
1342 'category' => $productTeste->produtoCat,
1343 // Set a minimal stock quantity
1344 'image_id' => '', // optional
1345 'gallery_ids' => array() , // optional
1346 'sku' => $productTeste->produtoRef, // optional
1347 'tax_class' => '', // optional
1348 'weight' => $productTeste->produtoPeso, // optional
1349 'width' => $productTeste->produtoDimensaoL,
1350 'length' => $productTeste->produtoDimensaoC,
1351 // For NEW attributes/values use NAMES (not slugs)
1352 'attributes' => ['Cor' => $remoteAttributes['Cor'],
1353 'Tamanho' => $remoteAttributes['Tamanho']],
1354 ));
1355 }
1356
1357 //exit;
1358 //lista todos os produtos variáveis.
1359 echo "<h1>Total de Variações Locais</h1>";
1360 var_dump(self::listAllVariableProducts($bkSku));
1361
1362 //exibe todos os attributos
1363 self::getAllAttributes($bkSku);
1364
1365 //exibe todos os termos (por taxonomia)
1366 self::getAllAttrForTaxonomy($tax = 'pa_cor', $bkSku);
1367
1368 //retorna um array contendo todos os ids de produtos variáveis[Locais]
1369 $current_products = self::getAllVariableProduct($bkSku);
1370 echo "<i>current_products:{produtos: variações locais[Tamanho,Cor]}</i><br>";
1371 var_dump($current_products);
1372
1373 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
1374 MigrationRules::setCollection($collection);
1375 MigrationRules::setPostId($bkSku);
1376 MigrationRules::setProdPosition($prodPosition);
1377 MigrationRules::setProductTeste($productTeste);
1378 MigrationRules::setRemoteAttr($remoteAttributes);
1379
1380 //post_id, $collection, prodposition, productTeste, remoteAttr
1381
1382 $remoteTotalVariableProd = self::getAllRemoteVariableProductList($productTeste);
1383 //var_dump($remoteTotalVariableProd);
1384
1385 if (empty($current_products))
1386 {
1387 echo "criando o produto bk <br>";
1388 self::storeVariableProduct($productTeste);
1389 }
1390 else
1391 {
1392 echo "Atualizando produtos bk <br>";
1393 self::updateVariableProduct($productTeste, $current_products);
1394 }
1395 /*
1396
1397 elseif(count($remoteTotalVariableProd) < count($current_products)){
1398 echo "Excluindo produto<br>";
1399 //self::deleteVariableProduct($productTeste,$remoteTotalVariableProd, $current_products);
1400 }
1401 */
1402 return true;
1403 }
1404
1405 //ProductProperties::setAuthor('');
1406 //caso
1407 /*if(!empty($post_id)){
1408 update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
1409 echo "<h2>SKU do produto Manipulado</h2><br>";
1410 var_dump($post_id);
1411 }*/
1412 //var_dump($produtoTeste);
1413 //pega os atributosdo produto remoto (taxonomias e termos)
1414 //$remoteAttributes = self::getAttributesForProduct($productTeste);
1415 $remoteAttributes = self::_getAttributesForProduct($productTeste);
1416 echo "<h1>Array de atributos remotos construido:</h1>";
1417 var_dump($remoteAttributes);
1418
1419 if ($post_id != 0 && empty($bkSku))
1420 {
1421 echo "Bk não entra aqui";
1422 var_dump($bkSku);
1423
1424 update_product_variation(array(
1425 'ID' => $post_id,
1426 'author' => '', // optional
1427 'title' => $productName,
1428 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}",
1429 'excerpt' => $productTeste->produtoDescricao,
1430 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1431 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1432 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1433 'manager_stock' => '0',
1434 'category' => $productTeste->produtoCat,
1435 // Set a minimal stock quantity
1436 'image_id' => '', // optional
1437 'gallery_ids' => array() , // optional
1438 'sku' => $productTeste->produtoId, // optional
1439 'tax_class' => '', // optional
1440 'weight' => $productTeste->produtoPeso, // optional
1441 'width' => $productTeste->produtoDimensaoL,
1442 'length' => $productTeste->produtoDimensaoC,
1443 // For NEW attributes/values use NAMES (not slugs)
1444 'attributes' => ['Cor' => $remoteAttributes['Cor'],
1445 'Tamanho' => $remoteAttributes['Tamanho']],
1446 ));
1447 }
1448 else
1449 {
1450 //var_dump($produtoTeste);
1451 $post_id = update_product_variation(array(
1452 'author' => '', // optional
1453 'title' => trim($productTeste->produtoNome) ,
1454 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}",
1455 'excerpt' => $productTeste->produtoDescricao,
1456 'category' => $productTeste->produtoCat,
1457 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1458 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1459 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1460 'manager_stock' => '0',
1461 // Set a minimal stock quantity
1462 'image_id' => '', // optional
1463 'gallery_ids' => array() , // optional
1464 'sku' => $productTeste->produtoId, // optional
1465 'tax_class' => '', // optional
1466 'weight' => $productTeste->produtoPeso, // optional
1467 'width' => $productTeste->produtoDimensaoL,
1468 'length' => $productTeste->produtoDimensaoC,
1469 // For NEW attributes/values use NAMES (not slugs)
1470 'attributes' => ['Cor' => $remoteAttributes['Cor'],
1471 'Tamanho' => $remoteAttributes['Tamanho']]
1472 ));
1473 }
1474 //exit;
1475 //lista todos os produtos variáveis.
1476 echo "<h1>Total de Variações Locais</h1>";
1477 var_dump(self::listAllVariableProducts($post_id));
1478
1479 //exibe todos os attributos
1480 self::getAllAttributes($post_id);
1481
1482 //exibe todos os termos (por taxonomia)
1483 self::getAllAttrForTaxonomy($tax = 'pa_cor', $post_id);
1484
1485 //retorna um array contendo todos os ids de produtos variáveis
1486 $current_products = self::getAllVariableProduct($post_id);
1487 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
1488 MigrationRules::setCollection($collection);
1489 MigrationRules::setPostId($post_id);
1490 MigrationRules::setProdPosition($prodPosition);
1491 MigrationRules::setProductTeste($productTeste);
1492 MigrationRules::setRemoteAttr($remoteAttributes);
1493
1494 //post_id, $collection, prodposition, productTeste, remoteAttr
1495 if (empty($current_products))
1496 {
1497 self::storeVariableProduct($productTeste);
1498 }
1499 else
1500 {
1501 self::updateVariableProduct($productTeste, $current_products);
1502 }
1503
1504 }
1505}
1506
1507function createTerms($post_id, $attributes_data)
1508{
1509 if (sizeof($attributes_data) > 0)
1510 {
1511 $attributes = array(); // Initializing
1512 // Loop through defined attribute data
1513 foreach ($attributes_data as $key => $attribute_array)
1514 {
1515 if (isset($attribute_array['name']) && isset($attribute_array['options']))
1516 {
1517 // Clean attribute name to get the taxonomy
1518 $taxonomy = 'pa_' . wc_sanitize_taxonomy_name($attribute_array['name']);
1519
1520 $option_term_ids = array(); // Initializing
1521 // Loop through defined attribute data options (terms values)
1522 foreach ($attribute_array['options'] as $option)
1523 {
1524 if (term_exists($option, $taxonomy))
1525 {
1526 // Save the possible option value for the attribute which will be used for variation later
1527 wp_set_object_terms($post_id, $option, $taxonomy, true);
1528 // Get the term ID
1529 $option_term_ids[] = get_term_by('name', $option, $taxonomy)->term_id;
1530 }
1531 else
1532 {
1533 //wp_set_object_terms($post_id, $option, $taxonomy, true );
1534 //$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1535 //var_dump($option_term_ids);
1536
1537 }
1538 }
1539 }
1540
1541 // Loop through defined attribute data
1542 $attributes[$taxonomy] = array(
1543 'name' => $taxonomy,
1544 'value' => $option_term_ids, // Need to be term IDs
1545 'position' => $key + 1,
1546 'is_visible' => $attribute_array['visible'],
1547 'is_variation' => $attribute_array['variation'],
1548 'is_taxonomy' => '1'
1549 );
1550 }
1551 // Save the meta entry for product attributes
1552 update_post_meta($post_id, '_product_attributes', $attributes);
1553
1554 }
1555}
1556
1557function create_product_attribute($label_name)
1558{
1559 global $wpdb;
1560
1561 $slug = sanitize_title($label_name);
1562
1563 if (strlen($slug) >= 28)
1564 {
1565 return new WP_Error('invalid_product_attribute_slug_too_long', sprintf(__('Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce') , $slug) , array(
1566 'status' => 400
1567 ));
1568 }
1569 elseif (wc_check_if_attribute_name_is_reserved($slug))
1570 {
1571 return new WP_Error('invalid_product_attribute_slug_reserved_name', sprintf(__('Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce') , $slug) , array(
1572 'status' => 400
1573 ));
1574 }
1575 elseif (taxonomy_exists(wc_attribute_taxonomy_name($label_name)))
1576 {
1577 return new WP_Error('invalid_product_attribute_slug_already_exists', sprintf(__('Name "%s" is already in use. Change it, please.', 'woocommerce') , $label_name) , array(
1578 'status' => 400
1579 ));
1580 }
1581
1582 $data = array(
1583 'attribute_label' => $label_name,
1584 'attribute_name' => $slug,
1585 'attribute_type' => 'select',
1586 'attribute_orderby' => 'menu_order',
1587 'attribute_public' => 0, // Enable archives ==> true (or 1)
1588
1589 );
1590
1591 $results = $wpdb->insert("{$wpdb->prefix}woocommerce_attribute_taxonomies", $data);
1592
1593 if (is_wp_error($results))
1594 {
1595 return new WP_Error('cannot_create_attribute', $results->get_error_message() , array(
1596 'status' => 400
1597 ));
1598 }
1599
1600 $id = $wpdb->insert_id;
1601
1602 do_action('woocommerce_attribute_added', $id, $data);
1603
1604 wp_schedule_single_event(time() , 'woocommerce_flush_rewrite_rules');
1605
1606 delete_transient('wc_attribute_taxonomies');
1607}
1608
1609/**
1610 * Save a new product attribute from his name (slug).
1611 *
1612 * @since 3.0.0
1613 * @param string $name | The product attribute name (slug).
1614 * @param string $label | The product attribute label (name).
1615 */
1616function save_product_attribute_from_name($name, $label = '', $set = true)
1617{
1618 if (!function_exists('get_attribute_id_from_name')) return;
1619
1620 global $wpdb;
1621
1622 $label = $label == '' ? ucfirst($name) : $label;
1623 $attribute_id = get_attribute_id_from_name($name);
1624
1625 if (empty($attribute_id))
1626 {
1627 $attribute_id = NULL;
1628 }
1629 else
1630 {
1631 $set = false;
1632 }
1633 $args = array(
1634 'attribute_id' => $attribute_id,
1635 'attribute_name' => $name,
1636 'attribute_label' => $label,
1637 'attribute_type' => 'select',
1638 'attribute_orderby' => 'menu_order',
1639 'attribute_public' => 0,
1640 );
1641
1642 if (empty($attribute_id))
1643 {
1644 $wpdb->insert("{$wpdb->prefix}woocommerce_attribute_taxonomies", $args);
1645 set_transient('wc_attribute_taxonomies', false);
1646 }
1647
1648 if ($set)
1649 {
1650 $attributes = wc_get_attribute_taxonomies();
1651 $args['attribute_id'] = get_attribute_id_from_name($name);
1652 $attributes[] = (object)$args;
1653 //print_r($attributes);
1654 set_transient('wc_attribute_taxonomies', $attributes);
1655 }
1656 else
1657 {
1658 return;
1659 }
1660}
1661
1662/**
1663 * Get the product attribute ID from the name.
1664 *
1665 * @since 3.0.0
1666 * @param string $name | The name (slug).
1667 */
1668function get_attribute_id_from_name($name)
1669{
1670 global $wpdb;
1671 $attribute_id = $wpdb->get_col("SELECT attribute_id
1672 FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
1673 WHERE attribute_name LIKE '$name'");
1674 return reset($attribute_id);
1675}
1676
1677/**
1678 * Create a new variable product (with new attributes if they are).
1679 * (Needed functions:
1680 *
1681 * @since 3.0.0
1682 * @param array $data | The data to insert in the product.
1683 */
1684
1685function create_product_variation($data)
1686{
1687 if (!function_exists('save_product_attribute_from_name')) return;
1688
1689 $postname = sanitize_title($data['title']);
1690 $author = empty($data['author']) ? '1' : $data['author'];
1691
1692 $post_data = array(
1693 'post_author' => $author,
1694 'post_name' => $postname,
1695 'post_title' => $data['title'],
1696 'post_content' => $data['content'],
1697 'post_excerpt' => $data['excerpt'],
1698 'post_status' => 'publish',
1699 'ping_status' => 'closed',
1700 'post_type' => 'product_variation',
1701 'post_parent' => $data['parent_id'],
1702 'guid' => home_url('/product/' . $postname . '/') ,
1703 );
1704
1705 // Creating the product (post data)
1706 //$product_id = wp_insert_post( );
1707 $result = wp_insert_post($post_data);
1708
1709 if ($result && !is_wp_error($result))
1710 {
1711 $product_id = $result;
1712 // Do something else
1713 var_dump($result);
1714 echo "sucesso";
1715 }
1716 else
1717 {
1718 echo "erro ao gravar produto variavel";
1719 var_dump($result);
1720 }
1721 // Get an instance of the WC_Product_Variable object and save it
1722 $product = new WC_Product_Variation($product_id);
1723
1724 ## ---------------------- Other optional data ---------------------- ##
1725 ## (see WC_Product and WC_Product_Variable setters methods)
1726 // THE PRICES (No prices yet as we need to create product variations)
1727 // IMAGES GALLERY
1728 // Prices
1729 if (empty($data['sale_price']))
1730 {
1731 $product->set_price($data['regular_price']);
1732 }
1733 else
1734 {
1735 $product->set_price($data['sale_price']);
1736 $product->set_sale_price($data['sale_price']);
1737 }
1738 $variation->set_regular_price($data['regular_price']);
1739
1740 if (!empty($data['gallery_ids']) && count($data['gallery_ids']) > 0) $product->set_gallery_image_ids($data['gallery_ids']);
1741
1742 // SKU/*
1743 // if( ! empty( $data['sku'] ) )
1744 // $product->set_sku( $data['sku'] );
1745
1746
1747 // STOCK (stock will be managed in variations)
1748 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
1749 if ($data['manager_stock'] == '0')
1750 {
1751 $product->set_manage_stock(false);
1752 }
1753 else
1754 {
1755 $product->set_manage_stock(true);
1756 }
1757
1758 $product->set_stock_status('');
1759
1760 // Tax class
1761 if (empty($data['tax_class'])) $product->set_tax_class($data['tax_class']);
1762
1763 // WEIGHT
1764 if (!empty($data['weight'])) $product->set_weight(''); // weight (reseting)
1765 else $product->set_weight($data['weight']);
1766
1767 $product->validate_props(); // Check validation
1768 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1769 $product_attributes = array();
1770
1771 foreach ($data['attributes'] as $key => $terms)
1772 {
1773 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1774 $attr_label = ucfirst($key); // attribute label name
1775 $attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug
1776 // NEW Attributes: Register and save them
1777 if (!taxonomy_exists($taxonomy))
1778
1779 var_dump(save_product_attribute_from_name($attr_name, $attr_label));
1780
1781 $product_attributes[$taxonomy] = array(
1782 'name' => $taxonomy,
1783 'value' => '',
1784 'position' => '',
1785 'is_visible' => 0,
1786 'is_variation' => 1,
1787 'is_taxonomy' => 1
1788 );
1789
1790 foreach ($terms as $value)
1791 {
1792 $term_name = ucfirst($value);
1793 $term_slug = sanitize_title($value);
1794
1795 // Check if the Term name exist and if not we create it.
1796 if (!term_exists($value, $taxonomy)) wp_insert_term($term_name, $taxonomy, array(
1797 'slug' => $term_slug
1798 )); // Create the term
1799 // Set attribute values
1800 wp_set_post_terms($product_id, $term_name, $taxonomy, true);
1801 }
1802 }
1803
1804 update_post_meta($product_id, '_product_attributes', $product_attributes);
1805 $product->save(); // Save the data
1806
1807}
1808
1809function get_product_category($catname)
1810{
1811 return $catname;
1812 if ($catname == '')
1813 {
1814 $catname = "CAMISAS";
1815 }
1816 else
1817 {
1818 $catnamesub = $catname;
1819 $slug = $catnamesub;
1820 //var_dump($slug);
1821 $productCategory = get_term_by('name', $slug, 'product_cat');
1822
1823 //echo "termo Id";
1824 //var_dump($productCategory->term_id);
1825 if ($productCategory)
1826 {
1827 $cat_id = get_term_by('id', $productCategory->term_id, 'product_cat');
1828 }
1829 else
1830 {
1831 return false;
1832 }
1833 //$cat_id = get_category($productCategory->term_id);
1834 //echo "cat_id";
1835 //var_dump($cat_id);
1836
1837 }
1838
1839 if (empty($cat_id))
1840 {
1841 //echo "insere um termo se não existir a categoria<br>";
1842 //var_dump($cat_id);
1843 $arg = array(
1844 'description' => $slug,
1845 'parent' => 0
1846 );
1847 $cat_id = wp_insert_term($slug, "product_cat", $arg);
1848 //echo "id inserido da categoria criada<br>";
1849 //var_dump($cat_id);
1850 return $cat_id['term_id'];
1851 }
1852 else
1853 {
1854 //var_dump("retornando resultado existindo uma categoria correspondente");
1855 return $cat_id->term_id;
1856 }
1857}
1858/**
1859 * Update a new variable product (with new attributes if they are).
1860 * (Needed functions:
1861 *
1862 * @since 3.0.0
1863 * @param array $data | The data to insert in the product.
1864 */
1865function update_product_variation($data)
1866{
1867 if (!function_exists('save_product_attribute_from_name')) return;
1868
1869 $category_id = get_product_category($data['category']);
1870 $postname = sanitize_title($data['title']);
1871 $author = empty($data['author']) ? '1' : $data['author'];
1872
1873 if (empty($data['excerpt']))
1874 {
1875 $data['excerpt'] = $postname;
1876 }
1877
1878 if (empty($data['ID']))
1879 {
1880
1881 $post_data = array(
1882 //'post_author' => $author,
1883 'post_name' => $postname,
1884 'post_title' => $data['title'],
1885 'post_content' => $data['content'],
1886 'post_excerpt' => $data['excerpt'],
1887 'post_status' => 'publish',
1888 'ping_status' => 'closed',
1889 'post_type' => 'product',
1890 'guid' => home_url('/product/' . $postname . '/') ,
1891 //'tax_input' => ['product_cat' => $category_id]
1892
1893 );
1894
1895 $product_id = wp_insert_post($post_data);
1896 //wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
1897
1898 }
1899 else
1900 {
1901 $post_data = array(
1902 'ID' => $data['ID'],
1903 'post_name' => $postname,
1904 'post_excerpt' => $data['excerpt'],
1905 'ping_status' => 'closed',
1906 'post_type' => 'product',
1907 'guid' => home_url('/product/' . $postname . '/')
1908 );
1909 $product_id = wp_update_post($post_data);
1910 }
1911
1912 $product = new WC_Product_Variable($product_id);
1913 $product->save();
1914
1915 ## ---------------------- Other optional data ---------------------- ##
1916 ## (see WC_Product and WC_Product_Variable setters methods)
1917 //THE PRICES (No prices yet as we need to create product variations)
1918 //IMAGES GALLERY
1919 if (!empty($data['gallery_ids']) && count($data['gallery_ids']) > 0) $product->set_gallery_image_ids($data['gallery_ids']);
1920
1921 //SKU
1922 if (!empty($data['sku'])) $product->set_sku($data['sku']);
1923
1924 // STOCK (stock will be managed in variations)
1925 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
1926 if ($data['manager_stock'] == '0')
1927 {
1928 $product->set_manage_stock(false);
1929 }
1930 else
1931 {
1932 $product->set_manage_stock(true);
1933 }
1934
1935 $product->set_stock_status('');
1936
1937 // Tax class
1938 if (empty($data['tax_class'])) $product->set_tax_class($data['tax_class']);
1939
1940 // WEIGHT
1941 if (!empty($data['weight'])) $product->set_weight($data['weight']); // weight (reseting)
1942
1943
1944 //length
1945 if (!empty($data['length'])) $product->set_length($data['length']); // length (reseting)
1946
1947 $product->validate_props(); // Check validation
1948 //WIDTH
1949 if (!empty($data['width'])) $product->set_width($data['width']); // weight (reseting)
1950
1951 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1952 $product_attributes = array();
1953 echo "Atributes da persistência do Objeto (não da variação)";
1954 //var_dump($data['attributes']);
1955
1956 foreach ($data['attributes'] as $key => $terms)
1957 {
1958 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1959 $attr_label = ucfirst($key); // attribute label name
1960 $attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug
1961 // NEW Attributes: Register and save them
1962 if (!taxonomy_exists($taxonomy)) echo "salvando taxonomia: name:{$attr_name}, label:{$attr_label}, tax:{$taxonomy} <br>";
1963
1964 echo "salvando taxonomia: name:{$attr_name}, label:{$attr_label}, tax:{$taxonomy} <br>";
1965 //var_dump(save_product_attribute_from_name($attr_name, $attr_label));
1966 //$slug = 'pa_' . strtolower($attribute->name);
1967 $attribute_id = wc_create_attribute(array(
1968 'name' => $attr_label,
1969 'slug' => $attr_name,
1970 'type' => 'product',
1971 'order_by' => 'menu_order',
1972 'has_archives' => false,
1973 ));
1974
1975 //var_dump($attribute_id);
1976 //Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
1977 /*register_taxonomy(
1978 $taxonomy,
1979 apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy, array( 'product' ) ),
1980 apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy, array(
1981 'labels' => array(
1982 'name' => $attr_label,
1983 ),
1984 'hierarchical' => true,
1985 'show_ui' => false,
1986 'query_var' => true,
1987 'rewrite' => false,
1988 ) )
1989 );*/
1990
1991 $product_attributes[$taxonomy] = array(
1992 'name' => $taxonomy,
1993 'value' => '',
1994 'position' => '',
1995 'is_visible' => 0,
1996 'is_variation' => 1,
1997 'is_taxonomy' => 1
1998 );
1999
2000 foreach ($terms as $value)
2001 {
2002 $term_name = ucfirst($value);
2003 $term_slug = sanitize_title($value);
2004
2005 // Check if the Term name exist and if not we create it.
2006 if (!term_exists($value, $taxonomy)){
2007 echo "salvando termo: term_name:{$term_name} | tax:{$taxonomy} | slug:{$term_slug}<br>";
2008 var_dump(wp_insert_term($term_name, $taxonomy, array(
2009 'slug' => $term_slug
2010 ))); // Create the term
2011 }
2012 /*
2013 $terms = get_terms([
2014 'taxonomy' => $taxonomy,
2015 'hide_empty' => false,
2016 ]);
2017
2018 echo "dump nas terms";
2019 var_dump($terms);
2020*/
2021 // Set attribute values
2022 if (isset($data['ID']))
2023 {
2024 echo "setando valores dos atributos: id:{$data['ID']}(atualizando), tax:{$taxonomy}, term_name:{$term_name}<br>";
2025 var_dump(wp_set_post_terms($product_id, $term_name, $taxonomy, true));
2026 }
2027 else
2028 {
2029 echo "setando valores dos atributos: id:{$product_id}(inserindo), tax:{$taxonomy}, term_name:{$term_name}<br>";
2030 var_dump(wp_set_post_terms($product_id, $term_name, $taxonomy, true));
2031 }
2032
2033 }
2034 }
2035 //print_r($product);
2036 if (isset($data['ID']))
2037 {
2038 echo "atualizando: product Attrb: {$product_attributes}<br>";
2039 update_post_meta($product_id, '_product_attributes', $product_attributes);
2040 }
2041 else
2042 {
2043 echo "inserindo: product Attrb:<br>";
2044 var_dump($product_attributes);
2045 update_post_meta($product_id, '_product_attributes', $product_attributes);
2046 }
2047 //var_dump($product);
2048 //exit;
2049 $product->save(); // Save the data
2050 return $product_id;
2051}
2052/*
2053*
2054$parent_id = 746; // Or get the variable product id dynamically
2055
2056// The variation data
2057$variation_data = array(
2058 'attributes' => array(
2059 'size' => 'M',
2060 'color' => 'Green',
2061 ),
2062 'sku' => '',
2063 'regular_price' => '22.00',
2064 'sale_price' => '',
2065 'stock_qty' => 10,
2066);
2067
2068// The function to be run
2069create_product_variation( $parent_id, $variation_data );
2070*/
2071/**
2072 * Create a product variation for a defined variable product ID.
2073 *
2074 * @since 3.0.0
2075 * @param int $product_id | Post ID of the product parent variable product.
2076 * @param array $variation_data | The data to insert in the product.
2077 */
2078
2079function _create_product_variation($product_id, $variation_data)
2080{
2081 // Get the Variable product object (parent)
2082 $product = wc_get_product($product_id);
2083
2084 // Creating the product variation
2085 if (empty($variation_data['update']))
2086 {
2087 //var_dump($variation_data);
2088 $variation_post = array(
2089 'post_title' => MigrationRules::getProductTeste()->produtoNome,
2090 'post_name' => 'product-' . MigrationRules::getPostId() . '-variation',
2091 'post_status' => 'publish',
2092 'post_parent' => MigrationRules::getPostId() ,
2093 'post_type' => 'product_variation',
2094 'guid' => site_url() . "/" . MigrationRules::getPostId()
2095 );
2096
2097 $variation_id = wp_insert_post($variation_post);
2098 }
2099 else
2100 {
2101
2102 $variation_post = array(
2103 'ID' => $variation_data['ID'],
2104 'post_title' => $product->get_name() ,
2105 'post_name' => 'product-' . $product_id . '-variation',
2106 'post_status' => 'publish',
2107 'post_parent' => $product_id,
2108 'post_type' => 'product_variation',
2109 'guid' => $product->get_permalink()
2110 );
2111
2112 $variation_id = wp_update_post($variation_post);
2113 }
2114
2115 // Get an instance of the WC_Product_Variation object
2116 $variation = new WC_Product_Variation($variation_id);
2117 //var_dump($variation_id);
2118 //exit;
2119 echo "Registrando taxonomia<br>";
2120 var_dump($variation_data['attributes']);
2121
2122 foreach ($variation_data['attributes'] as $attribute => $term_name)
2123 {
2124
2125 $taxonomy = 'pa_' . $attribute; // The attribute taxonomy
2126 echo "taxonomia problemática: {$taxonomy}<br>";
2127
2128 // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2129 if (!taxonomy_exists($taxonomy))
2130 {
2131 echo "Registrando taxonomia : {$attribute}<br>";
2132 register_taxonomy($taxonomy, 'product_variation', array(
2133 'hierarchical' => false,
2134 'label' => ucfirst($attribute) ,
2135 'query_var' => true,
2136 'rewrite' => array(
2137 'slug' => sanitize_title($attribute)
2138 ) , // The base slug
2139
2140 ));
2141 }
2142
2143 $ntax = ucfirst($attribute);
2144 echo "taxonomia com ucfirst: {$ntax}<br>";
2145 echo "nome do termo";
2146 var_dump($term_name);
2147
2148 // Check if the Term name exist and if not we create it.
2149 if (!term_exists($term_name, $taxonomy)) echo "TERMO INSERIDO {$term_name}<br> ";
2150 var_dump(wp_insert_term($term_name, $taxonomy)); // Create the term
2151 $term_slug = get_term_by('name', $term_name, $taxonomy)->slug; // Get the term slug
2152 // Get the post Terms names from the parent variable product.
2153 $post_term_names = wp_get_post_terms($product_id, $taxonomy, array(
2154 'fields' => 'names'
2155 ));
2156
2157 // Check if the post term exist and if not we set it in the parent variable product.
2158 if (!in_array($term_name, $post_term_names)) echo "wp_set_post_terms: nome do slug {$term_slug} | productId:{$product_id} | term_name:{$term_name} | tax:{$taxonomy}<br>";
2159 var_dump(wp_set_post_terms($product_id, $term_name, $taxonomy, true));
2160
2161 //var_dump($term_slug);
2162 // Set/save the attribute data in the product variation
2163 echo "update_post_meta: variation_id: [{$variation_id}] - " . 'attribute_' . $taxonomy . "<br>";
2164 var_dump(update_post_meta($variation_id, 'attribute_' . $taxonomy, $term_slug, true));
2165 }
2166
2167 ## Set/save all other data
2168
2169
2170 // SKU
2171 //if( ! empty( $variation_data['sku'] ) )
2172 // $variation->set_sku( $variation_data['sku'] );
2173 // Prices
2174 // Prices
2175 echo "<h4>valores do preço promocional</h4><br>";
2176 var_dump($variation_data['sale_price'] == "0,00");
2177 var_dump($variation_data['sale_price']);
2178
2179 if (empty($variation_data['sale_price']))
2180 {
2181
2182 $variation->set_price($variation_data['regular_price']);
2183 }
2184 else
2185 {
2186 if (!$variation_data['sale_price'] == "0,00")
2187 {
2188 $variation->set_sale_price($variation_data['sale_price']);
2189 }
2190 $variation->set_price($variation_data['regular_price']);
2191 }
2192 $variation->set_regular_price($variation_data['regular_price']);
2193
2194 // Stock
2195 var_dump($variation_data['stock_qty']);
2196 if (!empty($variation_data['stock_qty']))
2197 {
2198 $variation->set_stock_quantity($variation_data['stock_qty']);
2199 $variation->set_manage_stock(true);
2200 $variation->set_stock_status('');
2201 }
2202 else
2203 {
2204 //$variation->set_manage_stock(true);
2205 $variation->set_manage_stock(false);
2206 $variation->set_stock_status('outofstock');
2207 }
2208
2209 if ($variation_data['stock_qty'] == 0)
2210 {
2211 $variation->set_manage_stock(false);
2212 $variation->set_stock_status('outofstock');
2213 }
2214 $variation->set_weight(''); // weight (reseting)
2215 //var_dump( $variation_data['ID']);
2216 $variation->save(); // Save the data
2217 //var_dump($variation->get_stock_quantity());
2218 //exit;
2219
2220}
2221
2222function tirarAcentos($string)
2223{
2224 return preg_replace(array(
2225 "/(á|à|ã|â|ä)/",
2226 "/(Á|À|Ã|Â|Ä)/",
2227 "/(é|è|ê|ë)/",
2228 "/(É|È|Ê|Ë)/",
2229 "/(í|ì|î|ï)/",
2230 "/(Í|Ì|Î|Ï)/",
2231 "/(ó|ò|õ|ô|ö)/",
2232 "/(Ó|Ò|Õ|Ô|Ö)/",
2233 "/(ú|ù|û|ü)/",
2234 "/(Ú|Ù|Û|Ü)/",
2235 "/(ñ)/",
2236 "/(Ñ)/"
2237 ) , explode(" ", "a A e E i I o O u U n N") , $string);
2238}
2239
2240/**
2241 * Method to delete Woo Product
2242 *
2243 * @param int $id the product ID.
2244 * @param bool $force true to permanently delete product, false to move to trash.
2245 * @return \WP_Error|boolean
2246 */
2247function wh_deleteProduct($id, $force = false)
2248{
2249 $product = wc_get_product($id);
2250
2251 if (empty($product)) return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce') , 'product', $id));
2252
2253 // If we're forcing, then delete permanently.
2254 if ($force)
2255 {
2256 if ($product->is_type('variable'))
2257 {
2258 foreach ($product->get_children() as $child_id)
2259 {
2260 $child = wc_get_product($child_id);
2261 $child->delete(true);
2262 }
2263 }
2264 elseif ($product->is_type('grouped'))
2265 {
2266 foreach ($product->get_children() as $child_id)
2267 {
2268 $child = wc_get_product($child_id);
2269 $child->set_parent_id(0);
2270 $child->save();
2271 }
2272 }
2273
2274 $product->delete(true);
2275 $result = $product->get_id() > 0 ? false : true;
2276 }
2277 else
2278 {
2279 $product->delete();
2280 $result = 'trash' === $product->get_status();
2281 }
2282
2283 if (!$result)
2284 {
2285 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce') , 'product'));
2286 }
2287
2288 // Delete parent product transients.
2289 if ($parent_id = wp_get_post_parent_id($id))
2290 {
2291 wc_delete_product_transients($parent_id);
2292 }
2293 return true;
2294}
2295
2296/**
2297 * Add a widget to the dashboard.
2298 *
2299 * This function is hooked into the 'wp_dashboard_setup' action below.
2300 */
2301function wporg_add_dashboard_widgets()
2302{
2303 wp_add_dashboard_widget('wporg_dashboard_widget', // Widget slug.
2304 esc_html__('Wiki Importer', 'wporg') , // Title.
2305 'wporg_dashboard_widget_render'
2306 // Display function.
2307 );
2308}
2309add_action('wp_dashboard_setup', 'wporg_add_dashboard_widgets');
2310
2311/**
2312 * Create the function to output the content of our Dashboard Widget.
2313 */
2314function wporg_dashboard_widget_render()
2315{
2316 // Display whatever you want to show.
2317 $html = '<h2>Clique <span style="color:#0099FF" id="importData"><b>aqui</b></span> para importar Dados do ERP Wiki</h2>
2318 <p id="link_produtos">Visualizar Produtos -> <a href="edit.php?post_type=product">aqui</a> </p>
2319 <div id="importBlock">
2320 <img id="importLogo" width="450" height="368" src="https://lindabrand.com.br/wp-content/uploads/importLogo.png"/>
2321 </div>';
2322
2323 $html .= '<script>
2324 jQuery("#link_produtos").hide();
2325 jQuery("#importData").click(function(){
2326
2327 jQuery.ajax({
2328 type: "GET",
2329 url: "admin.php?action=executeWikiImport",
2330 beforeSend: function(){
2331 jQuery("#importLogo").hide();
2332 var img = jQuery("<img />", {
2333 id: "importGif",
2334 src: "https://lindabrand.com.br/wp-content/uploads/import.gif",
2335 width: "420px",
2336 height: "368",
2337 alt: "import"
2338 });
2339
2340 img.appendTo(jQuery("#importBlock"));
2341 },
2342 success: function(){
2343 alert("Dados Importados com sucesso");
2344 jQuery("#importGif").hide();
2345 jQuery("#importLogo").show();
2346 jQuery("#link_produtos").show();
2347 }
2348 });
2349 });
2350
2351 </script>';
2352
2353 echo $html;
2354}
2355
2356//add_action( 'importInitializer', 'executeWikiImport', 10,0);
2357//add_action("after_setup_theme",function(){
2358// do_action('importInitializer');
2359//});
2360add_action('init', 'executeWikiImportHome');
2361function executeWikiImportHome()
2362{
2363 if (isset($_GET['action']) && $_GET['action'] == "executeWikiImport" && is_home())
2364 {
2365 echo "<h1>No contexto da action [init]</h1>";
2366 initMigration();
2367 //initMigration();
2368 //create curl resource
2369 //$ch = curl_init();
2370 //curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2371 //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2372 //$output = curl_exec($ch);
2373 //curl_close($ch);
2374
2375 }
2376}
2377
2378add_action('admin_init', 'executeWikiImport');
2379function executeWikiImport()
2380{
2381 if (isset($_GET['action']) && $_GET['action'] == "executeWikiImport")
2382 {
2383 echo "<h1>No contexto da action [admin_init]</h1>";
2384 initMigration();
2385 //initMigration();
2386 //create curl resource
2387 //$ch = curl_init();
2388 //curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2389 //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2390 //$output = curl_exec($ch);
2391 //curl_close($ch);
2392
2393 }
2394}
2395
2396add_action('woocommerce_thankyou', 'MyPersistRemoteObject3', 20, 2);
2397function MyPersistRemoteObject3($order_id)
2398{
2399
2400 $ch = curl_init();
2401 curl_setopt_array($ch, array(
2402 CURLOPT_URL => "http://localhost/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_b1a61b313f9f99357ee53fc0578c3535fcf53492&consumer_secret=cs_2d13d58f38d093d436e8ea0db8f06d673e605eae",
2403 CURLOPT_RETURNTRANSFER => true,
2404 CURLOPT_ENCODING => "",
2405 CURLOPT_MAXREDIRS => 10,
2406 CURLOPT_TIMEOUT => 30,
2407 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2408 CURLOPT_CUSTOMREQUEST => "GET",
2409 CURLOPT_SSL_VERIFYPEER => false,
2410
2411 CURLOPT_HTTPHEADER => array(
2412 "Authorization: Basic *****************",
2413 "Cache-Control: no-cache"
2414 ) ,
2415 ));
2416 echo "http://localhost/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_b1a61b313f9f99357ee53fc0578c3535fcf53492&consumer_secret=cs_2d13d58f38d093d436e8ea0db8f06d673e605eae";
2417 $result = curl_exec($ch);
2418 var_dump($result);
2419
2420 $jsonResult = json_decode($result);
2421 var_dump($jsonResult);
2422 foreach ($jsonResult->meta_data as $k => $meta)
2423 {
2424 if ($meta->key == "Tipo de pagamento" && $meta->value == "Boleto")
2425 {
2426 $bolVencimento = new stdClass;
2427 $bolVencimento->key = "Boleto Vencimento";
2428 $order = new WC_Order($order_id);
2429 $order_date = $order->order_date;
2430 $date = new DateTime($order_date);
2431 $date->modify("+3 day");
2432 $bolVencimento->value = $date->format("d-m-Y");
2433 $jsonResult->meta_data[] = $bolVencimento;
2434 }
2435 }
2436 //http://app.wikisistemas.com.br:8088/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=732&guid=8ad303b9-8f7a-4525-8502-67e1b4dd2414&estoquePositivo=0
2437 $replaced_result = substr_replace(json_encode($jsonResult) , '"empresa":732, "guid":"8ad303b9-8f7a-4525-8502-67e1b4dd2414",', 11, 0);
2438
2439 //print_r($replaced_result);
2440 //echo " ";
2441 //print_r(base64_encode($replaced_result));
2442 /* $opts = [
2443 'http' => [
2444 'method' => 'GET'
2445 ]
2446 ];*/
2447
2448 //$context = stream_context_create($opts);
2449 //$result = file_get_contents('http://app.wikisistemas.com.br:8086/EcommerceExternoWebservice.asmx/RecebePedidoWooCommerce?json=' . base64_encode($replaced_result), false, $context);
2450 //var_dump($result);
2451 //
2452 //print_r($replaced_result);
2453 $ch2 = curl_init();
2454 curl_setopt_array($ch2, array(
2455 CURLOPT_URL => 'http://52.6.107.225/script.php?pedido=' . base64_encode($replaced_result) ,
2456 CURLOPT_RETURNTRANSFER => true,
2457 CURLOPT_ENCODING => "",
2458 CURLOPT_MAXREDIRS => 10,
2459 CURLOPT_TIMEOUT => 30,
2460 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2461 CURLOPT_CUSTOMREQUEST => "GET",
2462 CURLOPT_SSL_VERIFYPEER => false,
2463
2464 CURLOPT_HTTPHEADER => array(
2465 "Authorization: Basic *****************",
2466 "Cache-Control: no-cache"
2467 ) ,
2468 ));
2469
2470 $result2 = curl_exec($ch2);
2471 echo "retorno do WS<br>";
2472 var_dump($result2);
2473 echo "pedido base64<br>";
2474 print_r($replaced_result);
2475
2476}
2477
2478add_filter('woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2);
2479function grey_out_variations_when_out_of_stock($grey_out, $variation)
2480{
2481 if (!$variation->is_in_stock())
2482 {
2483 return false;
2484 }
2485 else
2486 {
2487 return true;
2488 }
2489}
2490////*/5 * * * * /opt/bitnami/php/bin/php ~/apps/wordpress/htdocs/cron-importer.php
2491//venda somente a partir de 2 produtos
2492/*add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 10, 3 );
2493function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {
2494
2495 $cart_items_count = WC()->cart->get_cart_contents_count();
2496 $total_count = $cart_items_count + $quantity;
2497
2498 if( $cart_items_count > 2 || $total_count > 2 ){
2499 // Set to false
2500 $passed = true;
2501 // Display a message
2502
2503 }
2504 else{
2505 wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
2506 }
2507 return $passed;
2508}
2509
2510// Checking and validating when updating cart item quantities when products are added to cart
2511add_filter( 'woocommerce_update_cart_validation', 'only_six_items_allowed_cart_update', 10, 4 );
2512function only_six_items_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {
2513
2514 $cart_items_count = WC()->cart->get_cart_contents_count();
2515 $original_quantity = $values['quantity'];
2516 $total_count = $cart_items_count - $original_quantity + $updated_quantity;
2517
2518 if( $cart_items_count > 2 || $total_count > 2 ){
2519 // Set to false
2520 $passed = true;
2521 // Display a message
2522
2523 }else{
2524 wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
2525 }
2526 return $passed;
2527}
2528
2529/**
2530 * When an item is added to the cart, check total cart quantity
2531*/
2532/*
2533function so_21363268_limit_cart_quantity( $valid, $product_id, $quantity ) {
2534
2535 $max_allowed = 6;
2536 $current_cart_count = WC()->cart->get_cart_contents_count();
2537
2538 if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $valid ){
2539 wc_add_notice( sprint( __( 'Whoa hold up. You can only have %d items in your cart', 'your-plugin-textdomain' ), $max ), 'error' );
2540 $valid = false;
2541 }
2542
2543 return $valid;
2544
2545}
2546add_filter( 'woocommerce_add_to_cart_validation', 'so_21363268_limit_cart_quantity', 10, 3 );*/
2547
2548// On single product pages
2549//add_filter( 'woocommerce_quantity_input_args', 'min_qty_filter_callback', 20, 2 );
2550/*
2551add_action( 'woocommerce_check_cart_items', 'wc_min_item_required_qty' );
2552function wc_min_item_required_qty() {
2553 $categories = array('OUTLET'); // The targeted product category
2554 $min_item_qty = 2; // Minimum Qty required (for each item)
2555 $display_error = false; // Initializing
2556
2557 // Loop through cart items
2558 foreach(WC()->cart->get_cart() as $cart_item ) {
2559 $item_quantity = $cart_item['quantity']; // Cart item quantity
2560 $product_id = $cart_item['product_id']; // The product ID
2561
2562 // For cart items remaining to "Noten" producct category
2563 if( has_term( $categories, 'product_cat', $product_id ) && $item_quantity < $min_item_qty ) {
2564 wc_clear_notices(); // Clear all other notices
2565
2566 // Add an error notice (and avoid checkout).
2567 wc_add_notice( sprintf( 'Bitte beachte die Mindestbestellmenge. Du brauchst mindestens %s Notenexemplare pro Arrangement. Aktuell hast du %s Stück in deinem Warenkorb.', $min_item_qty , $item_quantity ), 'error' );
2568 break; // Stop the loop
2569 }
2570 }
2571}*/
2572
2573
2574
2575/*
2576function update_sku( $sku ){
2577
2578 $args = array(
2579 'post_type' => 'product',
2580 'posts_per_page' => 12
2581 );
2582 $i=0;
2583 $loop = new WP_Query( $args );
2584
2585 if ( $loop->have_posts() ) {
2586 while ( $loop->have_posts() ) : $loop->the_post();
2587
2588 $random_sku = mt_rand(100000, 999999);
2589
2590 update_post_meta($loop->post->ID,'_sku',$random_sku);
2591
2592 $i++;
2593 endwhile;
2594 } else {
2595 echo __( 'No products found' );
2596 }
2597 wp_reset_postdata();
2598}
2599*/
2600
2601add_filter( 'init', 'updateAllSku', 10, 1);
2602function updateAllSku(){
2603 if(isset($_GET['update_sku'])){
2604 $args = array(
2605 'post_type' => 'product',
2606 'posts_per_page' => 200
2607 );
2608
2609 $result = new WP_Query( $args );
2610 foreach($result->posts as $k=>$product){
2611 if(isset($product->ID)){
2612 update_post_meta($product->ID,'_sku',$product->ID);
2613 }
2614 }
2615
2616 $result2 = new WP_Query(array(
2617 'post_type' => 'product_variation',
2618 'posts_per_page' => 200
2619 ));
2620
2621 print_r($result2->posts);
2622 }
2623}
2624