uc_ups.ship.inc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. <?php
  2. /**
  3. * @file
  4. * UPS functions for label generation.
  5. */
  6. /**
  7. * Shipment creation callback.
  8. *
  9. * Confirms shipment data before requesting a shipping label.
  10. *
  11. * @param $order_id
  12. * The order id for the shipment.
  13. * @param $package_ids
  14. * Array of package ids to shipped.
  15. *
  16. * @see uc_ups_fulfill_order_validate()
  17. * @see uc_ups_fulfill_order_submit()
  18. * @ingroup forms
  19. */
  20. function uc_ups_fulfill_order($form, &$form_state, $order, $package_ids) {
  21. $pkg_types = _uc_ups_pkg_types();
  22. $form['order_id'] = array('#type' => 'value', '#value' => $order->order_id);
  23. $packages = array();
  24. $addresses = array();
  25. // Container for package data
  26. $form['packages'] = array(
  27. '#type' => 'fieldset',
  28. '#title' => t('Packages'),
  29. '#collapsible' => TRUE,
  30. '#tree' => TRUE,
  31. );
  32. foreach ($package_ids as $id) {
  33. $package = uc_shipping_package_load($id);
  34. if ($package) {
  35. foreach ($package->addresses as $address) {
  36. if (!in_array($address, $addresses)) {
  37. $addresses[] = $address;
  38. }
  39. }
  40. // Create list of products and get a representative product (last one in
  41. // the loop) to use for some default values.
  42. $product_list = array();
  43. $declared_value = 0;
  44. foreach ($package->products as $product) {
  45. $product_list[] = $product->qty . ' x ' . $product->model;
  46. $declared_value += $product->qty * $product->price;
  47. }
  48. // Use last product in package to determine package type.
  49. $ups_data = db_query("SELECT pkg_type FROM {uc_ups_products} WHERE nid = :nid", array(':nid' => $product->nid))->fetchAssoc();
  50. $product->ups = $ups_data;
  51. $pkg_form = array(
  52. '#type' => 'fieldset',
  53. '#title' => t('Package !id', array('!id' => $id)),
  54. );
  55. $pkg_form['products'] = array(
  56. '#theme' => 'item_list',
  57. '#items' => $product_list,
  58. );
  59. $pkg_form['package_id'] = array(
  60. '#type' => 'hidden',
  61. '#value' => $id,
  62. );
  63. $pkg_form['pkg_type'] = array(
  64. '#type' => 'select',
  65. '#title' => t('Package type'),
  66. '#options' => $pkg_types,
  67. '#default_value' => $product->ups['pkg_type'],
  68. '#required' => TRUE,
  69. );
  70. $pkg_form['declared_value'] = array(
  71. '#type' => 'textfield',
  72. '#title' => t('Declared value'),
  73. '#default_value' => $declared_value,
  74. '#required' => TRUE,
  75. );
  76. $pkg_form['weight'] = array(
  77. '#type' => 'container',
  78. '#attributes' => array('class' => array('uc-inline-form', 'clearfix')),
  79. '#description' => t('Weight of the package. Default value is sum of product weights in the package.'),
  80. '#weight' => 15,
  81. );
  82. $pkg_form['weight']['weight'] = array(
  83. '#type' => 'textfield',
  84. '#title' => t('Weight'),
  85. '#default_value' => isset($package->weight) ? $package->weight : 0,
  86. '#size' => 10,
  87. '#maxlength' => 15,
  88. );
  89. $pkg_form['weight']['units'] = array(
  90. '#type' => 'select',
  91. '#title' => t('Units'),
  92. '#options' => array(
  93. 'lb' => t('Pounds'),
  94. 'kg' => t('Kilograms'),
  95. 'oz' => t('Ounces'),
  96. 'g' => t('Grams'),
  97. ),
  98. '#default_value' => isset($package->weight_units) ?
  99. $package->weight_units :
  100. variable_get('uc_weight_unit', 'lb'),
  101. );
  102. $pkg_form['dimensions'] = array(
  103. '#type' => 'container',
  104. '#attributes' => array('class' => array('uc-inline-form', 'clearfix')),
  105. '#description' => t('Physical dimensions of the package.'),
  106. '#weight' => 20,
  107. );
  108. $pkg_form['dimensions']['length'] = array(
  109. '#type' => 'textfield',
  110. '#title' => t('Length'),
  111. '#default_value' => isset($package->length) ? $package->length : 1,
  112. '#size' => 10,
  113. );
  114. $pkg_form['dimensions']['width'] = array(
  115. '#type' => 'textfield',
  116. '#title' => t('Width'),
  117. '#default_value' => isset($package->width) ? $package->width : 1,
  118. '#size' => 10,
  119. );
  120. $pkg_form['dimensions']['height'] = array(
  121. '#type' => 'textfield',
  122. '#title' => t('Height'),
  123. '#default_value' => isset($package->height) ? $package->height : 1,
  124. '#size' => 10,
  125. );
  126. $pkg_form['dimensions']['units'] = array(
  127. '#type' => 'select',
  128. '#title' => t('Units'),
  129. '#options' => array(
  130. 'in' => t('Inches'),
  131. 'ft' => t('Feet'),
  132. 'cm' => t('Centimeters'),
  133. 'mm' => t('Millimeters'),
  134. ),
  135. '#default_value' => isset($package->length_units) ?
  136. $package->length_units :
  137. variable_get('uc_length_unit', 'in'),
  138. );
  139. $form['packages'][$id] = $pkg_form;
  140. }
  141. }
  142. $form = uc_shipping_address_form($form, $form_state, $addresses, $order);
  143. foreach (array('delivery_email', 'delivery_last_name', 'delivery_street1', 'delivery_city', 'delivery_country', 'delivery_postal_code') as $field) {
  144. $form['destination'][$field]['#required'] = TRUE;
  145. }
  146. // Determine shipping option chosen by the customer.
  147. $method = $order->quote['method'];
  148. $methods = module_invoke_all('uc_shipping_method');
  149. if (isset($methods[$method])) {
  150. $services = $methods[$method]['quote']['accessorials'];
  151. $method = $services[$order->quote['accessorials']];
  152. }
  153. // Container for shipment data.
  154. $form['shipment'] = array(
  155. '#type' => 'fieldset',
  156. '#title' => t('Shipment data'),
  157. '#collapsible' => TRUE,
  158. );
  159. // Inform user of customer's shipping choice.
  160. $form['shipment']['shipping_choice'] = array(
  161. '#type' => 'markup',
  162. '#prefix' => '<div>',
  163. '#markup' => t('Customer selected "@method" as the shipping method and paid @rate', array('@method' => $method, '@rate' => uc_currency_format($order->quote['rate']))),
  164. '#suffix' => '</div>',
  165. );
  166. // Pass shipping charge paid information on to validation function so it
  167. // can be displayed alongside actual costs.
  168. $form['shipment']['paid'] = array(
  169. '#type' => 'value',
  170. '#value' => uc_currency_format($order->quote['rate']),
  171. );
  172. $services = _uc_ups_service_list();
  173. $default_service = '';
  174. if ($method == 'ups') {
  175. $default_service = $order->quote['accessorials'];
  176. }
  177. $form['shipment']['service'] = array(
  178. '#type' => 'select',
  179. '#title' => t('UPS service'),
  180. '#options' => $services,
  181. '#default_value' => $default_service,
  182. );
  183. $today = getdate();
  184. $form['shipment']['ship_date'] = array(
  185. '#type' => 'date',
  186. '#title' => t('Ship date'),
  187. '#default_value' => array(
  188. 'year' => $today['year'],
  189. 'month' => $today['mon'],
  190. 'day' => $today['mday']
  191. ),
  192. );
  193. $form['shipment']['expected_delivery'] = array(
  194. '#type' => 'date',
  195. '#title' => t('Expected delivery'),
  196. '#default_value' => array(
  197. 'year' => $today['year'],
  198. 'month' => $today['mon'],
  199. 'day' => $today['mday']
  200. ),
  201. );
  202. $form['actions'] = array('#type' => 'actions');
  203. $form['actions']['submit'] = array(
  204. '#type' => 'submit',
  205. '#value' => t('Review shipment')
  206. );
  207. return $form;
  208. }
  209. /**
  210. * Passes final information into shipment object.
  211. *
  212. * @see uc_ups_fulfill_order()
  213. * @see uc_ups_confirm_shipment()
  214. */
  215. function uc_ups_fulfill_order_validate($form, &$form_state) {
  216. $errors = form_get_errors();
  217. if (isset($errors)) {
  218. // Some required elements are missing - don't bother with making
  219. // a UPS API call until that gets fixed.
  220. return;
  221. }
  222. $origin = new stdClass();
  223. $destination = new stdClass();
  224. $packages = array();
  225. foreach ($form_state['values'] as $key => $value) {
  226. if (substr($key, 0, 7) == 'pickup_') {
  227. $field = substr($key, 7);
  228. $origin->$field = $value;
  229. }
  230. elseif (substr($key, 0, 9) == 'delivery_') {
  231. $field = substr($key, 9);
  232. $destination->$field = $value;
  233. }
  234. }
  235. // This is a total hack to work around changes made in the return value
  236. // from uc_shipping_address_form(). That function needs to be fixed, but
  237. // until then this should do the trick.
  238. $origin = $form_state['values']['pickup_address'];
  239. $origin->phone = $form_state['values']['phone'];
  240. $origin->first_name = $form_state['values']['first_name'];
  241. $origin->last_name = $form_state['values']['last_name'];
  242. $origin->company = $form_state['values']['company'];
  243. $origin->street1 = $form_state['values']['street1'];
  244. $origin->street2 = $form_state['values']['street2'];
  245. $origin->city = $form_state['values']['city'];
  246. $origin->zone = $form_state['values']['zone'];
  247. $origin->country = $form_state['values']['country'];
  248. $origin->postal_code = $form_state['values']['postal_code'];
  249. $origin->email = $form_state['values']['pickup_email'];
  250. $_SESSION['ups'] = array();
  251. $_SESSION['ups']['origin'] = $origin;
  252. if (empty($destination->company)) {
  253. $destination->company = $destination->first_name . ' ' . $destination->last_name;
  254. }
  255. // Determine if address is Residential or Commercial
  256. $destination->residential = variable_get('uc_ups_residential_quotes', FALSE);
  257. $_SESSION['ups']['destination'] = $destination;
  258. foreach ($form_state['values']['packages'] as $id => $pkg_form) {
  259. $package = uc_shipping_package_load($id);
  260. $package->pkg_type = $pkg_form['pkg_type'];
  261. $package->value = $pkg_form['declared_value'];
  262. $package->weight = $pkg_form['weight']['weight'];
  263. $package->weight_units = $pkg_form['weight']['units'];
  264. $package->length = $pkg_form['dimensions']['length'];
  265. $package->width = $pkg_form['dimensions']['width'];
  266. $package->height = $pkg_form['dimensions']['height'];
  267. $package->length_units = $pkg_form['dimensions']['units'];
  268. $package->qty = 1;
  269. $_SESSION['ups']['packages'][$id] = $package;
  270. }
  271. $_SESSION['ups']['service'] = $form_state['values']['service'];
  272. $_SESSION['ups']['paid'] = $form_state['values']['paid'];
  273. $_SESSION['ups']['ship_date'] = $form_state['values']['ship_date'];
  274. $_SESSION['ups']['expected_delivery'] = $form_state['values']['expected_delivery'];
  275. $_SESSION['ups']['order_id'] = $form_state['values']['order_id'];
  276. $request = uc_ups_shipment_request($_SESSION['ups']['packages'], $origin, $destination, $form_state['values']['service']);
  277. $response_obj = drupal_http_request(variable_get('uc_ups_connection_address', 'https://wwwcie.ups.com/ups.app/xml/') . 'ShipConfirm', array(
  278. 'method' => 'POST',
  279. 'data' => $request,
  280. ));
  281. $response = new SimpleXMLElement($response_obj->data);
  282. if (isset($response->Response->Error)) {
  283. $error = $response->Response->Error;
  284. $error_msg = (string) $error->ErrorSeverity . ' Error ' . (string) $error->ErrorCode . ': ' . (string) $error->ErrorDescription;
  285. if (strpos((string) $error->ErrorSeverity, 'Hard') !== FALSE) {
  286. form_set_error('', $error_msg);
  287. return FALSE;
  288. }
  289. else {
  290. drupal_set_message($error_msg, 'error');
  291. }
  292. }
  293. $charge = new stdClass();
  294. // if NegotiatedRates exist, quote based on those, otherwise, use TotalCharges
  295. if (isset($response->ShipmentCharges)) {
  296. $charge = $response->ShipmentCharges->TotalCharges;
  297. $_SESSION['ups']['rate']['type'] = t('Total Charges');
  298. if (isset($response->NegotiatedRates)) {
  299. $charge = $response->NegotiatedRates->NetSummaryCharges->GrandTotal;
  300. $_SESSION['ups']['rate']['type'] = t('Negotiated Rates');
  301. }
  302. }
  303. $_SESSION['ups']['rate']['currency'] = (string) $charge->CurrencyCode;
  304. $_SESSION['ups']['rate']['amount'] = (string) $charge->MonetaryValue;
  305. $_SESSION['ups']['digest'] = (string) $response->ShipmentDigest;
  306. }
  307. /**
  308. * Passes final information into shipment object.
  309. *
  310. * @see uc_ups_fulfill_order()
  311. * @see uc_ups_confirm_shipment()
  312. */
  313. function uc_ups_fulfill_order_submit($form, &$form_state) {
  314. $form_state['redirect'] = 'admin/store/orders/' . $form_state['values']['order_id'] . '/shipments/ups';
  315. }
  316. /**
  317. * Constructs an XML shipment request.
  318. *
  319. * @param $packages
  320. * Array of packages received from the cart.
  321. * @param $origin
  322. * Delivery origin address information.
  323. * @param $destination
  324. * Delivery destination address information.
  325. * @param $ups_service
  326. * UPS service code (refers to UPS Ground, Next-Day Air, etc.).
  327. *
  328. * @return
  329. * ShipConfirm XML document to send to UPS.
  330. */
  331. function uc_ups_shipment_request($packages, $origin, $destination, $ups_service) {
  332. $store['name'] = uc_store_name();
  333. $store['owner'] = variable_get('uc_store_owner', NULL);
  334. $store['email'] = uc_store_email();
  335. $store['email_from'] = uc_store_email();
  336. $store['phone'] = variable_get('uc_store_phone', NULL);
  337. $store['fax'] = variable_get('uc_store_fax', NULL);
  338. $store['street1'] = variable_get('uc_store_street1', NULL);
  339. $store['street2'] = variable_get('uc_store_street2', NULL);
  340. $store['city'] = variable_get('uc_store_city', NULL);
  341. $store['zone'] = variable_get('uc_store_zone', NULL);
  342. $store['postal_code'] = variable_get('uc_store_postal_code', NULL);
  343. $store['country'] = variable_get('uc_store_country', 840);
  344. $account = variable_get('uc_ups_shipper_number', '');
  345. $ua = explode(' ', $_SERVER['HTTP_USER_AGENT']);
  346. $user_agent = $ua[0];
  347. $services = _uc_ups_service_list();
  348. $service = array('code' => $ups_service, 'description' => $services[$ups_service]);
  349. $pkg_types = _uc_ups_pkg_types();
  350. $shipper_zone = uc_get_zone_code($store['zone']);
  351. $shipper_country = uc_get_country_data(array('country_id' => $store['country']));
  352. $shipper_country = $shipper_country[0]['country_iso_code_2'];
  353. $shipper_zip = $store['postal_code'];
  354. $shipto_zone = uc_get_zone_code($destination->zone);
  355. $shipto_country = uc_get_country_data(array('country_id' => $destination->country));
  356. $shipto_country = $shipto_country[0]['country_iso_code_2'];
  357. $shipto_zip = $destination->postal_code;
  358. $shipfrom_zone = uc_get_zone_code($origin->zone);
  359. $shipfrom_country = uc_get_country_data(array('country_id' => $origin->country));
  360. $shipfrom_country = $shipfrom_country[0]['country_iso_code_2'];
  361. $shipfrom_zip = $origin->postal_code;
  362. $ups_units = variable_get('uc_ups_unit_system', variable_get('uc_length_unit', 'in'));
  363. $package_schema = '';
  364. foreach ($packages as $package) {
  365. // Determine length conversion factor and weight conversion factor
  366. // for this shipment
  367. $length_factor = uc_length_conversion($package->length_units, variable_get('uc_ups_unit_system', variable_get('uc_length_unit', 'in')));
  368. switch ($ups_units) {
  369. case 'in':
  370. $weight_factor = uc_weight_conversion($package->weight_units, 'lb');
  371. $units = 'LBS';
  372. $unit_name = 'Pounds';
  373. break;
  374. case 'cm':
  375. $weight_factor = uc_weight_conversion($package->weight_units, 'kg');
  376. $units = 'KGS';
  377. $unit_name = 'Kilograms';
  378. break;
  379. }
  380. $qty = $package->qty;
  381. for ($i = 0; $i < $qty; $i++) {
  382. $package_type = array('code' => $package->pkg_type, 'description' => $pkg_types[$package->pkg_type]);
  383. $package_schema .= "<Package>";
  384. $package_schema .= "<PackagingType>";
  385. $package_schema .= "<Code>" . $package_type['code'] . "</Code>";
  386. $package_schema .= "</PackagingType>";
  387. if ($package->pkg_type == '02' && $package->length && $package->width && $package->height) {
  388. if ($package->length < $package->width) {
  389. list($package->length, $package->width) = array($package->width, $package->length);
  390. }
  391. $package_schema .= "<Dimensions>";
  392. $package_schema .= "<UnitOfMeasurement>";
  393. $package_schema .= "<Code>" . strtoupper(variable_get('uc_ups_unit_system', variable_get('uc_length_unit', 'in'))) . "</Code>";
  394. $package_schema .= "</UnitOfMeasurement>";
  395. $package_schema .= "<Length>" . (floor($package->length * $length_factor) + 1) . "</Length>";
  396. $package_schema .= "<Width>" . (floor($package->width * $length_factor) + 1) . "</Width>";
  397. $package_schema .= "<Height>" . (floor($package->height * $length_factor) + 1) . "</Height>";
  398. $package_schema .= "</Dimensions>";
  399. }
  400. $size = $package->length * $length_factor + 2 * $length_factor * ($package->width + $package->height);
  401. $weight = max(1, $package->weight * $weight_factor);
  402. $package_schema .= "<PackageWeight>";
  403. $package_schema .= "<UnitOfMeasurement>";
  404. $package_schema .= "<Code>" . $units . "</Code>";
  405. $package_schema .= "<Description>" . $unit_name . "</Description>";
  406. $package_schema .= "</UnitOfMeasurement>";
  407. $package_schema .= "<Weight>" . number_format($weight, 1, '.', '') . "</Weight>";
  408. $package_schema .= "</PackageWeight>";
  409. if ($size > 130 && $size <= 165) {
  410. $package_schema .= "<LargePackageIndicator/>";
  411. }
  412. $package_schema .= "<PackageServiceOptions>";
  413. $package_schema .= "<InsuredValue>";
  414. $package_schema .= "<CurrencyCode>" . variable_get('uc_currency_code', 'USD') . "</CurrencyCode>";
  415. $package_schema .= "<MonetaryValue>" . number_format($package->value, 2, '.', '') . "</MonetaryValue>";
  416. $package_schema .= "</InsuredValue>";
  417. $package_schema .= "</PackageServiceOptions>";
  418. $package_schema .= "</Package>";
  419. }
  420. }
  421. $schema = uc_ups_access_request() . "
  422. <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  423. <ShipmentConfirmRequest xml:lang=\"en-US\">
  424. <Request>
  425. <TransactionReference>
  426. <CustomerContext>Complex Rate Request</CustomerContext>
  427. <XpciVersion>1.0001</XpciVersion>
  428. </TransactionReference>
  429. <RequestAction>ShipConfirm</RequestAction>
  430. <RequestOption>validate</RequestOption>
  431. </Request>
  432. <Shipment>";
  433. $schema .= "<Shipper>";
  434. $schema .= "<Name>" . $store['name'] . "</Name>";
  435. $schema .= "<ShipperNumber>" . variable_get('uc_ups_shipper_number', '') . "</ShipperNumber>";
  436. if ($store['phone']) {
  437. $schema .= "<PhoneNumber>" . $store['phone'] . "</PhoneNumber>";
  438. }
  439. if ($store['fax']) {
  440. $schema .= "<FaxNumber>" . $store['fax'] . "</FaxNumber>";
  441. }
  442. if ($store['email']) {
  443. $schema .= "<EMailAddress>" . $store['email'] . "</EMailAddress>";
  444. }
  445. $schema .= "<Address>";
  446. $schema .= "<AddressLine1>" . $store['street1'] . "</AddressLine1>";
  447. if ($store['street2']) {
  448. $schema .= "<AddressLine2>" . $store['street2'] . "</AddressLine2>";
  449. }
  450. $schema .= "<City>" . $store['city'] . "</City>";
  451. $schema .= "<StateProvinceCode>$shipper_zone</StateProvinceCode>";
  452. $schema .= "<PostalCode>$shipper_zip</PostalCode>";
  453. $schema .= "<CountryCode>$shipper_country</CountryCode>";
  454. $schema .= "</Address>";
  455. $schema .= "</Shipper>";
  456. $schema .= "<ShipTo>";
  457. $schema .= "<CompanyName>" . $destination->company . "</CompanyName>";
  458. $schema .= "<AttentionName>" . $destination->first_name . ' ' . $destination->last_name . "</AttentionName>";
  459. $schema .= "<PhoneNumber>" . $destination->phone . "</PhoneNumber>";
  460. $schema .= "<EMailAddress>" . $destination->email . "</EMailAddress>";
  461. $schema .= "<Address>";
  462. $schema .= "<AddressLine1>" . $destination->street1 . "</AddressLine1>";
  463. if ($destination->street2) {
  464. $schema .= "<AddressLine2>" . $destination->street2 . "</AddressLine2>";
  465. }
  466. $schema .= "<City>" . $destination->city . "</City>";
  467. $schema .= "<StateProvinceCode>$shipto_zone</StateProvinceCode>";
  468. $schema .= "<PostalCode>$shipto_zip</PostalCode>";
  469. $schema .= "<CountryCode>$shipto_country</CountryCode>";
  470. if ($destination->residential) {
  471. $schema .= "<ResidentialAddressIndicator/>";
  472. }
  473. $schema .= "</Address>";
  474. $schema .= "</ShipTo>";
  475. $schema .= "<ShipFrom>";
  476. $schema .= "<CompanyName>" . $origin->company . "</CompanyName>";
  477. $schema .= "<AttentionName>" . $origin->first_name . ' ' . $origin->last_name . "</AttentionName>";
  478. $schema .= "<PhoneNumber>" . $origin->phone . "</PhoneNumber>";
  479. $schema .= "<EMailAddress>" . $origin->email . "</EMailAddress>";
  480. $schema .= "<Address>";
  481. $schema .= "<AddressLine1>" . $origin->street1 . "</AddressLine1>";
  482. if ($origin->street2) {
  483. $schema .= "<AddressLine2>" . $origin->street2 . "</AddressLine2>";
  484. }
  485. $schema .= "<City>" . $origin->city . "</City>";
  486. $schema .= "<StateProvinceCode>$shipfrom_zone</StateProvinceCode>";
  487. $schema .= "<PostalCode>$shipfrom_zip</PostalCode>";
  488. $schema .= "<CountryCode>$shipfrom_country</CountryCode>";
  489. $schema .= "</Address>";
  490. $schema .= "</ShipFrom>";
  491. $schema .= "<PaymentInformation>";
  492. $schema .= "<Prepaid>";
  493. $schema .= "<BillShipper>";
  494. $schema .= "<AccountNumber>$account</AccountNumber>";
  495. $schema .= "</BillShipper>";
  496. $schema .= "</Prepaid>";
  497. $schema .= "</PaymentInformation>";
  498. if (variable_get('uc_ups_negotiated_rates', FALSE)) {
  499. $schema .= "<RateInformation>
  500. <NegotiatedRatesIndicator/>
  501. </RateInformation>";
  502. }
  503. $schema .= "<Service>";
  504. $schema .= "<Code>{$service['code']}</Code>";
  505. $schema .= "<Description>{$service['description']}</Description>";
  506. $schema .= "</Service>";
  507. $schema .= $package_schema;
  508. $schema .= "</Shipment>";
  509. $schema .= "<LabelSpecification>";
  510. $schema .= "<LabelPrintMethod>";
  511. $schema .= "<Code>GIF</Code>";
  512. $schema .= "</LabelPrintMethod>";
  513. $schema .= "<LabelImageFormat>";
  514. $schema .= "<Code>GIF</Code>";
  515. $schema .= "</LabelImageFormat>";
  516. $schema .= "</LabelSpecification>";
  517. $schema .= "</ShipmentConfirmRequest>";
  518. return $schema;
  519. }
  520. /**
  521. * Last chance for user to review shipment.
  522. *
  523. * @see uc_ups_confirm_shipment_submit()
  524. * @see theme_uc_ups_confirm_shipment()
  525. * @ingroup forms
  526. */
  527. function uc_ups_confirm_shipment($form, &$form_state, $order) {
  528. $form['digest'] = array(
  529. '#type' => 'hidden',
  530. '#value' => $_SESSION['ups']['digest']
  531. );
  532. $form['actions'] = array('#type' => 'actions');
  533. $form['actions']['submit'] = array(
  534. '#type' => 'submit',
  535. '#value' => t('Request Pickup')
  536. );
  537. return $form;
  538. }
  539. /**
  540. * Displays final shipment information for review.
  541. *
  542. * @see uc_ups_confirm_shipment()
  543. * @ingroup themeable
  544. */
  545. function theme_uc_ups_confirm_shipment($variables) {
  546. $form = $variables['form'];
  547. $output = '<div class="shipping-address"><b>' . t('Ship from:') . '</b><br />';
  548. $output .= uc_address_format(
  549. check_plain($_SESSION['ups']['origin']->first_name),
  550. check_plain($_SESSION['ups']['origin']->last_name),
  551. check_plain($_SESSION['ups']['origin']->company),
  552. check_plain($_SESSION['ups']['origin']->street1),
  553. check_plain($_SESSION['ups']['origin']->street2),
  554. check_plain($_SESSION['ups']['origin']->city),
  555. check_plain($_SESSION['ups']['origin']->zone),
  556. check_plain($_SESSION['ups']['origin']->postal_code),
  557. check_plain($_SESSION['ups']['origin']->country)
  558. );
  559. $output .= '<br />' . check_plain($_SESSION['ups']['origin']->email);
  560. $output .= '</div>';
  561. $output .= '<div class="shipping-address"><b>' . t('Ship to:') . '</b><br />';
  562. $output .= uc_address_format(
  563. check_plain($_SESSION['ups']['destination']->first_name),
  564. check_plain($_SESSION['ups']['destination']->last_name),
  565. check_plain($_SESSION['ups']['destination']->company),
  566. check_plain($_SESSION['ups']['destination']->street1),
  567. check_plain($_SESSION['ups']['destination']->street2),
  568. check_plain($_SESSION['ups']['destination']->city),
  569. check_plain($_SESSION['ups']['destination']->zone),
  570. check_plain($_SESSION['ups']['destination']->postal_code),
  571. check_plain($_SESSION['ups']['destination']->country)
  572. );
  573. $output .= '<br />' . check_plain($_SESSION['ups']['destination']->email);
  574. $output .= '</div>';
  575. $output .= '<div class="shipment-data">';
  576. $method = uc_ups_uc_shipping_method();
  577. $output .= '<b>' . $method['ups']['quote']['accessorials'][$_SESSION['ups']['service']] . '</b><br />';
  578. $output .= '<i>' . check_plain($_SESSION['ups']['rate']['type']) . '</i>: ' . theme('uc_price', array('price' => $_SESSION['ups']['rate']['amount'])) . ' (' . check_plain($_SESSION['ups']['rate']['currency']) . ') -- ';
  579. $output .= '<i>' . t('Paid') . '</i>: ' . $_SESSION['ups']['paid'] . '<br />';
  580. $ship_date = $_SESSION['ups']['ship_date'];
  581. $output .= 'Ship date: ' . format_date(gmmktime(12, 0, 0, $ship_date['month'], $ship_date['day'], $ship_date['year']), 'uc_store');
  582. $exp_delivery = $_SESSION['ups']['expected_delivery'];
  583. $output .= '<br />Expected delivery: ' . format_date(gmmktime(12, 0, 0, $exp_delivery['month'], $exp_delivery['day'], $exp_delivery['year']), 'uc_store');
  584. $output .= "</div>\n<br style=\"clear: both;\" />";
  585. $output .= drupal_render_children($form);
  586. return $output;
  587. }
  588. /**
  589. * Generates label and schedules pickup of the shipment.
  590. *
  591. * @see uc_ups_confirm_shipment()
  592. */
  593. function uc_ups_confirm_shipment_submit($form, &$form_state) {
  594. // Request pickup using parameters in form.
  595. $order_id = $_SESSION['ups']['order_id'];
  596. $packages = array_keys($_SESSION['ups']['packages']);
  597. $request = uc_ups_request_pickup($form_state['values']['digest'], $order_id, $packages);
  598. $result = drupal_http_request(variable_get('uc_ups_connection_address', 'https://wwwcie.ups.com/ups.app/xml/') . 'ShipAccept', array(
  599. 'method' => 'POST',
  600. 'data' => $request,
  601. ));
  602. $response = new SimpleXMLElement($result->data);
  603. $code = (string) $response->Response->ResponseStatusCode;
  604. if ($code == 0) { // failed request
  605. $error = $response->Response->Error;
  606. $error_severity = (string) $error->ErrorSeverity;
  607. $error_code = (string) $error->ErrorCode;
  608. $error_description = (string) $error->ErrorDescription;
  609. drupal_set_message(t('(@severity error @code) @description', array('@severity' => $error_severity, '@code' => $error_code, '@description' => $error_description)), 'error');
  610. if ($error_severity == 'HardError') {
  611. $form_state['redirect'] = 'admin/store/orders/' . $order_id . '/shipments/ups/' . implode('/', $packages);
  612. return;
  613. }
  614. }
  615. $shipment = new stdClass();
  616. $shipment->order_id = $order_id;
  617. $shipment->origin = clone $_SESSION['ups']['origin'];
  618. $shipment->destination = clone $_SESSION['ups']['destination'];
  619. $shipment->packages = $_SESSION['ups']['packages'];
  620. $shipment->shipping_method = 'ups';
  621. $shipment->accessorials = $_SESSION['ups']['service'];
  622. $shipment->carrier = t('UPS');
  623. // if NegotiatedRates exist, quote based on those, otherwise, use TotalCharges
  624. if (isset($response->ShipmentResults->ShipmentCharges)) {
  625. $charge = $response->ShipmentResults->ShipmentCharges->TotalCharges;
  626. if (isset($response->ShipmentResults->NegotiatedRates)) {
  627. $charge = $response->ShipmentResults->NegotiatedRates->NetSummaryCharges->GrandTotal;
  628. }
  629. }
  630. $cost = (string) $charge->MonetaryValue;
  631. $shipment->cost = $cost;
  632. $shipment->tracking_number = (string) $response->ShipmentResults->ShipmentIdentificationNumber;
  633. $ship_date = $_SESSION['ups']['ship_date'];
  634. $shipment->ship_date = gmmktime(12, 0, 0, $ship_date['month'], $ship_date['day'], $ship_date['year']);
  635. $exp_delivery = $_SESSION['ups']['expected_delivery'];
  636. $shipment->expected_delivery = gmmktime(12, 0, 0, $exp_delivery['month'], $exp_delivery['day'], $exp_delivery['year']);
  637. foreach ($response->ShipmentResults->PackageResults as $package_results) {
  638. $package =& current($shipment->packages);
  639. $package->tracking_number = (string) $package_results->TrackingNumber;
  640. $label_image = (string) $package_results->LabelImage->GraphicImage;
  641. // Save the label
  642. $directory = 'public://ups_labels';
  643. if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
  644. $label_path = $directory . '/label-' . $package->tracking_number . '.gif';
  645. if ($label_file = file_save_data(base64_decode($label_image), $label_path, FILE_EXISTS_REPLACE)) {
  646. file_usage_add($label_file, 'uc_shipping', 'package', $package->package_id);
  647. $package->label_image = $label_file;
  648. }
  649. else {
  650. drupal_set_message(t('Could not open a file to save the label image.'), 'error');
  651. }
  652. }
  653. else {
  654. drupal_set_message(t('Could not find or create the directory %directory in the file system path.', array('%directory' => $directory)), 'error');
  655. }
  656. unset($package);
  657. next($shipment->packages);
  658. }
  659. uc_shipping_shipment_save($shipment);
  660. unset($_SESSION['ups']);
  661. $form_state['redirect'] = 'admin/store/orders/' . $order_id . '/shipments';
  662. }
  663. /**
  664. * Constructs an XML label and pickup request.
  665. *
  666. * @param string $digest
  667. * Base-64 encoded shipment request.
  668. * @param int $order_id
  669. * The order id of the shipment.
  670. * @param array $packages
  671. * An array of package ids to be shipped.
  672. *
  673. * @return string
  674. * ShipmentAcceptRequest XML document to send to UPS.
  675. */
  676. function uc_ups_request_pickup($digest, $order_id = 0, $packages = array()) {
  677. $packages = (array) $packages;
  678. $schema = uc_ups_access_request();
  679. $schema .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  680. <ShipmentAcceptRequest>
  681. <Request>
  682. <RequestAction>ShipAccept</RequestAction>";
  683. if ($order_id || count($packages)) {
  684. $schema .= "\n<TransactionReference>
  685. <CustomerContext>";
  686. if ($order_id) {
  687. $schema .= "<OrderId>" . $order_id . "</OrderId>\n";
  688. }
  689. foreach ($packages as $pkg_id) {
  690. $schema .= "<PackageId>" . $pkg_id . "</PackageId>\n";
  691. }
  692. $schema .= "</CustomerContext>\n</TransactionReference>\n";
  693. }
  694. $schema .= " </Request>
  695. <ShipmentDigest>" . $digest . "</ShipmentDigest>
  696. </ShipmentAcceptRequest>";
  697. return $schema;
  698. }
  699. /**
  700. * Displays the shipping label for printing.
  701. *
  702. * Each argument is a component of the file path to the image.
  703. *
  704. * @ingroup themeable
  705. */
  706. function theme_uc_ups_label_image() {
  707. $args = explode('/', $_GET['q'], 8);
  708. if (count($args) != 8) {
  709. return MENU_NOT_FOUND;
  710. }
  711. $image_path = file_create_url(file_stream_wrapper_uri_normalize($args[7]));
  712. $output = <<<EOLABEL
  713. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 3.2//EN">
  714. <html>
  715. <head>
  716. <title>View/Print Label</title>
  717. <style>
  718. .small-text {font-size: 80%;}
  719. .large-text {font-size: 115%;}
  720. </style>
  721. </head>
  722. <body bgcolor="#FFFFFF">
  723. <table border="0" cellpadding="0" cellspacing="0" width="600"><tr>
  724. <td height="410" align="left" valign="top">
  725. <b class="large-text">View/Print Label</b>
  726. &nbsp;<br />
  727. <ol class="small-text"> <li><b>Print the label:</b> &nbsp;
  728. Select Print from the File menu in this browser window to print the label below.<br /><br /><li><b>
  729. Fold the printed label at the dotted line.</b> &nbsp;
  730. Place the label in a UPS Shipping Pouch. If you do not have a pouch, affix the folded label using clear plastic shipping tape over the entire label.<br /><br /><li><b>GETTING YOUR SHIPMENT TO UPS<br />
  731. Customers without a Daily Pickup</b><ul><li>Ground, 3 Day Select, and Standard to Canada shipments must be dropped off at an authorized UPS location, or handed to a UPS driver. Pickup service is not available for these services. To find the nearest drop-off location, select the Drop-off icon from the UPS tool bar.<li>
  732. Air shipments (including Worldwide Express and Expedited) can be picked up or dropped off. To schedule a pickup, or to find a drop-off location, select the Pickup or Drop-off icon from the UPS tool bar. </ul> <br />
  733. <b>Customers with a Daily Pickup</b><ul><li>
  734. Your driver will pickup your shipment(s) as usual. </ul>
  735. </ol></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="600">
  736. <tr>
  737. <td class="small-text" align="left" valign="top">
  738. &nbsp;&nbsp;&nbsp;
  739. FOLD HERE</td>
  740. </tr>
  741. <tr>
  742. <td align="left" valign="top"><hr />
  743. </td>
  744. </tr>
  745. </table>
  746. <table>
  747. <tr>
  748. <td height="10">&nbsp;
  749. </td>
  750. </tr>
  751. </table>
  752. <table border="0" cellpadding="0" cellspacing="0" width="650" ><tr>
  753. <td align="left" valign="top">
  754. <img src="$image_path" height="392" width="672">
  755. </td>
  756. </tr></table>
  757. </body>
  758. </html>
  759. EOLABEL;
  760. print $output;
  761. exit();
  762. }