format(DATE_ATOM)); if(!is_dir(AMAZON_SAVE_PATH)){ mkdir(AMAZON_SAVE_PATH); } // Benoetigte include Dateien require (DIR_FS_INC . 'yes_write_notice.inc.php'); require (DIR_FS_INC . 'xtc_encrypt_password.inc.php'); require (DIR_FS_INC . 'xtc_get_customer_status_value.inc.php'); require (DIR_FS_INC . 'xtc_get_serial_number.inc.php'); require (DIR_FS_INC . 'xtc_get_order_html_for_pdf.inc.php'); require (DIR_FS_INC . 'xtc_get_orders_ebay_seller.inc.php'); require (DIR_FS_INC . 'xtc_format_price_order.inc.php'); require (DIR_FS_CATALOG . 'lang/'.$_SESSION['language'].'/modules/order_total/ot_subtotal.php'); require (DIR_FS_CATALOG . 'lang/'.$_SESSION['language'].'/modules/order_total/ot_total.php'); include('includes/classes/amz_Helper.php'); include('includes/classes/amz_ReportList.php'); include('includes/classes/amz_Sync.php'); include('includes/classes/amz_SubmitFeed.php'); include('includes/classes/amz_Feedhandler.php'); require_once('includes/classes/product.php'); require_once('includes/classes/class.basics.php'); require_once('includes/classes/order.php'); require_once('includes/classes/reclamation.php'); include_once('includes/classes/yes_shipping.php'); include_once(DIR_FS_CATALOG.'includes/classes/xtcPrice.php'); include_once(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.phpmailer.php'); if(isset($_GET['action']) and $_GET['action'] == 'send_order_fulfillment_xslx'){ require_once('amazon_sp_versandmeldung_xslx.php'); exit; } if(isset($_GET['action']) and $_GET['action'] == 'fulfillment_dl'){ $target_file = main::get_secure_path().'Versand-Amazon.txt'; header('Content-Disposition: attachment; filename=' . basename($target_file) ); header('Content-Type: text/plain; charset=UTF-8'); header('Content-Length: ' . filesize($target_file)); header('Cache-Control: must-revalidate'); header('Pragma: public'); readfile($target_file); exit; } // BOF AMAZON SP require_once(DIR_WS_CLASSES.'amazon_sp.php'); $ASP_blank = new amazon_sp(null,false); foreach($ASP_blank->auth_params->users as $u=>$v){ $current_seller = $u; $_SESSION['current_amazon_selling_partner_id'] = $current_seller; } $ASP = new amazon_sp($current_seller); $amazon_user_array = [['id'=>'','text'=>TEXT_SELECT]]; $auth_user_counter = 0; foreach((array)$ASP->auth_params->users as $spID=>$u){ $amazon_user_array[] = ['id'=>$spID, 'text'=>$spID]; $auth_user_counter++; } if(isset($_REQUEST['current_amazon_merchant_id'])){ $_SESSION['current_amazon_merchant_id'] = xtc_db_input($_REQUEST['current_amazon_merchant_id']); xtc_redirect(xtc_href_link('amazon.php')); } if(isset($_REQUEST['current_amazon_selling_partner_id'])){ $_SESSION['current_amazon_selling_partner_id'] = xtc_db_input($_REQUEST['current_amazon_selling_partner_id']); xtc_redirect(xtc_href_link('amazon.php')); } $A = new amazon_helper; $AMAZON_SCHEDULE_VALUES = $A->get_amazon_schedule_values(); if(defined('MODULE_OTHER_AMAZON_CUSTOMERS_STATUS_ID')){ foreach(xtc_get_customers_statuses() as $status){ if($status['id'] == MODULE_OTHER_AMAZON_CUSTOMERS_STATUS_ID){ $cs_image = (isset($status['cs_image']))?$status['cs_image']:''; $cs_name = $status['text']; } } } if(isset($_GET['mario'])){ $spid = 'A3MIBXXS68ROV2'; $c = json_decode(file_get_contents(main::get_secure_path().'AMAZON_SP_AUTH.json')); foreach($c->users as $cu=>$cv){ if($cu == $spid){ $cv->auth->access_token = 'TEST STR'; } } print_r($c); die('stop'); } $rec_id_query = main::get_notice_recipients('amazon'); $smarty = new Smarty; $smarty->caching = false; $smarty->compile_dir=DIR_FS_CATALOG.'templates_c'; $smarty->template_dir=DIR_FS_ADMIN.'templates'; $smarty->assign('language_path',DIR_FS_CATALOG.'lang/'.$_SESSION['language'].'/admin/'.$_SESSION['language'].'.conf'); $smarty->assign('FORM_END',''); $lang_vars = array( 'BUTTON_GET_ACTIVE_LISTINGS' => BUTTON_GET_ACTIVE_LISTINGS, 'BUTTON_GET_OPEN_LISTINGS' => BUTTON_GET_OPEN_LISTINGS, 'BUTTON_GET_FLAT_FILE_ORDERS_DATA' => BUTTON_GET_FLAT_FILE_ORDERS_DATA, 'BUTTON_AMAZON_TRANSFER' => BUTTON_AMAZON_TRANSFER, 'BUTTON_AMAZON_TODO_LIST' => BUTTON_AMAZON_TODO_LIST, 'BUTTON_REPORTS' => BUTTON_REPORTS, 'ALLOCATE_AMAZON_PRODUCT'=>ALLOCATE_AMAZON_PRODUCT, 'BUTTON_FINISH_TODO'=>BUTTON_FINISH_TODO, 'TEXT_UPDATE_AMAZON_INTRO'=>TEXT_UPDATE_AMAZON_INTRO, 'AMAZON_REPORT_TYPE_GET_ORDERS_DATA',AMAZON_REPORT_TYPE_GET_ORDERS_DATA, 'TEXT_AMAZON_REPORT_TYPE'=>TEXT_AMAZON_REPORT_TYPE, 'TEXT_AMAZON_SCHEDULE'=>TEXT_AMAZON_SCHEDULE, 'TEXT_AMAZON_SCHEDULEDDATE'=>TEXT_AMAZON_SCHEDULEDDATE, 'TEXT_AMAZON_SCHEDULES_INTRO'=>TEXT_AMAZON_SCHEDULES_INTRO, 'TEXT_AMAZON_PRODUCTS_COUNT'=>TEXT_AMAZON_PRODUCTS_COUNT, 'TEXT_AMAZON_FEEDSUBMISSION_COUNT'=>TEXT_AMAZON_FEEDSUBMISSION_COUNT, 'TEXT_AMAZON_REPORTREQUEST_COUNT'=>TEXT_AMAZON_REPORTREQUEST_COUNT, 'TEXT_AMAZON_REPORTSCHEDULE_COUNT'=>TEXT_AMAZON_REPORTSCHEDULE_COUNT, 'BUTTON_PROCESS_ORDER'=>BUTTON_PROCESS_ORDER, 'BUTTON_PROCESS_ORDERS_FEED'=>BUTTON_PROCESS_ORDERS_FEED, 'BUTTON_AMAZON_IMPORT_LAGERBERICHT'=>BUTTON_AMAZON_IMPORT_LAGERBERICHT, 'BUTTON_AMAZON_IMPORT_LAGERBERICHT_UPLOAD'=>BUTTON_AMAZON_IMPORT_LAGERBERICHT_UPLOAD, 'TEXT_AUTOALLOCATE_FROM_IMPORT_BUTTON'=>TEXT_AUTOALLOCATE_FROM_IMPORT_BUTTON, 'TEXT_DELETE_IMPORT_BUTTON'=>TEXT_DELETE_IMPORT_BUTTON, 'TEXT_SYNC_FROM_IMPORT_BUTTON'=>TEXT_SYNC_FROM_IMPORT_BUTTON, 'SELLING_PARTNER_ID'=>$_SESSION['current_amazon_selling_partner_id'], // 'MERCHANT_ID'=>$_SESSION['current_amazon_merchant_id'], 'TEXT_SELECT_MERCHANT_ID_TITLE'=>TEXT_SELECT_MERCHANT_ID_TITLE, 'TEXT_SELECT_MERCHANT_ID'=>TEXT_SELECT_MERCHANT_ID, 'INPUT_AMAZON_USER'=>xtc_draw_pull_down_menu('current_amazon_selling_partner_id',$amazon_user_array,$_SESSION['current_amazon_selling_partner_id']), 'TEXT_YOU_MUST_SELECT_AMAZON_ACCOUNT'=>TEXT_YOU_MUST_SELECT_AMAZON_ACCOUNT, 'NUMBER_OF_ACCOUNTS'=>$auth_user_counter, 'BUTTON_AMAZON_CHANGE_ACCOUNT'=>BUTTON_AMAZON_CHANGE_ACCOUNT, 'INTRO_AMAZON_IMPORT_ORDERREPORT'=>INTRO_AMAZON_IMPORT_ORDERREPORT, 'BUTTON_AMAZON_IMPORT_ORDERREPORT'=>BUTTON_AMAZON_IMPORT_ORDERREPORT, ); $versand_file = main::get_secure_path().'Versand-Amazon.txt'; if(is_file($versand_file)){ $smarty->assign([ 'VERSAND_FILE'=>'1', 'VERSAND_FILE_DATE'=>date("d.m.Y H:i:s", filemtime($versand_file)) ]); } $smarty->assign($lang_vars); $page_vars = array( 'GET_ACTIVE_LISTINGS_LINK' => xtc_href_link('amazon.php','action=get_report&ReportType=GET_MERCHANT_LISTINGS_DATA'), 'GET_OPEN_LISTINGS_LINK' => xtc_href_link('amazon.php','action=get_report&ReportType=GET_FLAT_FILE_OPEN_LISTINGS_DATA'), 'GET_FLAT_FILE_ORDERS_DATA_LINK'=>xtc_href_link('amazon.php','action=get_report&ReportType=GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_SHIPPING'), 'REPORTS_LINK' => xtc_href_link('amazon.php','action=reports'), 'TEXT_AMAZON_SP_GET_ORDERS_LINK'=>TEXT_AMAZON_SP_GET_ORDERS_LINK, ); $smarty->assign($page_vars); $basics = new basics; if(isset($_REQUEST['query'])){ $search_term = xtc_db_input($_REQUEST['query']); if(mb_detect_encoding($_REQUEST['query']) == 'UTF-8') $search_term = yes_decode_string($search_term); $query = xtc_db_query( sprintf("SELECT p.products_id,pd.products_name FROM products p LEFT JOIN amazon_products ap USING(products_id) LEFT JOIN products_description pd USING(products_id) WHERE (products_ean LIKE '%%%s%%' or products_name LIKE '%%%s%%' or products_model LIKE '%%%s%%') and pd.language_id='%s' and pd.products_name != '' and ap.products_id IS NULL ORDER BY products_name LIMIT 50", $search_term,$search_term,$search_term,$_SESSION['languages_id'] )); $datas = array(); while($record = xtc_db_fetch_array($query)){ if(!empty($record['products_name'])){ $name = str_replace(array(':','{','}','[',']','"'),' ',$record['products_name']); $sugg = yes_encode_string($name).' ('.$record['products_id'].')'; if(strlen($sugg) > 50){ $sugg = substr($sugg,0,47).'...'; } $datas[] = array('value'=>$record['products_id'], 'label'=>$sugg ); } } $response = json_encode($datas); echo $response; exit; } $action = ''; if(isset($_REQUEST['action'])){ $action = $_REQUEST['action']; } if($auth_user_counter < 1){ $action = 'auth'; } switch($action){ case 'afc_list': $list = \YES4Trade\Model\amazon_feed_collector::get_list(); if(sizeOf($list)){ echo '
'; foreach($list[0] as $k=>$v){ if($k != 'amazon_feed_collector_id'){ printf('',$k); } } echo ''; foreach($list as $row){ echo ''; foreach($row as $k=>$v){ if($k != 'amazon_feed_collector_id'){ printf('',$v); } } echo ''; } echo '
%s
%s
'; }else{ echo 'Keine Einträge'; } echo '
'; exit; break; case 'cleanup': $ao = []; $q = xtc_db_query( "SELECT amazon_orders_id, orders_id FROM amazon_orders" ); while($r = xtc_db_fetch_array( $q ) ){ $ao[] = $r; } foreach($ao as $d){ xtc_db_query(sprintf( "DELETE FROM amazon_orders_products WHERE amazon_orders_id='%d'", $d['amazon_orders_id'] )); xtc_db_query(sprintf( "DELETE FROM amazon_orders WHERE amazon_orders_id='%d'", $d['amazon_orders_id'] )); xtc_db_query(sprintf( "DELETE FROM orders WHERE orders_id='%d'", $d['orders_id'] )); xtc_db_query(sprintf( "DELETE FROM orders_products WHERE orders_id='%d'", $d['orders_id'] )); xtc_db_query(sprintf( "DELETE FROM orders_status_history WHERE orders_id='%d'", $d['orders_id'] )); xtc_db_query(sprintf( "DELETE FROM orders_total WHERE orders_id='%d'", $d['orders_id'] )); } xtc_redirect(xtc_href_link('amazon.php')); break; case 'allocate_save': $oID = xtc_db_input($_GET['oID']); $amazon_order_id = xtc_db_input($_GET['amazon_order_id']); $ok = amazon_sp::check_yes_order_exists_and_not_allocated_to_amazon_order($oID); if(!$ok){ die(json_encode([ 'MSG'=>JS_ERROR_ORDER_NOT_EXISTS_OR_ALLOCATED ])); } $update_sql_array = [ 'orders_id'=>$oID ]; xtc_db_perform('amazon_orders',$update_sql_array, 'update',"orig_amazon_orders_id='".$oID."'"); $order = new order( $oID ); $order->add_history($order->info['orders_status'], false, 'Zuweisung zum Amazon Auftrag '.$amazon_order_id); die(json_encode([ 'MSG'=>'OK', ])); break; case 'allocate_select': $amazon_order_id = $_GET['amazon_order_id']; printf('

%s

',sprintf( TEXT_ALLOCATE_AMAZON_ORDER, $amazon_order_id )); printf('

%s

',TEXT_ALLOCATE_AMAZON_ORDER_MANUALLY); printf('%s %s', TEXT_ORDER, xtc_draw_input_field('yes_amazon_allocation_orders_id',$found_orders_id, 'size="7" maxlength="7"',false,'text',false) ); echo yes_draw_href_button(IMAGE_SAVE, 'javascript:ajaxAllocateSave(\''.$amazon_order_id.'\')', null, 'button', null, false ); exit; break; case 'get_orders': $apiInstance = new SellingPartnerApi\Api\OrdersV0Api($ASP->configObj); $marketplace_ids = array_slice($ASP->get_active_marketplaces(),0,10); $createdAfterDT = new DateTime('-7 Days'); $created_after = $createdAfterDT->format( DateTimeInterface::ISO8601 ); $created_after = str_replace('+0100','',$created_after); $created_before = null; $last_updated_after = null; $last_updated_before = null; $order_statuses = null; $fulfillment_channels = null; $payment_methods = null; $buyer_email = null; $seller_order_id = null; $max_results_per_page = AMAZON_REPORTLIST_MAX_COUNT; $easy_ship_shipment_statuses = null; $electronic_invoice_statuses = null; $next_token = (isset($_GET['NextToken'])) ? $_GET['NextToken'] : null; $amazon_order_ids = null; $actual_fulfillment_supply_source_id = null; $is_ispu = null; $store_chain_store_id = null; $data_elements = null; try{ if($next_token != null){ if(!in_array($_REQUEST['NextToken'],$_SESSION['AMZSP-GETORDERS-HISTORY'])){ $_SESSION['AMZSP-GETORDERS-HISTORY'][] = $_REQUEST['NextToken']; } $res = $apiInstance->getOrders($marketplace_ids,null, null, null, null, null, null, null, null, null, null, null, null, $next_token); }else{ $_SESSION['AMZSP-GETORDERS-HISTORY'] = []; $res = $apiInstance->getOrders($marketplace_ids,$created_after, $created_before, $last_updated_after, $last_updated_before, $order_statuses, $fulfillment_channels, $payment_methods, $buyer_email, $seller_order_id, $max_results_per_page, $easy_ship_shipment_statuses, $electronic_invoice_statuses, $next_token, $amazon_order_ids, $actual_fulfillment_supply_source_id, $is_ispu, $store_chain_store_id, $data_elements); } $items = $res->getPayload()->getOrders(); foreach($items as $nr => $o){ foreach($o as $ok=>$ov){ switch($ok){ case 'seller_order_id': if($o->getOrderStatus() != 'Canceled'){ $q = xtc_db_query(sprintf( "SELECT orders_id FROM amazon_orders WHERE orig_amazon_orders_id='%s'", $o->getAmazonOrderId() )); if(xtc_db_num_rows($q)){ $record = xtc_db_fetch_array($q); $items[ $nr ][$ok] = sprintf('%s', $record['orders_id'], $record['orders_id'] ); } } break; } if(gettype($ov) == 'object'){ $class = get_class($ov); switch($class){ case 'SellingPartnerApi\Model\OrdersV0\Address': $parts = []; foreach($ov as $address_part => $address_value){ if( $address_value == 'null' or empty($address_value)){ continue; } $parts[] = $address_value; } $items[ $nr ][$ok] = implode(', ',$parts); break; case 'SellingPartnerApi\Model\OrdersV0\Money': $items[ $nr ][$ok] = $ov->getAmount().' '.$ov->getCurrencyCode(); break; case 'SellingPartnerApi\Model\OrdersV0\BuyerInfo': $items[ $nr ][$ok] = $ov->getBuyerEmail(); break; case 'SellingPartnerApi\Model\OrdersV0\AutomatedShippingSettings': $items[ $nr ][$ok] = $ov->getHasAutomatedShippingSettings(); break; break; default: die('YES Todo: Unbekannter Class Key im Result: '.$class); break; } }elseif(gettype($ov) == 'array'){ $items[ $nr ][$ok] = implode(', ',$ov); } } } $result = $res->getPayload(); if($result->getNextToken() != ''){ $smarty->assign('NEXT_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']).'NextToken='.urlencode($result->getNextToken()) )); } $page_no = 1; if(isset($_SESSION['AMZSP-GETORDERS-HISTORY']) and sizeOf($_SESSION['AMZSP-GETORDERS-HISTORY'])){ $last_nr = ''; foreach($_SESSION['AMZSP-GETORDERS-HISTORY'] as $nr => $last){ if($last == $_REQUEST['NextToken']){ $last_nr = $nr-1; $page_no = $nr+2; } } if($last_nr < 0){ $smarty->assign('LAST_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']) )); }else{ $smarty->assign('LAST_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']).'NextToken='.urlencode($_SESSION['AMZSP-GETORDERS-HISTORY'][$last_nr]) )); } } $smarty->assign([ 'action'=>$action, 'items'=>$items, 'PAGE_INFO'=>sprintf(TEXT_AMAZON_GETORDERS_PAGING, $page_no, xtc_date_short($created_after), $max_results_per_page, ), ]); }catch( Exception $e){ die('Fehler: '.$e->getMessage()); } break; case 'update_refresh_token': $current_seller = $_GET['selling_partner_id']; $ASP = new amazon_sp($current_seller); $apiInstance = new SellingPartnerApi\Api\TokensV20210301Api($ASP->configObj); $old_refresh_token = ''; foreach($ASP->auth_params->users as $u){ if($u->selling_partner_id == $current_seller){ $old_refresh_token = $u->refresh_token; } } if(empty($old_refresh_token)){ die('YES Error: Refresh Token fuer Seller '.$current_seller.' not found.'); } try { $client = new GuzzleHttp\Client(); $res = null; try { $res = $client->post("https://api.amazon.com/auth/o2/token", [ GuzzleHttp\RequestOptions::JSON => [ "grant_type" => "refresh_token", "refresh_token" => $old_refresh_token, "client_id" => $ASP::AMAZON_SP_LWACLIENTID, 'client_secret' => $ASP::AMAZON_SP_LWACLIENTSECRET, ], ]); } catch (GuzzleHttp\Exception\ClientException $e) { $info = json_decode($e->getResponse()->getBody()->getContents(), true); if ($info["error"] === "invalid_grant") { yes_debug($info); } else { throw $e; } } $body = $res->getBody()->getContents(); $body = json_decode($body); $c = file_get_contents( main::get_secure_path().'AMAZON_SP_AUTH.json'); $json = json_decode($c); $json->users->$current_seller->auth = $body; $ASP->write_file(json_encode($json,JSON_PRETTY_PRINT), main::get_secure_path().'AMAZON_SP_AUTH.json'); $messageStack->add_session('Refresh Token for Seller '.$current_seller.' updated','success'); xtc_redirect(xtc_href_link('amazon.php')); }catch( Exception $e){ echo $e->getMessage(); } exit; break; case 'importOrderReport': $items = []; $selling_partner_id = $_POST['selling_partner_id']; if($_FILES['csv']['error'] == 0){ $name = $_FILES['csv']['name']; $ext = strtolower(end(explode('.', $_FILES['csv']['name']))); $type = $_FILES['csv']['type']; $tmpName = $_FILES['csv']['tmp_name']; // check the file is a csv if(($handle = fopen($tmpName, 'r')) !== FALSE) { // necessary if a large csv file set_time_limit(0); while(($data = fgetcsv($handle, 3000, "\t")) !== FALSE) { $items[] = $data; } fclose($handle); } $messageStack->add_session(MSG_SUCCESS_CSV_FILE_UPLOAD,'success'); }else{ $messageStack->add_session(MSG_ERROR_CSV_FILE_UPLOAD,'error'); } if(sizeOf($items)){ $orders_created_array = []; $R = new Report; $amazon_values = $R->prepareCSVData( 'ORDERREPORT_CSV', $items,$selling_partner_id ); foreach($amazon_values as $order){ if($R->is_order_processed($order)){ // printf(" Amazon Order %s existiert.\r\n",$order['order_id']); }else{ // printf(" Amazon Order %s noch nicht importiert.\r\n",$order['order_id']); $orders_created_array = array_merge($orders_created_array,$R->import_order($order,true)); } } $messageStack->add_session(sprintf(MSG_SUCCESS_AMAZON_CSV_ORDERIMPORT, sizeOf($orders_created_array)),'success'); } xtc_redirect(xtc_href_link('amazon.php')); break; case 'edit_schedule': $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); if(isset($_GET['delete']) and $_GET['delete'] == 1){ try{ $result = $apiInstance->cancelReportSchedule($_GET['id']); $messageStack->add_session(sprintf(MSG_SUCCESS_SCHEDULE_DELETE, $_GET['id']),'success'); }catch(Exception $e){ $messageStack->add_session(sprintf(MSG_ERROR_SCHEDULE_DELETE, $_GET['id'], $e->getMessage()),'error'); } xtc_redirect(xtc_href_link('amazon.php')); } $result = $apiInstance->getReportSchedule($_GET['id']); $m_text = implode(',',$result->getMarketplaceIds()); foreach(amazon_sp::AMAZON_SP_MARKETPLACES as $m){ if($m['id'] == current($result->getMarketplaceIds())){ $m_text = $m['country']; } } printf('

Report Automation #%s

' . '' . '' . '' . '
Typ:%s
Marktplätze:%s
Interval:%s Tage
Nächste Generierung:%s
', $result->getReportScheduleId(), $result->getReportType(), $m_text, str_replace(['P','D'],'',$result->getPeriod()), $result->getNextReportCreationTime() ); printf('', xtc_href_link('amazon.php',xtc_get_all_get_params(array('delete')).'delete=1'), IMAGE_DELETE ); exit; break; case 'add_schedule': if(isset($_GET['schedule_duration'])){ $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); switch($_GET['schedule_duration']){ case '1': $period = 'P1D'; break; case '3': $period = 'P3D'; break; default: $period = 'P7D'; break; } $markets = array_slice($ASP->get_active_marketplaces(),0,10); foreach($markets as $market){ try { $body = new SellingPartnerApi\Model\ReportsV20210630\CreateReportScheduleSpecification; $body->setMarketplaceIds([$market]); $body->setPeriod($period); $body->setReportType($_GET['type']); $result = $apiInstance->createReportSchedule($body); $messageStack->add_session(sprintf(MSG_SUCCESS_SCHEDULE_ADDED, $market, $period, $_GET['type']),'success'); } catch (Exception $e) { $messageStack->add_session(sprintf('Exception when calling ReportsV20210630Api->createReportSchedule: %s', $e->getMessage()),'error'); } } xtc_redirect(xtc_href_link('amazon.php')); } $select_options = [ ['id'=>'1','text'=>TEXT_SCHEDULE_1_DAY], ['id'=>'3','text'=>TEXT_SCHEDULE_3_DAYS], ['id'=>'7','text'=>TEXT_SCHEDULE_1_WEEK], ]; $script = << $(function(){ $('button#add_schedule').on('click',function(){ $(this).hide(); let sType = $('select[name="ReportType"]').val(); window.location.href='amazon.php?action=add_schedule&type='+sType+'&schedule_duration='+$('select[name="schedule_duration"]').val(); }); }); ADD_SCHEDULE_SCRIPT; printf($script, $type); printf('

%s

',TEXT_ADD_SCHEDULE_INTRO); echo xtc_draw_pull_down_menu('ReportType',[ ['id'=>'GET_FLAT_FILE_OPEN_LISTINGS_DATA','text'=>'GET_FLAT_FILE_OPEN_LISTINGS_DATA'], ]); echo xtc_draw_pull_down_menu('schedule_duration',$select_options); printf(' ', IMAGE_SAVE ); echo '
'; exit; break; case 'marketplaceParticipations': printf('

Amazon Marktplatz Einstellungen Seller %s

', $current_seller ); $apiInstance = new SellersApi( $ASP->getSPAPI_config($current_seller) ); $result = $apiInstance->getMarketplaceParticipations(); $payload = $result->getPayload(); echo ''; foreach($payload as $MPO){ $m = $MPO->getMarketplace(); $p = $MPO->getParticipation(); printf("", $m->getName(), $m->getId(), $m->getDefaultCurrencyCode(), ($p->getIsParticipating() == 1) ? YES : NO, ($p->getHasSuspendedListings() == 1) ? NO : YES ); } echo '
MarktplatzMarktplatz IDWährungMarktplatz freigeschaltetEinstellen aktiv?
%s%s%s%s%s
'; echo yes_draw_href_button('Update Refresh-Token',xtc_href_link('amazon.php','action=update_refresh_token&selling_partner_id='.$current_seller),'padding: 4px;','button','ui-button ui-corner-all ui-state-default'); echo '
'; exit; break; case 'auth': // OBERSTER EINTRAG $appID = $ASP::AMAZON_SP_APPLICATION_ID; $endpoint = Endpoint::EU; if(isset($_GET['selling_partner_id']) and isset($_GET['spapi_auth_code'])){ if($_SESSION['spapi_auth_state'] != $_GET['state']){ die('YES: Access Violation - session auth state differs'); } $ASP->configObj = new SellingPartnerApi\Configuration([ "lwaClientId" => $ASP::AMAZON_SP_LWACLIENTID, "lwaClientSecret" => $ASP::AMAZON_SP_LWACLIENTSECRET, "lwaRefreshToken" => $LWA_refresh_token, "awsAccessKeyId" => $ASP::AMAZON_SP_awsAccessKeyId, "awsSecretAccessKey" => $ASP::AMAZON_SP_awsSecretAccessKey, // If you're not working in the North American marketplace, change // this to another endpoint from lib/Endpoint.php "endpoint" => SellingPartnerApi\Endpoint::EU, "roleArn" => $ASP::AMAZON_SP_roleArn, ]); $apiInstance = new SellingPartnerApi\Api\AuthorizationV1Api($ASP->configObj); //localhost/yes/admin/amazon.php?spId=A16I2ECK44VS83&spCode=ANLLOKBjEQMCSqvEkveb&action=auth try { $client = new GuzzleHttp\Client(); $res = null; try { $res = $client->post("https://api.amazon.com/auth/o2/token", [ GuzzleHttp\RequestOptions::JSON => [ "grant_type" => "authorization_code", "code" => $_GET['spapi_auth_code']/*$auth_code*/, "client_id" => $ASP::AMAZON_SP_LWACLIENTID, //"redirect_uri"=>'https://agri.abcde.biz/amazon_oauth_redirect.php', "client_secret" => $ASP::AMAZON_SP_LWACLIENTSECRET, // "version" => "beta", ], ]); } catch (GuzzleHttp\Exception\ClientException $e) { yes_mail_debug(print_r($e,true)); $info = json_decode($e->getResponse()->getBody()->getContents(), true); if ($info["error"] === "invalid_grant") { yes_debug($info); } else { throw $e; } } try{ $body = (string)$res->getBody(); }catch(Exception $em){ echo $em->getMessage(); yes_mail_debug('Fall 0:'.print_r($em,true)); } yes_mail_debug('BODY:'.print_r($body,true)); try{ $c = json_decode(file_get_contents(main::get_secure_path().'AMAZON_SP_AUTH.json')); foreach($c->users as $cu=>$cv){ if($cu == $_GET['selling_partner_id']){ $cv->auth = json_decode($body); } } }catch(Exception $ee){ echo $ee->getMessage(); yes_mail_debug('Fall 1:'.print_r($ee,true)); } try{ $ASP->write_file( json_encode( $c ),main::get_secure_path().'AMAZON_SP_AUTH.json'); }catch(Exception $eee){ echo $eee->getMessage(); yes_mail_debug('Fall 2:'.print_r($eee,true)); exit; } $messageStack->add_session('Amazon SP Authorisierung gespeichert','success'); xtc_redirect(xtc_href_link('amazon.php')); } catch (Exception $e) { echo 'Exception when calling AuthorizationV1Api->getAuthorizationCode: ', $e->getMessage(), PHP_EOL; } } if(isset($_GET['marketplaceId'])){ foreach($ASP::AMAZON_SP_MARKETPLACES as $m){ if($m['id'] == $_GET['marketplaceId']){ $state = bin2hex(random_bytes(256)); $_SESSION["spapi_auth_state"] = $state; $_SESSION["spapi_auth_time"] = time(); // $beta = '&version=beta'; $beta = ''; if(main::isDev(true)){ // $m['url'] = str_replace('https://sellingpartnerapi','https://sandbox.sellingpartnerapi',$m['url']); } // if(main::isDev()){ $redirect_uri = '&redirect_uri='.urlencode('https://yes-a177922.de/amazon_oauth_redirect.php'); // }else{ // $redirect_uri = '&redirect_uri='.urlencode(HTTPS_CATALOG_SERVER.'admin/amazon_oauth_redirect.php'); // } header('Location: '.$m['url'].'/apps/authorize/consent?application_id='.$appID.'&state='.$state.$beta); } } } $smarty->assign('action',$action); $auth = $ASP->getAuth_params(); $auth_array = []; $aktiv = false; // wenigstens 1 seller aktiv? // for($i=0;$iusers as $u_name=>$user){ if(($user_zaehler+1) > AMAZONUSER_COUNTER){ continue; } $u = $user->auth; if(gettype($u->LWA_refresh_token) != 'NULL' and isset($u->LWA_refresh_token) and $u->LWA_refresh_token != ''){ $auth_array[] = 'Marketplace ID '.$u->marketplace_id.'
'; $aktiv = true; }else{ $auth_array[] = ''; } $user_zaehler++; } $marketplaces = $ASP->get_marketplaces_for_selectbox(); $smarty->assign(['AUTH'=>$auth_array, 'aktiv'=>($aktiv === true)?1:0, 'AMAZONUSER_COUNTER'=>AMAZONUSER_COUNTER, 'MARKETPLACES_SELECT'=>xtc_draw_pull_down_menu('marketplace_id',$marketplaces) ]); break; case 'import_lagerbericht_delete': unlink($amazon_import_filename); $messageStack->add_session(MSG_SUCCESS_IMPORT_LAGERBERICHT_DELETED,'success'); xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action')))); break; case 'import_lagerbericht': if($_FILES['lagerbericht']['type'] != 'text/plain'){ $messageStack->add_session(MSG_ERROR_IMPORT_LAGERBERICHT_FORBIDDEN_TYPE,'error'); xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action')))); }else if( $_FILES['lagerbericht']['size'] < 1 ){ $messageStack->add_session(MSG_ERROR_IMPORT_LAGERBERICHT_FILESIZE,'error'); xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action')))); } if($importfile = xtc_try_upload('lagerbericht','importdata/','755','txt')){ copy($importfile->destination . '/' . $importfile->filename,$amazon_import_filename); unlink($importfile->destination . '/' . $importfile->filename); xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action')))); }else{ $messageStack->add_session(MSG_ERROR_IMPORT_LAGERBERICHT_IMPORT_ERROR,'error'); xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action')))); } exit; break; // ONLY FOR _GET_MERCHANT_LISTINGS_DATA_ case 'autoallocate_process': case 'auto_allocate': $R = new Report; $R->setReportType($_GET['ReportType']); if(isset($_REQUEST['from_file']) and $_REQUEST['from_file'] == '1' and is_file($amazon_import_filename)){ $service = $AS->get_service(); $R = new Report; $R->setReportType('_GET_MERCHANT_LISTINGS_DATA_'); $R->import_filename = $amazon_import_filename; $items = $R->invokeGetReport($service, $request,true); }else{ if(!isset($_REQUEST['reportId']) or empty($_REQUEST['reportId']) or !isset($_REQUEST['reportDocumentId']) or empty($_REQUEST['reportDocumentId']) ){ die('Missing parameter.'); } $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); $report_type = $_GET['ReportType']; $marketplaceIds = ["A1PA6795UKMFR9"]; try { $result = $apiInstance->getReportDocument($_REQUEST['reportDocumentId']); //die('RES:'.$result->getReportId()); } catch (Exception $e) { echo 'Exception when calling ReportsV20210630Api->getReports: ', $e->getMessage(), PHP_EOL; exit; } $items = $R->invokeGetReport($result, $current_seller); } $unallocated = array(); if(sizeOf($items)){ foreach($items as $item){ if($item['products_id'] < 0){ $unallocated[] = $item; } } } if($action == 'autoallocate_process'){ $allocateds = 0; foreach($unallocated as $un){ if(isset($_REQUEST['use_ebay_sku']) and $_REQUEST['use_ebay_sku'] == 1){ $query = xtc_db_query(sprintf( "SELECT products_id FROM ebay_products WHERE sku='%s'",$un['sku'] )); }else{ $query = xtc_db_query(sprintf( "SELECT products_id FROM products WHERE products_id='%s'",$un['sku'] )); } if(xtc_db_num_rows($query)){ if(isset($_REQUEST['use_ebay_sku']) and $_REQUEST['use_ebay_sku'] == 1){ $ep_pid_record = xtc_db_fetch_array($query); $insert_pID = $ep_pid_record['products_id']; $query = xtc_db_query(sprintf( "SELECT ap.products_id FROM amazon_products ap LEFT JOIN ebay_products ep USING(products_id) WHERE ep.sku='%s' AND ap.selling_partner_id='%s'",$un['sku'],$current_seller )); }else{ $query = xtc_db_query(sprintf( "SELECT products_id FROM amazon_products WHERE products_id='%s' AND selling_partner_id='%s'",$un['sku'],$current_seller )); $insert_pID = $un['sku']; } if(!xtc_db_num_rows($query)){ $insert_sql_array = array( 'products_id'=>$insert_pID, 'sku'=>$un['sku'], 'asin'=>$un['asin'], 'price'=>$un['price'], 'quantity'=>$un['qty'], 'selling_partner_id'=>$current_seller ); xtc_db_perform('amazon_products',$insert_sql_array); $insert_sql_array = array( 'products_id'=>$insert_pID, 'editor_id'=>$_SESSION['customer_id'], 'date_saved'=>'now()', 'comments'=>'Amazon Automatik Zuweisung' ); xtc_db_perform('products_history',$insert_sql_array); $allocateds++; } } } $messageStack->add_session(sprintf(MSG_AUTOALLOCATE_SUCCESS,$allocateds),'success'); xtc_redirect(xtc_href_link('amazon.php')); exit; }else{ header('Content-Type: text/html; charset='.CHARSET); if(sizeOf($unallocated)){ echo '

'.TEXT_AUTOALLOCATE_INTRO.'

'; if(defined('AMAZON_AUTOALLOCATE_USE_EBAY_PRODUCTS_SKU') and AMAZON_AUTOALLOCATE_USE_EBAY_PRODUCTS_SKU == 'True'){ echo ''; }else{ echo ''; } echo ''; echo ''; echo ''; echo ''; echo ''; foreach($unallocated as $un){ printf('', $un['sku'],$un['name'],$un['asin'],number_format($un['price'],2,',','.'),$un['qty'] ); } echo ''; echo '
SKUNameASINPreis'.TEXT_QUANTITY.'
%s%s%s%s%s
'; }else{ echo '

'.TEXT_NO_SYNC_PRODUCTS.'

'; } } exit; break; case 'allocate_orders_products': require_once(DIR_FS_INC.'yes_end_auction_add.inc.php'); $pID = (int)xtc_db_input($_REQUEST['products_id']); $aoic = xtc_db_input($_REQUEST['amazon_order_item_code']); $sku = xtc_db_input($_REQUEST['sku']); if($pID < 1 or empty($aoic) or empty($sku)){ die(json_encode(array( 'ERROR'=>'Missing Parameters' ))); } $exists_query = xtc_db_query(sprintf( "SELECT products_id FROM products WHERE products_id='%d'", $pID )); if(!xtc_db_num_rows($exists_query)){ die(json_encode(array( 'ERROR'=>sprintf(MSG_ERROR_PRODUCT_NOT_EXISTS,$pID) ))); } $product = new product($pID); // ALS ERSTES IN DER AMAZON_PRODUCTS UPDATEN $query = xtc_db_query(sprintf( "SELECT amazon_products_id FROM amazon_products WHERE products_id=%s", $pID )); if(xtc_db_num_rows($query)){ echo "Dieser Amazon Artikel hat bereits eine Zuweisung zum YES Artikel\r\n"; $record = xtc_db_fetch_array($query); $amazon_products_id = $record['amazon_products_id']; }else{ // merchant_id fehlt(e) hier - 2020-02-03 $merchant_query = xtc_db_query(sprintf( "SELECT ao.selling_partner_id FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE aop.amazon_order_item_code='%s'", $aoic )); $merchant_result = xtc_db_fetch_array($merchant_query); $insert_sql_array = array( 'products_id'=>$pID, 'sku'=>$sku, 'selling_partner_id'=>$merchant_result['selling_partner_id'] ); xtc_db_perform('amazon_products',$insert_sql_array); $product->add_history(sprintf( 'Artikel wurde der Amazon SKU %s zugewiesen.',$sku )); } $tax_class_id = $product->info['products_tax_class_id']; // EU-OSS SAFE $tax_rate = xtc_get_tax_rate($tax_class_id); // NUN ALLE ORDERS DIE DIESEN UNZUGEWIESENEN ARTIKEL ENTHALTEN UPDATEN $query = xtc_db_query(sprintf( "SELECT orders_products_id,products_tax,orders_id,products_quantity FROM orders_products WHERE amazon_sku='%s' AND products_id <= 0", $sku )); $allocated_orders = 0; while($record = xtc_db_fetch_array($query)){ $update_sql_array = array( 'products_id'=>$pID, 'products_model'=>$product->info['products_model'], 'products_tax'=>$tax_rate ); if(defined('MODULE_OTHER_AMAZON_PRODUCTS_NAME_FROM_AMAZON') and MODULE_OTHER_AMAZON_PRODUCTS_NAME_FROM_AMAZON != 'True'){ $update_sql_array['products_name'] = xtc_get_products_name($pID); } xtc_db_perform('orders_products',$update_sql_array,"update",'orders_products_id='.$record['orders_products_id']); yes_end_auction_add($pID, $record['products_quantity']); $order = new order($record['orders_id']); // EU-OSS $country_id = $order->delivery['country_id']; $zone_id = $order->delivery['zone_id']; // BOF - BUGF_CH_OSS - BLOCK UEBERFLUESSIG WENN AKTIV //if(!yes_eu_oss_use_country_handling($country_id)){ // $country_id = STORE_COUNTRY; // $zone_id = 0; //} // EOF - BUGF_CH_OSS - BLOCK UEBERFLUESSIG WENN AKTIV // BOF - Neuberechnung MWST Versand - Ticket 1620 if(number_format($record['products_tax'],2,'.','') != number_format($tax_rate,2,'.','')){ $shipping_tax = $order->get_shipping_tax_class(); $update_sql_array = array( 'tax_rate_percent'=>xtc_get_tax_rate($shipping_tax,$country_id, $zone_id) ); xtc_db_perform(TABLE_ORDERS_TOTAL,$update_sql_array,'update',"orders_id='".$record['orders_id']."' AND class='ot_shipping'"); $order = new order($record['orders_id']); $order->recalc(); } // EOF - Neuberechnung MWST Versand - Ticket 1620 $order->add_history($order->info['orders_status'], 0, sprintf('Der unbekannte Amazon Artikel %s (pID %s) wurde zugewiesen.', $product->info['products_name'],$pID )); $allocated_orders++; } die('Es wurden '.$allocated_orders.' Artikel in Amazon-Bestellungen aktualisiert und die Amazon Zuweisung gespeichert.'); break; case 'allocate_orders_products_select': $orders_id = xtc_db_input($_REQUEST['orders_id']); $products = array(); $query = xtc_db_query(sprintf( "SELECT amazon_order_item_code,products_name,products_price,products_quantity FROM orders_products WHERE orders_id=%s AND products_id<=0", $orders_id )); while($record = xtc_db_fetch_array($query)){ $sku_query = xtc_db_query(sprintf( "SELECT aop.sku FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE ao.orders_id=%s", $orders_id )); $sku_record = xtc_db_fetch_array($sku_query); $record['sku'] = $sku_record['sku']; $products[] = $record; } $smarty->assign(array( 'ORDERS_ID'=>$_REQUEST['orders_id'], 'PRODUCTS'=>$products, 'TEXT_ALLOCATE_ORDERS_PRODUCTS_NO_SEARCH_RESULTS'=>TEXT_ALLOCATE_ORDERS_PRODUCTS_NO_SEARCH_RESULTS, 'TEXT_ALLOCATE_ORDERS_PRODUCTS_SEARCH_RESULTS'=>TEXT_ALLOCATE_ORDERS_PRODUCTS_SEARCH_RESULTS, 'TEXT_ALLOCATE_ORDERS_PRODUCTS_ORDER'=>TEXT_ALLOCATE_ORDERS_PRODUCTS_ORDER, 'TEXT_ALLOCATE_ORDERS_PRODUCTS_ORDER_FAILED'=>TEXT_ALLOCATE_ORDERS_PRODUCTS_ORDER_FAILED )); $smarty->display('amazon_allocate_orders_products.html'); exit; break; case 'delete_allocation': if(!isset($_REQUEST['pID'])){ die(json_encode(array( 'error'=>'Missing Parameter' ))); } $pID = (int)$_REQUEST['pID']; xtc_db_query(sprintf("DELETE FROM amazon_products WHERE products_id='%s'", $pID )); $product = new product($pID); $product->add_history(sprintf( MSG_AMAZON_ALLOCATION_DELETE )); die(json_encode(array( 'html'=>MSG_AMAZON_ALLOCATION_DELETE ))); break; case 'order_fulfillments': $items = array(); // BOF - TICKET 417 require (DIR_FS_INC . 'yes_get_sha1_from_string.inc.php'); $codes = array(); $import_dir_array = array(); for($i=0;$i<14;$i++){ $import_dir_array[] = yes_get_sha1_from_string( date('Y-m-d',(time()-(60*60*24*$i)) ) ); } foreach($import_dir_array as $dir){ if(!is_dir('exportdata/'.$dir)){ continue; } $files = $basics->get_directory_content('exportdata/'.$dir.'/'); foreach($files as $file){ if(!stristr($file,'VERSANDCODES')){ continue; } $content = $basics->read_file_content('exportdata/'.$dir.'/'.$file); $lines = explode("\n",$content); foreach($lines as $nr => $line){ if($nr == 0) continue; $parts = explode("\t",$line); if(!stristr($parts[0],'R') and $parts[0] != ''){ $is_combined_query = xtc_db_query(sprintf( "SELECT orders_id FROM orders WHERE combined_orders_id=%s", (int)str_replace('"','',$parts[0]) )); if(xtc_db_num_rows($is_combined_query)){ while($combined = xtc_db_fetch_array($is_combined_query)){ $codes['o'.$combined['orders_id']] = str_replace('"','',$parts[1]); } }else{ $codes['o'.str_replace('"','',$parts[0])] = str_replace('"','',$parts[1]); } } } } } // EOF - TICKET 417 $max_items = (isset($_REQUEST['max_items']) and $_REQUEST['max_items'] > 0 and $_REQUEST['max_items'] < 50) ? (int)xtc_db_input($_REQUEST['max_items']) : 50; $query = yes_db_query( "SELECT aop.*,ao.orders_id,ao.orig_amazon_orders_id FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE yes_shipping_status=1 AND order_fulfillment_send=0" ); $total = yes_db_num_rows($query); if($total > 0){ $collected_entries = array(); foreach($query as $record){ $collected_entries[] = $record; // BOF - KOMBINIERTE AMAZON BESTELLUNGEN $combined_check_query = xtc_db_query(sprintf( "SELECT amazon_orders_id FROM amazon_orders WHERE orig_amazon_orders_id='%s' AND amazon_orders_id!='%d'", $record['orig_amazon_orders_id'], $record['amazon_orders_id'] )); $combined_addons = array(); if(xtc_db_num_rows($combined_check_query)){ while($combined_check = xtc_db_fetch_array($combined_check_query)){ $combined_addons[] = $combined_check['amazon_orders_id']; } } foreach($combined_addons as $amazon_orders_id){ $add_query = yes_db_query(sprintf( "SELECT aop.*,ao.orders_id,ao.orig_amazon_orders_id FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE order_fulfillment_send=0 AND ao.amazon_orders_id='%d'", $amazon_orders_id )); while($add = xtc_db_fetch_array($add_query)){ $add['is_combined'] = true; $collected_entries[] = $add; } } // EOF - KOMBINIERTE AMAZON BESTELLUNGEN } $counter = 0; foreach($collected_entries as $record){ if($counter > $max_items) break; $record['products_id'] = yes_get_products_id_from_amazon_sku($record['sku'],$record['selling_partner_id']); $record['shipper_tracking_number_value'] = ''; if(isset($codes['o'.$record['orders_id']])){ $record['shipper_tracking_number_value'] = $codes['o'.$record['orders_id']]; }else{ // ticket 1277 vom 16.09.14 // alle trackingids zum auftrag $tracking_query = xtc_db_query(sprintf( "SELECT id,tracking_id FROM shippings WHERE orders_id='%s' ORDER BY date_added DESC", $record['orders_id'] )); if(xtc_db_num_rows($tracking_query)){ $tr_counter = 0; $tracking_numbers = array(); // BOF - VERALTETES HANDLING - DENKE KANN AB ANFANG 2015 ausgebaut werden while($tracking = xtc_db_fetch_array($tracking_query)){ if($tracking['tracking_id'] != ''){ $tracking_numbers[] = $tracking['tracking_id']; }else{ if($tr_counter == 0){ // NUR DEN LETZTEN shippings EINTRAG $YS = new yes_shipping($tracking['id']); $tracking_numbers = $YS->getTracking_id_array(); } } $tr_counter++; } // EOF - VERALTETES HANDLING - DENKE KANN AB ANFANG 2015 ausgebaut werden $record['shipper_tracking_number_value'] = implode(' + ',$tracking_numbers); } } if($counter < $max_items) $items[] = $record; // KOMBINIERTE DUERFEN NICHT GETRENNT WERDEN if(!isset($record['is_combined'])){ $counter++; } } } $amazon_form_id = 'order_ff'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=send_order_fulfillment_xslx','post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $smarty->assign('action',$action); $smarty->assign('items',$items); $smarty->assign(array( 'HEADING_TITLE'=>sprintf(HEADING_TITLE_FULFILLMENTS,sizeOf($items),$total) )); break; case 'send_order_fulfillment': //// // // --------------------------------------------- // ACHTUNG - HIER BEACHTEN DASS ES UNTERSCHIEDLICHE MERCHANT IDs GIBT // NOCH NICHT INTEGRIERT!!! // --------------------------------------------- // //// $one_click = (isset($_GET['one_click']) and $_GET['one_click'] == 1) ? true : false; $one_click_feed_submissions = array(); // VERSANDABSCHLUSS WIRD AN AMAZON GEMELDET if(!isset($_REQUEST['amazon_order_item_code']) or !sizeOf($_REQUEST['amazon_order_item_code'])){ if(!$one_click){ $messageStack->add_session(MSG_ERROR_NO_ORDERS_TO_FULFILLMENT,'error'); xtc_redirect(xtc_href_link('amazon.php')); }else{ die(json_encode(array( 'MESSAGES'=>array(MSG_ERROR_NO_ORDERS_TO_FULFILLMENT) ))); } } $fulfillments = array(); $SF = new SubmitFeed(); foreach($_REQUEST['amazon_order_item_code'] as $item_code){ $query = yes_db_query(sprintf( "SELECT ao.orders_id,ao.orig_amazon_orders_id,ao.selling_partner_id,aop.* FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE aop.yes_shipping_status=1 AND aop.order_fulfillment_send=0 and amazon_order_item_code='%s' ORDER BY ao.selling_partner_id", xtc_db_input($item_code) )); if(!yes_db_num_rows($query)){ // BOF - KOMBINIERTE AMAZON BESTELLUNGEN $combined1_query = xtc_db_query(sprintf( "SELECT ao.orig_amazon_orders_id,ao.amazon_orders_id FROM amazon_orders_products aop LEFT JOIN amazon_orders ao USING(amazon_orders_id) WHERE amazon_order_item_code='%s'", xtc_db_input($item_code) )); $combined1 = xtc_db_fetch_array($combined1_query); $combined_check_query = xtc_db_query(sprintf( "SELECT ao.amazon_orders_id FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE orig_amazon_orders_id='%s' AND ao.amazon_orders_id!='%d' AND aop.order_fulfillment_send=0", $combined1['orig_amazon_orders_id'], $combined1['amazon_orders_id'] )); if(!xtc_db_num_rows($combined_check_query)){ continue; } $query = yes_db_query(sprintf( "SELECT ao.orders_id,ao.orig_amazon_orders_id,ao.selling_partner_id,aop.* FROM amazon_orders ao LEFT JOIN amazon_orders_products aop USING(amazon_orders_id) WHERE aop.order_fulfillment_send=0 and amazon_order_item_code='%s' ORDER BY ao.selling_partner_id", xtc_db_input($item_code) )); } // UPDATE DER SHIPPER TRACKING NUMBER if(isset($_REQUEST['shipper_tracking_number'][$item_code])){ $update_sql_array = array( 'shipper_tracking_number'=>$_REQUEST['shipper_tracking_number'][$item_code] ); xtc_db_perform('amazon_orders_products',$update_sql_array,'update', sprintf("amazon_order_item_code='%s'", $_REQUEST['shipper_tracking_number'][$item_code] ) ); } $record = current($query); // BEI KOMBINIERTEN WERDEN DIE items HINZUGEFUEGT $exists = -1; if(isset($fulfillments[$record['selling_partner_id']])){ foreach($fulfillments[$record['selling_partner_id']] as $_k=>$_f){ if($_f['amazon_orders_id'] == $record['orig_amazon_orders_id']){ $exists = $_k; } } } $fulfill_item = array( 'amazon_order_item_code'=>$record['amazon_order_item_code'], 'selling_partner_id'=>$record['selling_partner_id'], 'quantity'=>$record['quantity'], 'merchant_fulfillment_item_id'=>$record['shippings_id'], 'shipper_tracking_number'=>((isset($_REQUEST['shipper_tracking_number'][$item_code]) ) ? $_REQUEST['shipper_tracking_number'][$item_code] : '') ); if($exists > -1){ $fulfillments[ $record['selling_partner_id'] ][$exists]['items'][] = $fulfill_item; }else{ $order = new order($record['orders_id']); $order->add_history($order->info['orders_status'],false,'amazon fulfillment sent'); $fulfillment = array(); $fulfillment['merchant_orders_id'] = $order->info['id']; $fulfillment['amazon_orders_id'] = $record['orig_amazon_orders_id']; $fulfillment['shipping_method_service_level'] = $A->get_amazon_shipping_method_name($record['shipping_method']); if($record['carrier_code'] != 'Other' and $record['carrier_code'] != ''){ $fulfillment['carrier_code'] = $record['carrier_code']; }else{ $fulfillment['carrier_name'] = $record['carrier_name']; } if(isset($_REQUEST['shipper_tracking_number'][$item_code])){ $fulfillment['shipper_tracking_number'] = $_REQUEST['shipper_tracking_number'][$item_code]; } // KANN WEG, NACHSCHAUEN WELCHER carrier AN AMAZON GESENDET WIRD // TICKET 3404, 06-2023 yes_mail_debug(sprintf( "Auftrag %d, Service Level %s, Carrier Code %s, TrackingNr %s", $record['orders_id'], $fulfillment['shipping_method_service_level'], $fulfillment['carrier_code'], $fulfillment['shipper_tracking_number'] )."\r\n\r\nREQUEST:\r\n\r\n".print_r($_REQUEST,true)); $fulfillment['items'][] = $fulfill_item; if(!isset($fulfillments[$record['selling_partner_id']])) $fulfillments[$record['selling_partner_id']] = array(); $fulfillments[$record['selling_partner_id']][] = $fulfillment; } } foreach($fulfillments as $mercID=>$fulf){ $auth_params = $A->get_auth_data_array($mercID); $xml = $SF->get_order_fulfillment_feed($fulf); $FeedType = '_POST_ORDER_FULFILLMENT_DATA_'; $service = $AS->get_service(); $feed = $xml->asXML(); $feedHandle = @fopen('php://memory', 'rw+'); fwrite($feedHandle, $feed); rewind($feedHandle); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'FeedType' => $FeedType, 'FeedContent' => $feedHandle, 'PurgeAndReplace' => false, 'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)) ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters); $result = $SF->invokeSubmitFeed($service, $request); fclose($feedHandle); $insert_sql_array = array( 'feed_submission_id'=>$result->getFeedSubmissionId(), 'feed_type'=>$result->getFeedType(), 'feed_processing_status'=>$result->getFeedProcessingStatus(), 'submitted_date'=>'now()', 'selling_partner_id'=>$auth_params['selling_partner_id'] ); xtc_db_perform( 'amazon_feeds',$insert_sql_array ); $amazon_feeds_id = xtc_db_insert_id(); $_orders = array(); foreach($_REQUEST['amazon_order_item_code'] as $item_code){ $insert_sql_array = array( 'amazon_feeds_id'=>$amazon_feeds_id, 'amazon_order_item_code'=>$item_code ); xtc_db_perform( 'amazon_feeds_order_fulfillments',$insert_sql_array ); } if(!$one_click){ die($result->getFeedSubmissionId()); }else{ $one_click_feed_submissions[] = $result->getFeedSubmissionId(); } } // end foreach fulfillments if($one_click){ die(json_encode(array( 'FEED_SUBMISSION_ID_ARRAY'=>$one_click_feed_submissions, 'MESSAGES'=>array('Amazon Fulfillment: '.sizeOf($one_click_feed_submissions).' Feed Submission ID generated') ))); } break; case 'process_order_feed': if(!isset($_REQUEST['reportId']) or !isset($_REQUEST['ReportType']) ){ die('Missing parameter for processing order'); } $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'Report' => @fopen('php://memory', 'rw+'), 'ReportId' => $_REQUEST['reportId'] ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $service = $AS->get_service(); $R = new Report; $R->setReportType($_REQUEST['ReportType']); $request = new MarketplaceWebService_Model_GetReportRequest($parameters); $items = $R->invokeGetReport($service, $request); $orders_created_array = array(); foreach($items as $order){ if($R->is_order_processed($order)){ $messageStack->add_session(sprintf( MSG_ERROR_PROCESS_ORDER_EXISTS,$order['order_id'] )); } $orders_created_array = array_merge($orders_created_array,$R->import_order($order)); } if(sizeOf($orders_created_array)){ // BESTELLBESTAETIGUNG AN AMAZON $SF = new SubmitFeed(); $feed = $SF->getOrderAcknowledgementFeed($orders_created_array); $FeedType = '_POST_ORDER_ACKNOWLEDGEMENT_DATA_'; $service = $AS->get_service(); $feed = $feed->asXML(); $feedHandle = @fopen('php://memory', 'rw+'); fwrite($feedHandle, $feed); rewind($feedHandle); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'FeedType' => $FeedType, 'FeedContent' => $feedHandle, 'PurgeAndReplace' => false, 'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)) ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters); $result = $SF->invokeSubmitFeed($service, $request); fclose($feedHandle); $_orders = array(); foreach($orders_created_array as $_order){ $_orders[] = $_order['merchant_orders_id']; } $messageStack->add_session(sprintf(MSG_SUCCESS_AMAZON_ORDER_FEED_IMPORTED,implode(', ',$_orders)),'success'); }else $messageStack->add_session(MSG_ERROR_AMAZON_ORDER_NOT_IMPORTED,'error'); xtc_redirect(xtc_href_link('amazon.php')); exit; break; case 'process_order': if(!isset($_REQUEST['amazon_order_id']) or !isset($_REQUEST['reportId']) or !isset($_REQUEST['ReportType']) ){ die('Missing parameter for processing order'); } $aoID = xtc_db_input($_REQUEST['amazon_order_id']); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'Report' => @fopen('php://memory', 'rw+'), 'ReportId' => $_REQUEST['reportId'] ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $service = $AS->get_service(); $R = new Report; $R->setReportType($_REQUEST['ReportType']); $request = new MarketplaceWebService_Model_GetReportRequest($parameters); $items = $R->invokeGetReport($service, $request); foreach($items as $order){ if($order['order_id'] != $_REQUEST['amazon_order_id']){ continue; } if($R->is_order_processed($order)){ $messageStack->add_session(sprintf( MSG_ERROR_PROCESS_ORDER_EXISTS,$order['order_id'] )); } $orders_created_array = $R->import_order($order); if(sizeOf($orders_created_array)){ // BESTELLBESTAETIGUNG AN AMAZON $SF = new SubmitFeed(); $feed = $SF->getOrderAcknowledgementFeed($orders_created_array); $FeedType = '_POST_ORDER_ACKNOWLEDGEMENT_DATA_'; $service = $AS->get_service(); $feed = $feed->asXML(); $feedHandle = @fopen('php://memory', 'rw+'); fwrite($feedHandle, $feed); rewind($feedHandle); // auth_oarams wurden ja oben schon gesetzt $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'FeedType' => $FeedType, 'FeedContent' => $feedHandle, 'PurgeAndReplace' => false, 'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)) ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters); $result = $SF->invokeSubmitFeed($service, $request); fclose($feedHandle); // BOF MAILVERSAND $lang_query = xtc_db_query(sprintf( "SELECT languages_id,directory FROM languages WHERE code='%s'", DEFAULT_LANGUAGE )); $lang = xtc_db_fetch_array($lang_query); if( is_file(DIR_FS_CATALOG.'templates/'.CURRENT_TEMPLATE.'/mail/'.$lang['directory'].'/order_amazon_mail.html') and is_file(DIR_FS_CATALOG.'templates/'.CURRENT_TEMPLATE.'/mail/'.$lang['directory'].'/order_amazon_mail.txt') ){ foreach($orders_created_array as $order){ $mail_com = sprintf(" Amazon Order %s - YES Order %s\r\n",$order['amazon_orders_id'],$order['merchant_orders_id']); $smarty = new yesSmarty; $smarty->compile_dir=DIR_FS_CATALOG.'templates_c'; $smarty->secure_dir = array(DIR_FS_CATALOG.'templates/'); $insert_id = $order['merchant_orders_id']; $amazon_orders_id = $order['amazon_orders_id']; $languages_id = $lang['languages_id']; // mail('m.aspeleiter@yes-websolutions.de','amazon send order #'.$insert_id,HTTP_SERVER."\r\nAMZ ORDER ".$amazon_orders_id."\r\n".$mail_com); include(DIR_FS_CATALOG.'amazon_send_order.php'); } } // EOF MAILVERSAND $_orders = array(); foreach($orders_created_array as $_order){ $_orders[] = $_order['merchant_orders_id']; } $messageStack->add_session(sprintf(MSG_SUCCESS_AMAZON_ORDER_IMPORTED,implode(', ',$_orders)),'success'); }else $messageStack->add_session(MSG_ERROR_AMAZON_ORDER_NOT_IMPORTED,'error'); } xtc_redirect(xtc_href_link('amazon.php')); exit; break; case 'update_schedule': if(!isset($_REQUEST['ReportType']) or !isset($_REQUEST['Schedule'])){ die('Missing params to update schedule'); } $service = $AS->get_service(); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'ReportType'=>$_REQUEST['ReportType'], 'Schedule'=>$_REQUEST['Schedule'] ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $R = new Report; $request = new MarketplaceWebService_Model_ManageReportScheduleRequest($parameters); $response = $service->ManageReportSchedule($request); $messageStack->add_session( sprintf(MSG_SUCCESS_AMAZON_UPDATE_SCHEDULE, $R->getReportTypeTitle($_REQUEST['ReportType']), $_REQUEST['Schedule']), 'success' ); xtc_redirect(xtc_href_link('amazon.php')); exit; break; case 'delete_todo': if(!isset($_REQUEST['todo']) or !is_array($_REQUEST['todo'])){ die('Missing parameters to delete.'); } $feed_array = array(); // UPDATEREPORTACK foreach($_REQUEST['todo'] as $amazon_feeds_id){ $amazon_feeds_id = xtc_db_input($amazon_feeds_id); $feed_submission_id_query = xtc_db_query(sprintf( "SELECT feed_submission_id FROM amazon_feeds WHERE amazon_feeds_id='%s' AND selling_partner_id='%s'", $amazon_feeds_id,$current_seller )); if(xtc_db_num_rows($feed_submission_id_query)){ $feed_submission_id_record = xtc_db_fetch_array($feed_submission_id_query); $feed_array[] = $feed_submission_id_record['feed_submission_id']; } xtc_db_query(sprintf( "DELETE FROM amazon_feeds WHERE amazon_feeds_id='%s'", $amazon_feeds_id )); xtc_db_query(sprintf( "DELETE FROM amazon_feeds_price_items WHERE amazon_feeds_id='%s'", $amazon_feeds_id )); xtc_db_query(sprintf( "DELETE FROM amazon_feeds_quantity_items WHERE amazon_feeds_id='%s'", $amazon_feeds_id )); } if(sizeOf($feed_array)){ $service = $AS->get_service(); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'FeedSubmissionIdList' => array ('Id' => $feed_array) ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_CancelFeedSubmissionsRequest($parameters); $response = $service->cancelFeedSubmissions($request); } $messageStack->add_session(sprintf(MSG_SUCCESS_DELETE_TODO,sizeOf($_REQUEST['todo'])),'success'); xtc_redirect(xtc_href_link('amazon.php')); exit; break; case 'todo_list': $items = array(); $query = xtc_db_query(sprintf( "SELECT * FROM amazon_feeds WHERE selling_partner_id='%s' ORDER BY submitted_date", $auth_params['merchant_id'] )); while($record = xtc_db_fetch_array($query)){ $items[] = $record; } $amazon_form_id = 'todo_delete'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=delete_todo','post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $smarty->assign('action',$action); $smarty->assign('items',$items); break; case 'allocate': $pID = xtc_db_input( $_REQUEST['pID'] ); $sku = xtc_db_input( $_REQUEST['sku'] ); $asin = xtc_db_input( $_REQUEST['asin']); if($pID < 1 or ($sku == '' and $asin == '')){ die(json_encode(array( 'html'=>'Missing Parameter', 'error'=>1 ))); } $query = xtc_db_query(sprintf( "SELECT products_id FROM products WHERE products_id='%d'", $pID )); if(!xtc_db_num_rows($query)){ die(json_encode(array( 'html'=>sprintf(MSG_ERROR_PRODUCT_NOT_EXISTS,$pID), 'error'=>1 ))); } $asin = xtc_db_input( $_REQUEST['asin'] ); $reportId = xtc_db_input( $_REQUEST['reportId'] ); $ReportType = xtc_db_input( $_REQUEST['ReportType'] ); $from = xtc_db_input( $_REQUEST['from'] ); $check_query = xtc_db_query(sprintf( "SELECT amazon_products_id FROM amazon_products WHERE (products_id='%s' or sku='%s') and selling_partner_id='%s'", $pID,$sku,$_SESSION['current_amazon_selling_partner_id'] )); if(xtc_db_num_rows($check_query)){ die(json_encode(array( 'html'=>MSG_ERROR_AMAZON_ALLOCATION, 'error'=>1 ))); } $qty = (int)xtc_db_input($_REQUEST['qty']); $price = (float)xtc_db_input($_REQUEST['price']); $insert_sql_array = array( 'products_id'=>$pID, 'sku'=>$sku, 'asin'=>$asin, 'quantity'=>$qty, 'price'=>$price, 'selling_partner_id'=>$_SESSION['current_amazon_selling_partner_id'], ); xtc_db_perform('amazon_products',$insert_sql_array); $product = new product($pID); $product->add_history(sprintf(HISTORY_AMAZON_ADDED,$sku)); $SQ = new products_quantity($pID); $collies = xtc_get_product_collies($pID); if(sizeOf($collies)>0){ $qty_available = xtc_get_product_collie_qty($pID); }else{ $qty_available = $SQ->get_products_total_qty(); } die(json_encode(array( 'html'=>MSG_SUCCESS_AMAZON_ALLOCATION, 'error'=>0, 'data'=>array( 'products_id'=>sprintf( '%s', $pID,$pID,$pID,$pID ), 'price_local'=>number_format($price,2,',',''), 'qty_local'=>$qty, 'qty_available'=>$qty_available ) ))); // $messageStack->add_session(MSG_SUCCESS_AMAZON_ALLOCATION,'success'); // xtc_redirect(xtc_href_link('amazon.php',xtc_get_all_get_params(array('action','pID','sku','asin')).'action=feed')); exit; break; case 'allocate_search': $amazon_form_id = 'allocate_search'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=allocate','post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $smarty->assign('mode',$action); $smarty->assign('sku',$_REQUEST['sku']); $smarty->assign('asin',$_REQUEST['asin']); echo $smarty->display('amazon_helper.html'); exit; break; case 'transfer': $products_id_array = array(); $query = xtc_db_query(sprintf( "SELECT products_id FROM amazon_products WHERE asin = '' and selling_partner_id='%s'", $current_seller )); while($record = xtc_db_fetch_array($query)){ $products_id_array[] = $record['products_id']; } $FeedType = '_POST_PRODUCT_DATA_'; $service = $AS->get_service(); $SF = new SubmitFeed(); $feed = $SF->get_product_feed($products_id_array, $FeedType); $feed = $feed->asXML(); // header('Content-Type:text/xml'); // die($feed); $feedHandle = @fopen('php://memory', 'rw+'); fwrite($feedHandle, $feed); rewind($feedHandle); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'FeedType' => $FeedType, 'FeedContent' => $feedHandle, 'PurgeAndReplace' => false, 'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)), ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters); $result = $SF->invokeSubmitFeed($service, $request); fclose($feedHandle); exit; break; case 'sync_process': $file = AMAZON_SAVE_PATH.basename($_REQUEST['file']); $items = array(); if(!is_file($file)){ die('Unknown File '.$file); } $xml = simplexml_load_file($file); for($i=0;$iItem);$i++){ $sku = $xml->Item[$i]->SKU; $pID = $xml->Item[$i]->ProductsId; $product = new product($pID); $AmazonQuantityDB = current($xml->Item[$i]->AmazonQuantityDB); $AmazonQuantity = current($xml->Item[$i]->AmazonQuantity); $AmazonPriceDB = current($xml->Item[$i]->AmazonPriceDB); $AmazonPrice = current($xml->Item[$i]->AmazonPrice); $TodoList = $xml->Item[$i]->TodoList; $todo_size = (isset($TodoList->Todo)) ? sizeOf($TodoList->Todo) : 0; for($j=0;$j<$todo_size;$j++){ $todo = $TodoList->Todo[$j]; $attributes = $todo->attributes(); switch("".$attributes['action']){ case 'DBQuantityChange': $update_sql_array = array( 'quantity'=>(int)$AmazonQuantity, 'last_quantity_feed'=>'now()' ); xtc_db_perform('amazon_products',$update_sql_array,'update',sprintf( "products_id=%s and sku='%s' and selling_partner_id='%s'", $pID,$sku,$current_seller )); $SQ = new products_quantity($pID); $new_qty = current($todo->Value); $qty_total = $SQ->get_products_total_qty(); // DA WIR VOM ORIG-WERT MINUS RECHNEN - MUSS DER POSITIVE GESPEICHERT WERDEN yes_add_products_history($pID, sprintf(MSG_AMAZON_SYNC_UPDATE_QTY, $AmazonQuantityDB, $AmazonQuantity )); if(defined('PRODUCTS_QUANTITY_LOG_MODE') and PRODUCTS_QUANTITY_LOG_MODE == 1){ $SQ->update_log('at_amazon',$new_qty); } break; case 'DBUpdateAmazonASIN': $update_sql_array = array( 'asin'=>current($todo->Value), 'last_quantity_feed'=>'now()' ); xtc_db_perform('amazon_products',$update_sql_array,'update',sprintf( "products_id=%s and sku='%s' and selling_partner_id='%s'", $pID,$sku,$current_seller )); $product->add_history(sprintf( MSG_AMAZON_SYNC_UPDATE_ASIN,current($todo->Value) )); break; case 'DBPriceChange': $update_sql_array = array( 'price'=>current($todo->Value), 'last_price_feed'=>'now()' ); xtc_db_perform('amazon_products',$update_sql_array,'update',sprintf( "products_id=%s and sku='%s' and selling_partner_id='%s'", $pID,$sku,$current_seller )); $product->add_history(sprintf( MSG_AMAZON_SYNC_UPDATE_PRICE, $update_sql_array['price'] )); break; } } } unlink($file); $messageStack->add_session(MSG_SYNC_SUCCESS,'success'); xtc_redirect(xtc_href_link('amazon.php')); exit; break; case 'sync_confirm_process': $file = AMAZON_SAVE_PATH.basename($_REQUEST['file']); $items = array(); if(!is_file($file)){ die('Unknown File '.$file); } $xml = simplexml_load_file($file); unset($xml->Status); $xml->addChild('Status','Confirmed'); unset($xml->NumberOfItems); $xml->addChild('NumberOfItems',sizeOf($_REQUEST['todo'])); $counter = 0; // NICHT SUBMITTED RAUS for($i=0;$iItem);$i++){ $sku = $xml->Item[$i]->SKU; if(!isset($_REQUEST['todo']["$sku"])){ unset($xml->Item[$i]); } } $deletes = array(); for($i=0;$iItem);$i++){ $sku = $xml->Item[$i]->SKU; $todo_size = (isset($xml->Item[$i]->TodoList->Todo)) ? sizeOf($xml->Item[$i]->TodoList->Todo) : 0; for($j=0;$j<$todo_size;$j++){ $todo = $xml->Item[$i]->TodoList->Todo[$j]; $attributes = $todo->attributes(); if(!in_array($attributes['id'],$_REQUEST['todo']["$sku"])){ $deletes[] = array('item'=>$i,'todo_id'=>$j); } } } for($del=0;$delItem[ $deletes[$del]['item'] ]->TodoList->Todo[$deletes[$del]['todo_id']]); } unlink($file); $basics->create_file($file, $xml->asXML()); xtc_redirect(xtc_href_link('amazon.php','action=sync_process&file='.$_REQUEST['file'])); break; case 'sync_confirm': $file = basename($_REQUEST['file']); $items = array(); $xml = simplexml_load_file(AMAZON_SAVE_PATH.$file); foreach($xml->children() as $sync_item){ switch($sync_item->getName()){ case 'Status': $status = $sync_item; break; case 'NumberOfItems': $number_of_items = $sync_item; break; case 'Created': $created = $sync_item; break; case 'Item': $_item = array(); foreach($sync_item->children() as $item){ switch($item->getName()){ case 'TodoList': foreach($item->children() as $todo){ $attributes = current($todo->attributes()); $value = current($todo->Value); switch($attributes['action']){ case 'DBUpdateAmazonASIN': $action_title = AMAZON_TODOLIST_ASIN; break; case 'DBPriceChange': $action_title = AMAZON_TODOLIST_PRICE; $value = number_format($value,2,',',''); break; case 'DBQuantityChange': $action_title = AMAZON_TODOLIST_QTY; break; } $_item['todo'][] = array( 'id'=>$attributes['id'], 'action_title'=>$action_title, 'action'=>$attributes['action'], 'value'=>$value ); } break; default: $_item[$item->getName()] = current($item); break; } } $items[] = $_item; break; } } $amazon_form_id = 'sync_confirm'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=sync_confirm_process&file='.$_REQUEST['file'],'post','id="'.$amazon_form_id.'"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $smarty->assign('action','sync_confirm'); $smarty->assign('items',$items); $smarty->assign('file',$_REQUEST['file']); $smarty->assign('filedate',date('d.m.Y H:i:s',strtotime($created))); $smarty->assign('items_num',$number_of_items); break; case 'sync': if(!isset($_REQUEST['reportDocumentId']) or !isset($_REQUEST['reportDocumentId'])){ die('Missing Parameter'); } $reportDocumentId = $_REQUEST['reportDocumentId']; $R = new Report; $R->setReportType($_GET['ReportType']); $R->import_filename = $amazon_import_filename; if(empty($reportDocumentId)){ $service = $AS->get_service(); $items = $R->invokeGetReport($service, $request,true); $parameters = array ( 'MWSAuthToken' => $auth_params['mwsauthtoken'] ); }else{ $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); try { $result = $apiInstance->getReportDocument($reportDocumentId); } catch (Exception $e) { echo 'Exception when calling ReportsV20210630Api->getReports: ', $e->getMessage(), PHP_EOL; } $items = $R->invokeGetReport($result, $current_seller); } $sync = new amz_Sync($items); if(!sizeOf($sync->getItems())){ $messageStack->add_session(MSG_ERROR_NO_ITEMS,'error'); xtc_redirect(xtc_href_link('amazon.php')); } $sync->process_worklist(); $filename = sprintf('AMAZON_WORKLIST_%s.xml', time() ); $file = sprintf('%s/%s',AMAZON_SAVE_PATH,$filename); $basics->create_file($file, $sync->getXML()); xtc_redirect(xtc_href_link('amazon.php','action=sync_confirm&file='.$filename)); exit; break; case 'get_yes_qty': $pID = xtc_db_input($_REQUEST['pID']); $SQ = new products_quantity($pID); $collies = xtc_get_product_collies($pID); if(sizeOf($collies)>0){ $avqty = xtc_get_product_collie_qty($pID); }else{ $avqty = $SQ->get_products_total_qty(); } die((int)$avqty); break; case 'admin_feedinfo': $feedApiInstance = new \SellingPartnerApi\Api\FeedsV20210630Api($ASP->getSPAPI_config($current_seller)); $types = ['POST_INVENTORY_AVAILABILITY_DATA','POST_PRODUCT_PRICING_DATA','POST_ORDER_FULFILLMENT_DATA']; if(isset($_GET['id'])){ $id = xtc_db_input($_GET['id']); $result = $feedApiInstance->getFeed($id); yes_debug($result);exit; }elseif( isset($_GET['docId'])){ $docId = xtc_db_input($_GET['docId']); $doc=$feedApiInstance->getFeedDocument($docId); $inhalt = file_get_contents($doc->getUrl()); $xml = simplexml_load_string($inhalt); if(current($xml->Message->ProcessingReport->ProcessingSummary->MessagesProcessed) > current($xml->Message->ProcessingReport->ProcessingSummary->MessagesSuccessful)){ printf('

Es wurden %d Messages gemeldet und nur %d davon Erfolgreich

', $xml->Message->ProcessingReport->ProcessingSummary->MessagesProcessed, $xml->Message->ProcessingReport->ProcessingSummary->MessageSuccessful ); foreach($xml->Message->ProcessingReport->Result as $r){ printf('MessageID %d: %s (%s)
%s
', $r->MessageID, $r->ResultCode, $r->ResultMessageCode, $r->ResultDescription ); } }else{ echo 'Feed wurde erfolgreich verarbeitet'; } }else{ $result = $feedApiInstance->getFeeds($types); foreach($result->getFeeds() as $feed){ printf('%s created %s status %s DocID: %s
', xtc_href_link('amazon.php','action=admin_feedinfo&id='.$feed->getFeedId()), $feed->getFeedId(), $feed->getCreatedTime(), $feed->getProcessingStatus(), xtc_href_link('amazon.php','action=admin_feedinfo&docId='.$feed->getResultFeedDocumentId()), $feed->getResultFeedDocumentId() ); } } exit; break; case 'check_request_process': die('2'); // keine relevanz mehr (amazon.js) $id = xtc_db_input($_REQUEST['feed_submission_id']); $feedApiInstance = new \SellingPartnerApi\Api\FeedsV20210630Api($ASP->getSPAPI_config($current_seller)); //$result = $feedApiInstance->getFeed($id); $feed = new amz_Feedhandler($id); // LOKAL BEREITS GESPEICHERT if($feed->getProcessed() == 1){ die('2'); } if($feed->set_feed_info_from_api($feedApiInstance)){ $feed->update_feed_info_db(); } if($feed->process_feed()){ die('1'); } $status = $feed->getFeed_processing_status(); $err = $feed->getErrorMsg(); if(sizeOf($err)){ for($i=0;$i

'; } die(sprintf( '%s
Feed-ID: %s

Status: %s', TEXT_REQUESTING_PROCESS,$id,$status)); break; case 'test': die(date('d.m.Y H:i:s')); break; case 'update_report_ack': $service = $AS->get_service(); $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'ReportIdList' => array ('Id' => $_REQUEST['reportId']), 'Acknowledged' => true, ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $request = new MarketplaceWebService_Model_UpdateReportAcknowledgementsRequest($parameters); $response = $service->updateReportAcknowledgements($request); if ($response->isSetUpdateReportAcknowledgementsResult()) { $updateReportAcknowledgementsResult = $response->getUpdateReportAcknowledgementsResult(); $messageStack->add_session(sprintf(MSG_SUCCESS_REPORT_ACK,$updateReportAcknowledgementsResult->getCount()),'success'); } xtc_redirect(xtc_href_link('amazon.php','action=reports')); exit; break; case 'get_report': $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); $report_type = $_GET['ReportType']; $marketplaceIds = ["A1PA6795UKMFR9"]; $body = new \SellingPartnerApi\Model\ReportsV20210630\CreateReportSpecification; $body->setReportType($report_type); $body->setMarketplaceIds($marketplaceIds); try { $result = $apiInstance->createReport($body); //die('RES:'.$result->getReportId()); } catch (Exception $e) { echo 'Exception when calling ReportsV20210630Api->getReports: ', $e->getMessage(), PHP_EOL; } $messageStack->add_session(MSG_SUCCESS_GET_REPORT,'success'); xtc_redirect(xtc_href_link('amazon.php','action=reports')); break; case 'update_qty': $current_seller = (isset($_REQUEST['selling_partner_id']))?$_REQUEST['selling_partner_id']:''; if(empty($current_seller)){ $ASP_blank = new amazon_sp(null, false); foreach($ASP_blank->auth_params->users as $username=>$data){ $current_seller = $username; } } $FeedType = 'POST_INVENTORY_AVAILABILITY_DATA'; $afc = new \YES4Trade\Model\amazon_feed_collector([ 'selling_partner_id'=>$current_seller, 'sku'=>"".$_REQUEST['sku'], 'feed_type'=>$FeedType, 'feed_value'=>"".$_REQUEST['qty'], 'fulfillment_latency'=>(int)$_REQUEST['fulfillment_latency'], ]); $afc->create(); die('0'); break; case 'update_price': $current_seller = (isset($_REQUEST['selling_partner_id']))?$_REQUEST['selling_partner_id']:''; if(empty($current_seller)){ $ASP_blank = new amazon_sp(null, false); foreach($ASP_blank->auth_params->users as $username=>$data){ $current_seller = $username; } } $FeedType = 'POST_PRODUCT_PRICING_DATA'; $afc = new \YES4Trade\Model\amazon_feed_collector([ 'selling_partner_id'=>$current_seller, 'sku'=>"".$_REQUEST['sku'], 'feed_type'=>$FeedType, 'feed_value'=>"".$_REQUEST['price'], ]); $afc->create(); die('0'); break; case 'ajax_update_qty': $amazon_form_id = 'update_qty'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=update_qty&selling_partner_id='.$current_seller,'post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $products_id = yes_get_products_id_from_amazon_sku(xtc_db_input($_REQUEST['sku']),$current_seller); $fl = yes_get_products_amazon_fulfillmentlatency($products_id); $smarty->assign(array( 'mode'=>'update_qty', 'asin'=>$_REQUEST['asin'], 'selling_partner_id'=>$current_seller, 'sku'=>$_REQUEST['sku'], 'fulfillment_latency'=>$fl )); $smarty->assign('INPUT_ASIN',xtc_draw_hidden_field('asin',$_REQUEST['asin'])); $smarty->assign('INPUT_SKU',xtc_draw_hidden_field('sku',$_REQUEST['sku'])); $smarty->assign('INPUT_QTY',xtc_draw_input_field('qty',$_REQUEST['qty'],'size="6" maxlength="6"')); $smarty->assign('INPUT_FULFILLMENT_LATENCY',xtc_draw_input_field('fulfillment_latency',$fl,'size="2" maxlength="2"')); if(!isset($_REQUEST['from'])){ $smarty->assign('AJAX_REFRESH_LINK',xtc_href_link('amazon.php','action=feed&ReportType='.$_REQUEST['ReportType'].'&reportDocumentId='.$_REQUEST['reportDocumentId'].'&reportId='.$_REQUEST['reportId'])); } echo $smarty->display('amazon_helper.html'); exit; break; case 'ajax_update_price': $amazon_form_id = 'update_price'; $smarty->assign('FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=update_price&selling_partner_id='.$current_seller,'post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('AMAZON_FORM_ID',$amazon_form_id); $smarty->assign(array( 'mode'=>'update_price', 'asin'=>$_REQUEST['asin'], //'merchant_id'=>$_REQUEST['merchant_id'], 'selling_partner_id'=>$current_seller, 'sku'=>$_REQUEST['sku'] )); $smarty->assign('INPUT_ASIN',xtc_draw_hidden_field('asin',$_REQUEST['asin'])); $smarty->assign('INPUT_SKU',xtc_draw_hidden_field('sku',$_REQUEST['sku'])); $smarty->assign('INPUT_PRICE',xtc_draw_input_field('price',$_REQUEST['price'],'size="12" maxlength="12"')); $smarty->assign('AJAX_REFRESH_LINK',xtc_href_link('amazon.php','action=feed&reportDocumentId='.$_REQUEST['reportDocumentId'])); echo $smarty->display('amazon_helper.html'); exit; break; case 'feed': $R = new Report; if(isset($_REQUEST['from_file']) and $_REQUEST['from_file'] == '1'){ $service = $AS->get_service(); $R->setReportType('_GET_MERCHANT_LISTINGS_DATA_'); $R->import_filename = $amazon_import_filename; $items = $R->invokeGetReport($service, $request,true); }else{ if(!isset($_REQUEST['reportId']) or empty($_REQUEST['reportId'])){ die('Missing parameter.'); } $reportId = $_REQUEST['reportId']; $reportDocumentId = $_REQUEST['reportDocumentId']; $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); try { $result = $apiInstance->getReportDocument($reportDocumentId); } catch (Exception $e) { echo 'Exception when calling ReportsV20210630Api->getReports: ', $e->getMessage(), PHP_EOL; } } switch($_REQUEST['ReportType']){ case 'FEE_DISCOUNTS_REPORT': case 'GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_SHIPPING': case 'GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL': $c = file_get_contents($result->getUrl()); $items = []; $rows = explode(PHP_EOL, $c); foreach($rows as $row){ $cols = explode("\t",$row); $items[] = $cols; } $smarty->assign('items',$items); $smarty->assign('REPORT_ID',$_REQUEST['reportId']); $smarty->assign('ReportType',$_REQUEST['ReportType']); $smarty->assign('ReportTypeTitle',$_REQUEST['ReportType']); $smarty->assign('ReportDate',$_REQUEST['from']); break; case 'GET_FLAT_FILE_OPEN_LISTINGS_DATA': case 'GET_MERCHANT_LISTINGS_DATA': case '_GET_FLAT_FILE_ORDERS_DATA_': case '_GET_FLAT_FILE_OPEN_LISTINGS_DATA_': case '_GET_MERCHANT_LISTINGS_DATA_': case '_GET_ORDERS_DATA_': $R->setReportType($_REQUEST['ReportType']); if(!isset($_REQUEST['from_file']) or $_REQUEST['from_file'] != '1'){ $items = $R->invokeGetReport($result, $current_seller); } if($_REQUEST['ReportType'] == '_GET_ORDERS_DATA_'){ $importable = true; foreach($items as $item){ if(!$item['valid_products_ids']){ $importable = false; } } if($importable){ $smarty->assign('IMPORTABLE',true); $smarty->assign('PROCESS_ORDER_FORM',xtc_draw_form('process_order_feed','amazon.php',xtc_get_all_get_params(array('action')).'action=process_order_feed')); } } $smarty->assign('items',$items); $smarty->assign('REPORT_ID',$_REQUEST['reportId']); $smarty->assign('REPORT_DOCUMENT_ID', $result->getReportDocumentId()); $smarty->assign('ReportType',$_REQUEST['ReportType']); $smarty->assign('ReportTypeTitle',$R->getReportTypeTitle($_REQUEST['ReportType'])); $smarty->assign('ReportDate',$_REQUEST['from']); $smarty->assign('PROCESS_ORDER_LINK',xtc_href_link('amazon.php',xtc_get_all_get_params(array('action','amazon_order_id')).'action=process_order')); $smarty->assign('LINK_AUTOALLOCATE',xtc_href_link('amazon.php',xtc_get_all_get_params(array('action','amazon_order_id')).'action=auto_allocate')); $amazon_form_id = 'allocate_search'; $smarty->assign('ALLOCATE_FORM',xtc_draw_form($amazon_form_id,'amazon.php','action=allocate','post','id="'.$amazon_form_id.'" onsubmit="return false;"')); $smarty->assign('ALLOCATE_AMAZON_FORM_ID',$amazon_form_id); //$smarty->assign('mode',$action); //$smarty->assign('sku',$_REQUEST['sku']); //$smarty->assign('asin',$_REQUEST['asin']); if(isset($_REQUEST['NextToken'])) $smarty->assign('NextLink',xtc_href_link('amazon.php',xtc_get_all_get_params(array('NextToken')).'NextToken='.$_REQUEST['NextToken'])); break; case 'FeedSummaryReport': $R->invokeGetReport($service, $request); break; case '_GET_FLAT_FILE_PAYMENT_SETTLEMENT_DATA_': $items = $R->invokeGetReport($service, $request); print_r($items); exit; break; } $smarty->assign([ 'action'=>$action, 'MARKETPLACE_IDS'=>$_GET['marketplace_ids'], ]); break; case 'feeds': case 'reports': $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); $report_types = [ "GET_FLAT_FILE_OPEN_LISTINGS_DATA", "GET_MERCHANT_LISTINGS_DATA", "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL", ]; $processingStatuses = [ "IN_QUEUE", "IN_PROGRESS", "DONE", ]; $createdSince = YES4TRADE_AMAZON_SP_GETREPORTS_STARTDATE; $page_size = 50; if(isset($_REQUEST['NextToken'])){ if(!in_array($_REQUEST['NextToken'],$_SESSION['AMZSP-REP-HISTORY'])){ $_SESSION['AMZSP-REP-HISTORY'][] = $_REQUEST['NextToken']; } try { $result = $apiInstance->getReports(null, null, null, null, null, null, $_REQUEST['NextToken']); } catch (Exception $e) { die('Exception when calling ReportsV20210630Api->getReports: '. $e->getMessage()); } }else{ $_SESSION['AMZSP-REP-HISTORY'] = []; $marketplaceIds = null; try { $result = $apiInstance->getReports($report_types, $processingStatuses,$marketplaceIds, $page_size, $createdSince); } catch (Exception $e) { die('Exception when calling ReportsV20210630Api->getReports: '. $e->getMessage()); } } if($result->getNextToken() != ''){ $smarty->assign('NEXT_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']).'NextToken='.urlencode($result->getNextToken()) )); } $page_no = 1; if(sizeOf($_SESSION['AMZSP-REP-HISTORY'])){ $last_nr = ''; foreach($_SESSION['AMZSP-REP-HISTORY'] as $nr => $last){ if($last == $_REQUEST['NextToken']){ $last_nr = $nr-1; $page_no = $nr+2; } } if($last_nr < 0){ $smarty->assign('LAST_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']) )); }else{ $smarty->assign('LAST_LINK',xtc_href_link('amazon.php', xtc_get_all_get_params(['NextToken']).'NextToken='.urlencode($_SESSION['AMZSP-REP-HISTORY'][$last_nr]) )); } } $smarty->assign([ 'action'=>$action, 'items'=>$result->getReports(), 'PAGE_INFO'=>sprintf(TEXT_AMAZON_REPORTS_PAGING, $page_no, xtc_date_short(YES4TRADE_AMAZON_SP_GETREPORTS_STARTDATE), $page_size, ), ]); break; case 'products': $order_by = (isset($_REQUEST['order_by'])) ? xtc_db_input($_REQUEST['order_by']) : 'amazon_products_id'; $query_raw = sprintf("select * from amazon_products where asin='' order by %s", $order_by ); $split = new splitPageResults($_GET['page'], $view_limit = MAX_DISPLAY_SEARCH_RESULTS, $query_raw, $query_numrows,$reviews_count_query_raw); $split_result = $split->display_count($query_numrows, MAX_DISPLAY_SEARCH_RESULTS, $_GET['page'], TEXT_DISPLAY_NUMBER_OF_ITEMS,xtc_get_all_get_params(array('page'))); $split_navi = $split->display_links($query_numrows, MAX_DISPLAY_SEARCH_RESULTS, MAX_DISPLAY_PAGE_LINKS, $_GET['page'], xtc_get_all_get_params(array('page'))); $smarty->assign('SPLIT_PAGE_RESULT',$split_result); $smarty->assign('SPLIT_PAGE_NAVI',$split_navi); $query = yes_db_query($query_raw,false); foreach($query as $product){ print_r($product); } $smarty->assign('action',$action); $smarty->display('amazon.html'); exit; break; case 'add_product': $pID = (int)xtc_db_input($_REQUEST['pID']); $sku = xtc_db_input($_REQUEST['sku']); $price = xtc_db_input($_REQUEST['price']); if(empty($pID) or empty($sku) or $price <= 0 ) die('Missing Parameters'); $check_query = xtc_db_query(sprintf( "SELECT amazon_products_id FROM amazon_products WHERE sku='%s'", $sku )); if(xtc_db_num_rows($check_query)) die(sprintf(MSG_ERROR_SKU_EXISTS,$sku)); xtc_db_query(sprintf( "INSERT INTO amazon_products SET products_id='%s',sku='%s',price='%s'", $pID,$sku,$price )); die('1'); break; case 'update_product': $pID = (int)xtc_db_input($_REQUEST['pID']); $sku = xtc_db_input($_REQUEST['sku']); $price = xtc_db_input($_REQUEST['price']); if(empty($pID) or empty($sku) or $price <= 0 ) die('Missing Parameters'); xtc_db_query(sprintf( "UPDATE amazon_products SET sku='%s',price='%s' WHERE products_id='%s'", $sku,$price,$pID )); die('1'); break; case 'report': $parameters = array ( 'Marketplace' => $auth_params['marketplace_id'], 'Merchant' => $auth_params['merchant_id'], 'AvailableToDate' => new DateTime('now'), 'MaxCount' => 1, 'AvailableFromDate' => new DateTime('-1 hour'), 'ReportRequestIdList' => array('ID'=>$_REQUEST['RequestId']) ); if(!empty($auth_params['mwsauthtoken'])){ $parameters['MWSAuthToken'] = $auth_params['mwsauthtoken']; } $AS = new amazon_service(); $service = $AS->get_service(); $RL = new ReportList; $request = new MarketplaceWebService_Model_GetReportListRequest($parameters); $items = $RL->invokeGetReportList($service, $request); $item = current($items); $link = xtc_href_link('amazon.php',sprintf( 'action=feed&reportId=%s&ReportType=%s',$item['ID'],$item['REPORT_TYPE'] )); if($RL->getNextToken()!='') $link .= '&NextToken='.urlencode($RL->getNextToken()); xtc_redirect($link); break; default: if(!empty($_SESSION['current_amazon_selling_partner_id'] )){ $smarty->assign([ 'action'=>'', 'PRODUCTS_COUNT'=>$ASP->count_amazon_products_allocations($current_seller), ]); if(sizeOf((array)$ASP->auth_params->users)){ $report_id = Null; $apiInstance = new SellingPartnerApi\Api\ReportsV20210630Api($ASP->configObj); $report_types = [ 'GET_FLAT_FILE_OPEN_LISTINGS_DATA', 'GET_MERCHANT_LISTINGS_DATA', "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL", //'GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_SHIPPING', //'GET_ORDER_REPORT_DATA_INVOICING', /* 'GET_ORDER_REPORT_DATA_TAX', 'GET_ORDER_REPORT_DATA_SHIPPING', 'GET_FLAT_FILE_ORDER_REPORT_DATA_INVOICING', 'GET_FLAT_FILE_ORDER_REPORT_DATA_SHIPPING', 'GET_FLAT_FILE_ORDER_REPORT_DATA_TAX', 'GET_FLAT_FILE_PENDING_ORDERS_DATA',*/ ]; $processing_statuses = array("DONE"); // string[] | A list of processing statuses used to filter reports. $marketplace_ids = Null;//array('marketplace_ids_example'); // string[] | A list of marketplace identifiers used to filter reports. The reports returned will match at least one of the marketplaces that you specify. $markets = $ASP->get_active_marketplaces(); $marketplace_ids = array_slice($markets,0,10); $page_size = 100; // int | The maximum number of reports to return in a single call. $created_since = YES4TRADE_AMAZON_SP_GETREPORTS_STARTDATE; $created_until = Null; //'created_until_example'; // string | The latest report creation date and time for reports to include in the response, in ISO 8601 date time format. The default is now. $next_token = (isset($_GET['next_token']))?$_GET['next_token']:null; try { $result = $apiInstance->getReports($report_types, $processing_statuses, $marketplace_ids, $page_size, $created_since, $created_until, $next_token); // der part in der if-Abfrage nach "and" musste in der sandbox so eingebaut werden, // da der next_token Parameter in der sandbox ignoriert wird und immer der selbe // next_token des selben Reports zurueckgegeben wird if(!empty($result->getNextToken()) and !is_null($result->getNextToken()) and strtolower($result->getNextToken()) !== strtolower($next_token)){ //echo "\nGet Next Token \r\n".$result->getNextToken()."\r\nlast token:\r\n".$next_token."\r\n"; //system("php ".basename(__FILE__).' getreports '.$result->getNextToken()); } $smarty->assign('REPORT_COUNT',sizeOf($result->reports)); } catch (Exception $e) { echo 'Exception when calling ReportsV20210630Api->getReports: ', $e->getMessage(), PHP_EOL; $smarty->assign('REPORT_COUNT',0); } $smarty->assign([ 'CURRENT_SELLER'=>$current_seller, ]); $apiInstance = new \SellingPartnerApi\Api\ReportsV20210630Api( $ASP->configObj ); try{ $schedules = $apiInstance->getReportSchedules([ 'GET_FLAT_FILE_OPEN_LISTINGS_DATA', "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL", ]); $smarty->assign([ 'SCHEDULES'=>$schedules->getReportSchedules(), ]); }catch(Exception $e){ yes_debug($e); } $smarty->assign([ 'ADD_SCHEDULE_LINK'=>xtc_href_link('amazon.php','action=add_schedule&type=GET_FLAT_FILE_OPEN_LISTINGS_DATA'), 'TEXT_ADD_SCHEDULE'=>TEXT_ADD_SCHEDULE, 'TEXT_AMAZON_REPORT_COUNT'=>sprintf(TEXT_AMAZON_REPORT_COUNT,xtc_date_short(YES4TRADE_AMAZON_SP_GETREPORTS_STARTDATE)) ]); // end if exists auth users } } break; } yes_draw_pre_header(); yes_draw_header(TITLE); ?> 0){ $smarty->assign('AFC_LINK',xtc_href_link('amazon.php','action=afc_list')); } $smarty->display('amazon.html'); ?>