· 9 years ago · Jan 19, 2017, 06:08 PM
1package com.saic.wyoming.createsalesorder;
2
3import java.io.IOException;
4import java.math.BigDecimal;
5import java.sql.CallableStatement;
6import java.sql.Connection;
7import java.sql.SQLException;
8import java.sql.Savepoint;
9import java.sql.Timestamp;
10import java.sql.Types;
11import java.text.SimpleDateFormat;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Date;
15import java.util.HashMap;
16import java.util.List;
17import java.util.Set;
18import java.util.TreeSet;
19
20import javax.servlet.ServletException;
21
22import org.apache.commons.lang.StringUtils;
23import org.apache.commons.lang.time.DateUtils;
24import org.apache.log4j.Logger;
25import org.hibernate.Hibernate;
26import org.hibernate.HibernateException;
27import org.hibernate.Query;
28import org.hibernate.Session;
29import org.hibernate.criterion.Restrictions;
30import org.hibernate.type.StringType;
31import org.openbravo.base.exception.OBException;
32import org.openbravo.base.provider.OBProvider;
33import org.openbravo.base.session.OBPropertiesProvider;
34import org.openbravo.dal.core.OBContext;
35import org.openbravo.dal.core.SessionHandler;
36import org.openbravo.dal.service.OBCriteria;
37import org.openbravo.dal.service.OBDal;
38import org.openbravo.dal.service.OBQuery;
39import org.openbravo.database.ConnectionProvider;
40import org.openbravo.erpCommon.utility.OBError;
41import org.openbravo.exception.NoConnectionAvailableException;
42import org.openbravo.materialmgmt.ReservationUtils;
43import org.openbravo.model.ad.access.User;
44import org.openbravo.model.ad.system.Client;
45import org.openbravo.model.ad.utility.Sequence;
46import org.openbravo.model.common.businesspartner.BusinessPartner;
47import org.openbravo.model.common.businesspartner.Location;
48import org.openbravo.model.common.currency.Currency;
49import org.openbravo.model.common.enterprise.DocumentType;
50import org.openbravo.model.common.enterprise.Organization;
51import org.openbravo.model.common.enterprise.OrganizationInformation;
52import org.openbravo.model.common.enterprise.Warehouse;
53import org.openbravo.model.common.geography.City;
54import org.openbravo.model.common.geography.Country;
55import org.openbravo.model.common.geography.Region;
56import org.openbravo.model.common.order.Order;
57import org.openbravo.model.common.order.OrderDiscount;
58import org.openbravo.model.common.order.OrderLine;
59import org.openbravo.model.common.plm.Product;
60import org.openbravo.model.common.plm.ProductOrg;
61import org.openbravo.model.common.uom.UOM;
62import org.openbravo.model.financialmgmt.calendar.Calendar;
63import org.openbravo.model.financialmgmt.calendar.NonBusinessDay;
64import org.openbravo.model.financialmgmt.payment.FIN_PaymentMethod;
65import org.openbravo.model.financialmgmt.payment.PaymentTerm;
66import org.openbravo.model.financialmgmt.tax.TaxRate;
67import org.openbravo.model.pricing.discount.Discount;
68import org.openbravo.model.pricing.pricelist.PriceList;
69import org.openbravo.model.pricing.pricelist.PriceListVersion;
70import org.openbravo.scheduling.ProcessBundle;
71import org.openbravo.scheduling.ProcessContext;
72import org.openbravo.scheduling.ProcessLogger;
73
74import com.saic.wyoming.SAICError;
75import com.saic.wyoming.SAICError.ErrorType;
76import com.saic.wyoming.SAICErrorCollection;
77import com.saic.wyoming.alert.AlertUtils;
78import com.saic.wyoming.autorec.AutoRecService;
79import com.saic.wyoming.createsalesorder.structures.SOLoadObjects;
80import com.saic.wyoming.criteria.PIDUtil;
81import com.saic.wyoming.crossdock.CrossdockCheck;
82import com.saic.wyoming.crossdock.CrossdockFlag;
83import com.saic.wyoming.data.Contract;
84import com.saic.wyoming.data.CustomerDodaac;
85import com.saic.wyoming.data.CustomerPartner;
86import com.saic.wyoming.data.CustomerRFQ;
87import com.saic.wyoming.data.DOMAIN;
88import com.saic.wyoming.data.OEMAAllianceProgram;
89import com.saic.wyoming.data.Program;
90import com.saic.wyoming.data.ProposalItem;
91import com.saic.wyoming.data.PurchItemDesc;
92import com.saic.wyoming.data.PurchaseAgreementItem;
93import com.saic.wyoming.data.RFP;
94import com.saic.wyoming.data.RefData;
95import com.saic.wyoming.data.RefDataName;
96import com.saic.wyoming.data.RefDataValue;
97import com.saic.wyoming.data.RequestItem;
98import com.saic.wyoming.data.SalesOrderLoadRules;
99import com.saic.wyoming.data.SelectedBids;
100import com.saic.wyoming.data.com.saic.wyoming.crossdock.CustomerConfig;
101import com.saic.wyoming.exception.SalesOrderLoadException;
102import com.saic.wyoming.importProcess.CEMASFollowUpLoader;
103import com.saic.wyoming.importProcess.CustomerRFQLoader;
104import com.saic.wyoming.importProcess.CustomerReceiptLoader;
105import com.saic.wyoming.importProcess.MessageQueueProcessorJob;
106import com.saic.wyoming.messaging.castor.Cancellation;
107import com.saic.wyoming.messaging.castor.CustomerSO;
108import com.saic.wyoming.messaging.castor.CustomerSOLineItem;
109import com.saic.wyoming.messaging.castor.HeaderAddress;
110import com.saic.wyoming.messaging.castor.HeaderRef;
111import com.saic.wyoming.messaging.castor.LineAddress;
112import com.saic.wyoming.messaging.castor.LineRef;
113import com.saic.wyoming.messaging.castor.WyomingMessage;
114import com.saic.wyoming.messaging.castor.WyomingMessageChoice;
115import com.saic.wyoming.messaging.castor.types.SystemType;
116import com.saic.wyoming.order.DemandHistoryManager;
117import com.saic.wyoming.order.OrderPostHelper;
118import com.saic.wyoming.order.OrderStatusUpdater;
119import com.saic.wyoming.order.OrderUtil;
120import com.saic.wyoming.order.StorefrontUtils;
121import com.saic.wyoming.process.SAICMessageProcessResult;
122import com.saic.wyoming.process.SAICProcessResult;
123import com.saic.wyoming.props.ApplicationProperties;
124import com.saic.wyoming.props.ApplicationProperty;
125import com.saic.wyoming.transmission.TransmissionType;
126import com.saic.wyoming.transmission.TransmissionUtils;
127import com.saic.wyoming.utils.AlertUtil;
128import com.saic.wyoming.utils.ClauseUtil;
129import com.saic.wyoming.utils.CustomerUtil;
130import com.saic.wyoming.utils.DateParser;
131import com.saic.wyoming.utils.DateUtil;
132import com.saic.wyoming.utils.FrontEndHelper;
133import com.saic.wyoming.utils.NotesUtil;
134import com.saic.wyoming.utils.OBUtils;
135import com.saic.wyoming.utils.OrgUtil;
136import com.saic.wyoming.utils.ProcessEUtil;
137import com.saic.wyoming.utils.SWMaximoUtil;
138import com.saic.wyoming.utils.SalesOrderLoadRuleActionProvider;
139import com.saic.wyoming.utils.StatusHelper;
140import com.saic.wyoming.utils.StockUtils;
141import com.saic.wyoming.utils.TriggerWorkflowHelper;
142import com.saic.wyoming.utils.refdata.RefDataNames;
143import com.saic.wyoming.utils.refdata.RefDataObjectType;
144import com.saic.wyoming.utils.refdata.RefDataSource;
145import com.saic.wyoming.utils.refdata.RefDataUtil;
146import com.saic.wyoming.utils.refdata.RefDataValues;
147
148/*
149 * @author rohit.nagamalla
150 * @author shawn.m.laubach
151 *
152 */
153public class SalesOrder extends MessageQueueProcessorJob {
154
155 public static double NUM_MS_IN_DAY = 8.64E7;
156 private static final Set<Integer> OB_PRIORITY = new TreeSet<Integer>(
157 Arrays.asList(new Integer[] { 3, 5, 7 }));
158 private static final Set<String> MILSTRIP_PRIORITY_HIGH = new TreeSet<String>(
159 Arrays.asList(new String[] { "01", "02", "03" }));
160 private static final Set<String> MILSTRIP_PRIORITY_MEDIUM = new TreeSet<String>(
161 Arrays.asList(new String[] { "04", "05", "06", "07", "08" }));
162 private static final String MILSTRIP_NO_PRIORITY = "00";
163
164 private static final Set<String> MILSTRIP_PRIORITY_LOW = new TreeSet<String>(
165 Arrays.asList(new String[] { "09", "10", "11", "12", "13", "14", "15" }));
166 private static final String TSI_FMS_ORG_ID = "20122";
167 private SimpleDateFormat dateFormat = null;
168
169 static final long serialVersionUID = 0;
170 private ProcessContext context = null;
171 private ConnectionProvider connectionProvider = null;
172 private Connection connection = null;
173
174 public Timestamp instanceTime = null;
175
176 private Logger log = Logger.getLogger(this.getClass());
177 private ProcessLogger logger = null;
178 private int orderCreatedCounter;
179 private int errorCounter;
180
181 private static final String CAT_1 = "CAT1";
182 private static final String CAT_2 = "CAT2";
183 private static final String CAT_3 = "CAT3";
184 private static final String DODX_MISMATCH_ALERT_ID = "2037";
185 private static final String SAIC_ALERT = "2020";
186 private static final String POLCHEM_BUYER_ROLE_ID = "2E53126C54176C99E0536242A8C0CABB";
187
188 /**
189 * The code inside this function will be executed when the process is scheduled through the
190 * Process Scheduler
191 *
192 * @param bundle
193 * the process' parameters, security and contextual information
194 * @return
195 * @throws Exception
196 * if an error occurs executing the process
197 */
198 public SAICMessageProcessResult processMessage(ProcessBundle pb, String sourceSystem,
199 WyomingMessage wm) {
200 _bundle = pb;
201 // clear log for each running instance.
202 logger = pb.getLogger();
203 log.error("Start Sales Order");
204 String formatString = OBPropertiesProvider.getInstance().getOpenbravoProperties()
205 .getProperty("dateFormat.java");
206 dateFormat = new SimpleDateFormat(formatString);
207
208 try {
209 instanceTime = new Timestamp(System.currentTimeMillis());
210
211 // Get the Connection
212 connectionProvider = pb.getConnection();
213 connection = connectionProvider.getConnection();
214
215 // Set the OBContext by the current contextual information
216 context = pb.getContext();
217 OBContext.setOBContext(context.getUser(), context.getRole(), context.getClient(),
218 context.getOrganization());
219
220 WyomingMessageChoice choice = wm.getWyomingMessageChoice();
221 if (choice.getCustomerSO() != null) {
222 CustomerSO so = choice.getCustomerSO();
223 int flag = 0;
224 // Here we are checking if there are duplicate line numbers. If duplicate lines are found
225 // then error out and don't load order
226 List<String> lineNos = new ArrayList<String>();
227 for (CustomerSOLineItem testLine : so.getCustomerSOLineItems().getCustomerSOLineItem()) {
228 String testLineNo = testLine.getLineNumber();
229 if (lineNos.contains(testLineNo))
230 throw new OBException("Duplicate line(s) detected"); // found a duplicate so throw
231 // exception
232 else
233 lineNos.add(testLineNo);
234 }
235
236 for (CustomerSOLineItem line : so.getCustomerSOLineItems().getCustomerSOLineItem()) {
237 String headInvpull = so.getInvPull();
238 String lineInvpull = line.getInvPull();
239
240 if (headInvpull == null)
241 break; // skip check if invPull not specified at header - LK 1/13/13
242
243 // Create an Order Line
244 if (headInvpull.equalsIgnoreCase(lineInvpull)) {
245 flag = 0;
246 } else {
247 flag = 1;
248 log.error("INVpull error: INVpull doesn't match with header and line");
249 logger.logln("INVpull error: INVpull doesn't match with header and line");
250 // @TODO - Place alert here
251 break;
252 }
253 }
254 if (flag == 0)
255 SalesOrderSynch(wm.getSource(), so);
256 } else if (choice.getCancellation() != null) {
257 CancelOrder(choice.getCancellation());
258 } else {
259 log.error("This type of order is not identified: " + choice);
260 SAICError err = new SAICError("This type of order is not identified: " + choice,
261 ErrorType.UNHANDLED_MESSAGE_TYPE);
262 return new SAICMessageProcessResult(0, new SAICErrorCollection(err));
263 }
264 return new SAICMessageProcessResult(1);
265 } catch (OBException obe) {
266 throw obe;
267 } catch (Exception e) {
268 log.error(e.getMessage(), e);
269 logger.logln("Error processessing message: " + e.getMessage());
270 TransmissionUtils.createTransmissionError("Error processing message", e);
271 throw new OBException(e.getMessage(), e);
272 } finally {
273 Timestamp endTime = new Timestamp(System.currentTimeMillis());
274
275 log.debug("TDS Sales Order job started at: " + instanceTime);
276 log.debug("TDS Sales Order job ended at: " + endTime);
277
278 log.info(orderCreatedCounter + " Order(s) were created successfully. " + errorCounter
279 + " error(s) were encountered.");
280 logger.log(orderCreatedCounter + " Order(s) were created successfully. " + errorCounter
281 + " error(s) were encountered.");
282
283 // adding this to check for process monitor messages.
284 pb.setLog(logger);
285 }
286 }
287
288 private void checkDuplicatedDocs(CustomerSO so, BusinessPartner bp) {
289 // WPS-893: don't do the checks for Single Item Reqs
290 String strSingleItemReqs = so.getDeliveryOrder();
291 if (strSingleItemReqs != null && ("Single Item Reqs".equalsIgnoreCase(strSingleItemReqs)))
292 return;
293 // Search for duplicate contract number +
294 OBCriteria<Order> duplicatedOrders = OBDal.getInstance().createCriteria(Order.class);
295 duplicatedOrders.add(Restrictions.disjunction()
296 .add(Restrictions.or(Restrictions.eq(Order.PROPERTY_SCDELORD, so.getDeliveryOrder()),
297 Restrictions.eq(Order.PROPERTY_SCDELORD, so.getContractNumber())))
298 .add(Restrictions.or(
299 Restrictions.and(Restrictions.eq(Order.PROPERTY_ORDERREFERENCE, so.getDeliveryOrder()),
300 Restrictions.isNull(Order.PROPERTY_SCDELORD)),
301 Restrictions.and(Restrictions.eq(Order.PROPERTY_ORDERREFERENCE, so.getContractNumber()),
302 Restrictions.isNull(Order.PROPERTY_SCDELORD)))));
303 duplicatedOrders.add(Restrictions.ne(Order.PROPERTY_DOCUMENTSTATUS, "VO"));
304 duplicatedOrders.add(Restrictions.eq(Order.PROPERTY_BUSINESSPARTNER, bp));
305
306 List<Order> existingOrders = duplicatedOrders.list();
307 if (existingOrders.size() > 0) {
308 throw new OBException("Duplicate order(s) detected");
309 }
310 // add search for order line
311 OBCriteria<OrderLine> duplicatedOrdersInLines = OBDal.getInstance()
312 .createCriteria(OrderLine.class);
313 duplicatedOrdersInLines.add(Restrictions.disjunction()
314 .add(Restrictions.or(Restrictions.eq(OrderLine.PROPERTY_SCDELORD, so.getDeliveryOrder()),
315 Restrictions.eq(OrderLine.PROPERTY_SCDELORD, so.getContractNumber()))));
316 duplicatedOrdersInLines.createAlias(OrderLine.PROPERTY_SALESORDER, "o");
317 duplicatedOrdersInLines.add(Restrictions.ne("o." + Order.PROPERTY_DOCUMENTSTATUS, "VO"));
318 duplicatedOrdersInLines.add(Restrictions.eq("o." + Order.PROPERTY_BUSINESSPARTNER, bp));
319 List<OrderLine> existingOrdersInLines = duplicatedOrdersInLines.list();
320 if (existingOrdersInLines.size() > 0) {
321 throw new OBException("Duplicate order(s) detected");
322 }
323 }
324
325 /**
326 * @param cancellation
327 * @return
328 * @throws Exception
329 */
330 private boolean CancelOrder(Cancellation cancellation) throws Exception {
331 String internalPONumber = "no PO Number found";
332
333 try {
334 if (connection == null || connection.isClosed())
335 connection = connectionProvider.getConnection();
336
337 internalPONumber = cancellation.getCustomerPO();
338 Product product = OBUtils.findProduct(cancellation.getSAICPartNumber());
339 double quantityCancelled = cancellation.getQuantityCancelled();
340 String unitOfMeasure = cancellation.getUnitOfMeasure();
341 String lineNumber = null;// cancellation.getLineNumber();
342
343 CallableStatement proc = connection.prepareCall("{CALL SAICCSO_CANCEL_ORDER(?,?,?,?,?,?,?)}");
344 proc.setString(1, internalPONumber);
345 proc.setString(2, product.getId());
346 proc.setString(3, lineNumber);
347 proc.setDouble(4, quantityCancelled);
348 proc.setString(5, unitOfMeasure);
349 proc.registerOutParameter(6, Types.NUMERIC);
350 proc.registerOutParameter(7, Types.NUMERIC);
351
352 proc.execute();
353
354 int orderCount = proc.getInt(6);
355 int orderLineCount = proc.getInt(7);
356 log.debug(orderCount + " orders canceled \n" + orderLineCount + " order lines canceled");
357
358 } catch (Exception e) {
359 errorCounter++;
360 log.error("Either the Line or The header is not found with the given PPO number", e);
361 logger.logln("Could not cancel order: " + internalPONumber + " - " + e.getMessage());
362 TransmissionUtils.createTransmissionError(
363 "Either the Line or The header is not found with the given PPO number", e);
364 throw new OBException("Either the Line or The header is not found with the given PPO number",
365 e);
366 }
367
368 return true;
369 }
370
371 /**
372 * @param so
373 * @throws Exception
374 */
375
376 private void SalesOrderSynch(SystemType source, CustomerSO so) throws Exception {
377 Order order = OBProvider.getInstance().get(Order.class);
378 String customerName = so.getCustomerName();
379 String customerCode = so.getCustomerCode();
380
381 log.debug("customerName from JMS ::" + customerName);
382 log.debug("customerCode from JMS ::" + customerCode);
383
384 BusinessPartner businessPartner = null;
385 Location billingAddress = null;
386 SOLoadObjects data = new SOLoadObjects();
387 try {
388
389 data = SalesOrderDao.findOrgPrgramCustomer(source, so, logger);
390 // Check if duplicate orders, based on the org tree
391 checkDuplicatedDocs(so, data.getBusinessPartner());
392
393 businessPartner = data.getBusinessPartner();
394
395 if (businessPartner == null) {
396 String msg = "Error occurred while loading business partner for order: " + customerName
397 + "[" + customerCode + "]";
398 throw new Exception(msg);
399 }
400 for (Location businessPartnerLoc : businessPartner.getBusinessPartnerLocationList()) {
401 if (!businessPartnerLoc.isActive())
402 continue;
403
404 billingAddress = businessPartnerLoc;
405 }
406 } catch (Exception exception) {
407 String msg = exception.getMessage();
408 log.error(msg, exception);
409 logger.logln(msg + exception.getMessage());
410 errorCounter++;
411 TransmissionUtils.createTransmissionError(msg, exception);
412 throw new OBException(msg, exception);
413 }
414
415 Location shipToAddress = null;
416 try {
417 String locationName = null;
418 String shippingAddressStreet = null;
419 String shippingAddressCity = null;
420 String shippingAddressRegion = null;
421 String shippingAddressPostalCode = null;
422 String shippingAddressCountry = null;
423
424 // Added these 3 fields to accommodate OEMA. Ship To address for OEMA is stored at the line
425 // level. So at header level, the fields would be null. The fields are populated at the line
426 // and passed to locationSynchronization method
427 String shippingAddress2 = null;
428 String shippingAddress3 = null;
429 String shippingLocationType = null;
430 String bpLocationId = null;
431 if (so.getShipTo() != null) {
432 locationName = so.getShipTo().getLocationName();
433 shippingAddressCountry = so.getShipTo().getCountry();
434 if (shippingAddressCountry == null || shippingAddressCountry == "") {
435 shippingAddressCountry = "US";
436 } else if (shippingAddressCountry.length() > 2) {
437 // The value in the XML is not a two digit country code. Assume it is the name of country
438 // and try to find the two digit code in database. - LK
439 OBCriteria<Country> ctryCriteria = OBDal.getInstance().createCriteria(Country.class);
440 ctryCriteria.add(Restrictions.eq(Country.PROPERTY_NAME, shippingAddressCountry));
441 List<Country> foundList = ctryCriteria.list();
442
443 if (foundList.size() > 0) // found matching country by name set code to variable
444 shippingAddressCountry = foundList.get(0).getISOCountryCode();
445 }
446
447 shippingAddressCity = so.getShipTo().getCity();
448 shippingAddressRegion = so.getShipTo().getState();
449 shippingAddressPostalCode = so.getShipTo().getPostalCode();
450 shippingAddressStreet = so.getShipTo().getAddress1();
451 bpLocationId = so.getShipTo().getBPLocationID();
452 }
453
454 if (locationName != null && !locationName.equals("")
455 || shippingAddressStreet != null && !shippingAddressStreet.equals("")
456 && shippingAddressCity != null && !shippingAddressCity.equals("")
457 && shippingAddressRegion != null && !shippingAddressRegion.equals("")
458 && shippingAddressPostalCode != null && !shippingAddressPostalCode.equals("")) {
459 shipToAddress = locationSynchronization(locationName, businessPartner,
460 shippingAddressStreet, shippingAddressCity, shippingAddressRegion,
461 shippingAddressPostalCode, shippingAddressCountry, shippingAddress2, shippingAddress3,
462 shippingLocationType, source, bpLocationId);
463 log.debug("setting vendor address using locationname");
464
465 } else if (!data.getOrganization().getName().contains("OEM")) { // Sets the Partner address
466 // by default shipto address
467 log.debug("setting vendor address as default ship to address");
468 setPartnerAddressByDefultShipToAddress(order, businessPartner);
469 shipToAddress = order.getDeliveryLocation();
470 }
471 // if the business partner of the location doesn't match the business partner on the
472 // order, then throw an error.
473 if (shipToAddress != null && shipToAddress.getBusinessPartner() != null
474 && !shipToAddress.getBusinessPartner().getId().equals(businessPartner.getId())) {
475 throw new SalesOrderLoadException("Location mismatch. Location code " + locationName
476 + " does not belong to business partner " + businessPartner.getSearchKey());
477 }
478 } catch (Exception exception) {
479 // System.out.println("EXCEPTION#6");
480 log.error("Error in creating Location Synchronization", exception);
481 logger.logln("Error in creating Location Synchronization: " + exception.getMessage());
482 errorCounter++;
483 TransmissionUtils.createTransmissionError("Error in creating Location Synchronization",
484 exception);
485 throw new OBException("Error in creating Location Synchronization", exception);
486 }
487
488 String internalPO = so.getInternalPONumber();
489
490 log.debug("internalPO :::" + internalPO);
491
492 boolean orderExists = false;
493 String transType = "";
494 try {
495 orderExists = getOrderIfExists(internalPO);
496
497 // GP - 03/17/2012 - separating "A0A" and "ATA" transactions
498
499 if (!orderExists && (SystemType.CEMAS.equals(source))) {
500 if ((so.getRequisitionNumber() != null)
501 && getCEMASOrderIfExists(so.getRequisitionNumber())) {
502
503 CEMASFollowUpLoader followuploader = new CEMASFollowUpLoader();
504 OBCriteria<Order> orderCriteria = OBDal.getInstance().createCriteria(Order.class);
505 orderCriteria.add(Restrictions.eq("scRequisitionNumber", so.getRequisitionNumber()));
506 final List<Order> orderList = orderCriteria.list();
507 final Order cemasOrder = orderList.get(0);
508 transType = so.getCEMASTransactionType();
509
510 if ("ATA".equals(transType)) {
511 // PO exists for this order
512 boolean ifPOExists = getPOIfExists(cemasOrder);
513 if (ifPOExists)
514 followuploader.createLPS_LPXxmlNoMsg(cemasOrder, transType);
515 else
516 // PO doesn't exist yet
517 followuploader.createAE1xmlNoMsg(cemasOrder, "BD");
518 }
519 return;
520 }
521 }
522 } catch (Exception e) {
523 log.error("Error encountered while checking for an existing order.", e);
524 logger.logln("Error encountered while checking for an existing order: " + e.getMessage());
525 errorCounter++;
526 TransmissionUtils
527 .createTransmissionError("Error encountered while checking for an existing order.", e);
528 return;
529 }
530
531 if ((!orderExists)) {
532
533 try {
534
535 String orderDel = so.getDeliveryOrder();
536 String orderRef = so.getPONumber();
537 String orderRFQ = so.getRFQNumber();
538
539 String employeeID = so.getEmployeeIDNumber();
540 if (employeeID != null) {
541 employeeID = employeeID.replaceAll("^0+", "");
542 }
543
544 if (businessPartner.isCustomer()) {
545 createOrder(order, so, businessPartner, shipToAddress, billingAddress, internalPO,
546 orderDel, orderRef, orderRFQ, employeeID, source, data);
547
548 log.debug("Order created. Attempting to apply clauses");
549
550 ClauseUtil.applySalesOrderClauses(order);
551
552 } else {
553 log.debug(businessPartner.getName() + " Is not a customer");
554 }
555 } catch (Exception exception) {
556 exception.printStackTrace();
557 log.error("Error occurred in Openbravo while creating Order header.", exception);
558 logger.logln("Error encountered while creating Order header: " + exception.getMessage());
559 errorCounter++;
560 TransmissionUtils.createTransmissionError(
561 "Error occurred in Openbravo while creating Order header.", exception);
562 throw new OBException("Error occurred in Openbravo while creating Order header.",
563 exception);
564 }
565 } else {
566 log.error("Error occurred in Openbravo while creating Order header. Order '" + internalPO
567 + "' already exists in DB.");
568 logger.logln("Error encountered while creating Order header: Order '" + internalPO
569 + "' already exists in DB.");
570 errorCounter++;
571
572 }
573
574 }
575
576 public boolean getPOIfExists(String strReqNumber) throws Exception {
577 // GP 01/19/2012 CEMAS processing - check if PO exists for SO
578 boolean ifExists = false;
579 OBCriteria<Order> orderCriteria = OBDal.getInstance().createCriteria(Order.class);
580 orderCriteria.add(Restrictions.eq("scRequisitionNumber", strReqNumber));
581 final List<Order> orderList = orderCriteria.list();
582 final Order cemasOrder = orderList.get(0);
583
584 OrderLine SOorderline = OBDal.getInstance().get(OrderLine.class,
585 cemasOrder.getOrderLineList().get(0).getId());
586
587 OBCriteria<OrderLine> POorderlineCriteria = OBDal.getInstance().createCriteria(OrderLine.class);
588 POorderlineCriteria.add(Restrictions.eq("sOPOReference", SOorderline));
589 OrderLine poOrderline = (OrderLine) POorderlineCriteria.uniqueResult();
590 if (poOrderline != null)
591 ifExists = true;
592
593 return ifExists;
594 }
595
596 public boolean getPOIfExists(Order cemasOrder) throws Exception {
597 // GP 01/19/2012 CEMAS processing - check if PO exists for SO
598 boolean ifExists = false;
599 OrderLine soOrderLine = OBDal.getInstance().get(OrderLine.class,
600 cemasOrder.getOrderLineList().get(0).getId());
601
602 OBCriteria<OrderLine> ordLineCriteria = OBDal.getInstance().createCriteria(OrderLine.class);
603 ordLineCriteria.add(Restrictions.eq(OrderLine.PROPERTY_SOPOREFERENCE, soOrderLine));
604
605 List<OrderLine> poLines = ordLineCriteria.list();
606 // if (poLines.size() == 1)
607 // return poLines.get(0);
608 if (poLines.size() != 0)
609 ifExists = true;
610
611 return ifExists;
612 }
613
614 /**
615 * @param strOrderPONumber
616 * @return
617 * @throws Exception
618 */
619 public boolean getOrderIfExists(String strOrderPONumber) throws Exception {
620 OBCriteria<Order> crit = OBDal.getInstance().createCriteria(Order.class);
621 crit.add(Restrictions.eq(Order.PROPERTY_SCPPPONUMBER, strOrderPONumber));
622 return crit.list().size() > 0;
623 }
624
625 /**
626 * @param reqNumber
627 * @return
628 * @throws Exception
629 */
630 public boolean getCEMASOrderIfExists(String reqNumber) throws Exception {
631 OBCriteria<Order> crit = OBDal.getInstance().createCriteria(Order.class);
632 crit.add(Restrictions.eq(Order.PROPERTY_SCREQUISITIONNUMBER, reqNumber));
633 return crit.list().size() > 0;
634 }
635
636 /**
637 * @param strOrderPONumber
638 * @return
639 * @throws Exception
640 */
641 public boolean getOrderifDocNoExists(String strDocNo) throws Exception {
642 OBCriteria<Order> crit = OBDal.getInstance().createCriteria(Order.class);
643 crit.add(Restrictions.eq(Order.PROPERTY_DOCUMENTNO, strDocNo));
644 return crit.list().size() > 0;
645 }
646
647 /**
648 * Check if the Ship To Dodaac is flagged as IMSP for the orderline
649 *
650 * @param orderLine
651 * @return True/False
652 */
653 private boolean isOrderLineImspDodaac(OrderLine orderLine) {
654 boolean isImspDodaac = false;
655 try {
656 if (orderLine.getScShipToDodaac() != null) {
657 OBCriteria<CustomerDodaac> dodaacCrit = OBDal.getInstance()
658 .createCriteria(CustomerDodaac.class);
659 dodaacCrit
660 .add(Restrictions.eq(CustomerDodaac.PROPERTY_DODAAC, orderLine.getScShipToDodaac()));
661 List<CustomerDodaac> dodaacList = dodaacCrit.list();
662 if (dodaacList.size() > 0) {
663 isImspDodaac = Boolean.TRUE.equals(dodaacList.get(0).isImspDodaac());
664 }
665 }
666 } catch (Exception e) {
667 log.debug("Error occured processing to check if the orderline is IMSP dodaac.", e);
668 }
669 return isImspDodaac;
670 }
671
672 /*
673 * Get discounts, and attach them to the sales order Discount rules spec - For FMS org -> + T4 +
674 * (T7 if palletized), For non-FMS org -> if CONUS: T3 + T5 + T6 + (T7 if palletized), and if
675 * OCONUS (not CONUS): T8 + TB + (T7 if palletized)
676 *
677 * Fees - T3 -> Supply Chain Management Fee (non-FMS) for CONUS or CCP orders (CLIN 0001AB), T4 ->
678 * Supply Chain Management Fee (FMS shipments) (CLIN 0001AC), T5 -> Retreads, handling (CLIN 0002)
679 * , T6 -> Scrap/Disposal or aircraft tires (CLIN 0003), T7 -> Palletization (CLIN 0010), T8 ->
680 * COCOM Support for OCONUS tires (CLIN 0005-0009), TB -> Cost recovery for OCONUS Air
681 * (CLIN0011AA)
682 */
683 public void attachOrderDiscounts(Order order) {
684 try {
685 // WYOM-11385 : unpost and unprocess the sales order before attaching fees if already posted
686 // or processed
687 if (order.isProcessed() || order.getPosted().equals("Y")) {
688 OrderPostHelper.reactivateOrder(order);
689 if (order.isProcessed()) {
690 order.setProcessed(false);
691 }
692 OBDal.getInstance().save(order);
693 }
694 OBCriteria<OrderLine> criteria = OBDal.getInstance().createCriteria(OrderLine.class);
695 criteria.add(Restrictions.eq(OrderLine.PROPERTY_SALESORDER, order));
696 for (OrderLine orderLine : criteria.list()) {
697 boolean isPalletized = new SalesOrderLoadRuleActionProvider().isPalletized(orderLine);
698 OBCriteria<Discount> discount = OBDal.getInstance().createCriteria(Discount.class);
699 discount.add(Restrictions.eq(Discount.PROPERTY_PRODUCT, orderLine.getProduct()));
700 log.debug("Attaching discounts to " + orderLine.getProduct());
701 Date orderDate = order.getOrderDate();
702
703 for (Discount discountToAdd : discount.list()) {
704 Date startDate = discountToAdd.getScValidFrom();
705 Date endDate = discountToAdd.getScValidTo();
706 if ((startDate != null && endDate != null)
707 && (startDate.compareTo(orderDate) <= 0 && endDate.compareTo(orderDate) >= 0)) {
708 OrderDiscount orderDiscount = OBProvider.getInstance().get(OrderDiscount.class);
709 orderDiscount.setNewOBObject(true);
710 orderDiscount.setId(OBUtils.createNewUUID());
711 orderDiscount.setOrganization(order.getOrganization());
712 if (isPalletized && "T7".equals(discountToAdd.getName())) {
713 orderDiscount.setDiscount(discountToAdd);
714 }
715 if (order.getOrganization() != null
716 && TSI_FMS_ORG_ID.equals(order.getOrganization().getId())
717 && "T4".equals(discountToAdd.getName())) { // FMS org
718 orderDiscount.setDiscount(discountToAdd);
719 } else if (order.getOrganization() != null
720 && !TSI_FMS_ORG_ID.equals(order.getOrganization().getId())) { // non-FMS org
721 if (Boolean.TRUE.equals(orderLine.isScIsconus())) {
722 if ("T3".equals(discountToAdd.getName()) || "T6".equals(discountToAdd.getName())) {
723 orderDiscount.setDiscount(discountToAdd);
724 } else if ("T5".equals(discountToAdd.getName())
725 && !isOrderLineImspDodaac(orderLine)) {
726 orderDiscount.setDiscount(discountToAdd);
727 }
728 } else if (!Boolean.TRUE.equals(orderLine.isScIsconus())
729 && ("T8".equals(discountToAdd.getName())
730 || "TB".equals(discountToAdd.getName()))) {
731 orderDiscount.setDiscount(discountToAdd);
732 }
733 }
734 if ("Negotiated Fee".equals(discountToAdd.getName())
735 && discountToAdd.getDescription().contains(order.getDocumentNo()))
736 orderDiscount.setDiscount(discountToAdd);
737
738 if (orderDiscount.getDiscount() != null) {
739 orderDiscount.setSalesOrder(order);
740 orderDiscount.setLineNo(orderLine.getLineNo());
741 if (orderDiscount.getDiscount().getScFeeAmount() != null) {
742 orderDiscount.setScFeeAmount(orderDiscount.getDiscount().getScFeeAmount());
743 }
744 OBDal.getInstance().save(orderDiscount);
745 }
746 } else {
747 log.debug("Discount " + discountToAdd.getName() + " with fee amount"
748 + discountToAdd.getScFeeAmount() != null
749 ? discountToAdd.getScFeeAmount().toString()
750 : "0" + " for Sales Order : " + order.getDocumentNo() + " (product sku : "
751 + orderLine.getProduct().getSKU()
752 + " ) is outdated. The discount is not attached to the order.");
753 }
754 }
755 }
756 OBDal.getInstance().save(order);
757 } catch (Exception e) {
758 log.debug("Error attaching discounts to the sales order.", e);
759 logger.log("Error attaching discounts to the sales order. " + e.getMessage());
760 }
761 }
762
763 /**
764 *
765 * @param order
766 * @throws Exception
767 */
768 public void cancelAdditionalSalesOrderLineInstructions(Order order) throws Exception {
769 RefDataName refDataName = RefDataUtil
770 .getRefDataName(RefDataNames.ADDITIONAL_SALES_ORDER_LINE_INSTRUCTIONS);
771 for (OrderLine orderline : order.getOrderLineList()) {
772 List<SalesOrderLoadRules> loadRules = new SalesOrderLoadRuleActionProvider()
773 .findSalesOrderLoadRuleActions(orderline);
774 for (SalesOrderLoadRules loadRule : loadRules) {
775 RefData refData = RefDataUtil.getRefData(RefDataObjectType.C_ORDERLINE, orderline,
776 refDataName, loadRule.getRuleAction());
777 if (refData != null && refData.isActive()) {
778 refData.setActive(false);
779 OBDal.getInstance().save(refData);
780 }
781 }
782 }
783 }
784
785 /**
786 * Remove the current discount and fees, and re-attach if there are any
787 *
788 * @param order
789 */
790 public void cancelOrderDiscounts(Order order) throws Exception {
791 List<OrderDiscount> orderDiscountList = order.getOrderDiscountList();
792 // Remove the current discount and fees (deactivate)
793 if (orderDiscountList != null) {
794 for (OrderDiscount orderDiscount : orderDiscountList) {
795 if (Boolean.TRUE.equals(orderDiscount.isActive())) {
796 orderDiscount.setActive(false);
797 OBDal.getInstance().save(orderDiscount);
798 }
799 }
800 }
801 }
802
803 /**
804 * @param so
805 * @param businessPartner1
806 * @param shippingAddressStreet1
807 * @param shippingAddressCity1
808 * @param shippingAddressCountry1
809 * @param shippingAddressPostalCode1
810 * @param shippingAddressRegion1
811 * @param billingAddressCountry1
812 * @param billingAddressStreet1
813 * @param billingAddressCity1
814 * @param billingAddressRegion1
815 * @param billingAddressPostalCode1
816 * @param internalPO
817 * @param orderDel
818 * @param orderRef
819 * @param orderRFQ
820 * @param msg
821 * @param employeeID
822 * @return
823 * @throws ServletException
824 * @throws IOException
825 * @throws NoConnectionAvailableException
826 * @throws SQLException
827 */
828 private boolean createOrder(Order order, CustomerSO so, BusinessPartner businessPartner1,
829 Location shipToAddress, Location billingAddress, String internalPO, String orderDel,
830 String orderRef, String orderRFQ, String ppBuyerID, SystemType source, SOLoadObjects data)
831 throws ServletException, IOException, NoConnectionAvailableException, SQLException {
832
833 // Create Order
834 order.setSalesTransaction(true);
835
836 // Set TDS Workflow status
837 order.setTdswkfDocstatus(StatusHelper.HEADER_NEW);
838
839 // Defining BP
840 order.setBusinessPartner(businessPartner1);
841
842 // set order Internal PPPO number
843 order.setScPppoNumber(internalPO);
844 // set order RFQ number number
845
846 // deliveryOrder
847 order.setScDelOrd(orderDel);
848
849 order.setScRfqNumber(orderRFQ);
850
851 // Order Reference
852 order.setOrderReference(orderRef); // Get the PONumber from XML and set the
853
854 // InvPull
855 String strInvPull = so.getInvPull();
856 boolean booleanInvPull = false;
857 if (strInvPull != null && strInvPull.equalsIgnoreCase("yes")) {
858 booleanInvPull = true;
859 }
860 order.setScInventoryPull(booleanInvPull);
861
862 // deliverynotes
863 String strDeliveryNotes = so.getMarkFor();
864 order.setDeliveryNotes(strDeliveryNotes);
865
866 // comments
867 String strComments = so.getComments();
868 order.setSCComments(strComments);
869
870 // Status
871 String strStatus = so.getCurrentStatus();
872 order.setScPpStatus(strStatus);
873
874 // Requisition number
875 String strReqNum = so.getRequisitionNumber();
876 order.setScRequisitionNumber(strReqNum);
877
878 // JobOrderNumber
879 String strJobOrderNumber = so.getJobOrderNumber();
880 order.setScJobOrder(strJobOrderNumber);
881
882 // OrderType
883 String strOrderType = so.getOrderType();
884 boolean booleanOrderType = false;
885 if (strOrderType != null && strOrderType.equalsIgnoreCase("yes")) {
886 booleanOrderType = true;
887 }
888
889 order.setScIsbom(booleanOrderType);
890
891 // POPriority
892
893 // Priority is defaulted to 5 by Openbravo. Keeping track of whether priority has been set by
894 // logic below. If not,
895 // if priority exists at the lines, use the highest priority. This part of the logic does not
896 // apply to CEMAS, MAXIMO
897 // PurchasePlace; if header priority is blank, default is 5
898 boolean prioritySet = false;
899 String strPOPriority = so.getPOPriority();
900 if (SystemType.CEMAS.equals(source)) {
901 // CEMAS Sales Orders should have the FC number loaded into the EM_SC_PPPO_NUMBER field as
902 // well
903 if (strReqNum != null) {
904 order.setScPppoNumber(strReqNum);
905 }
906 if (strPOPriority != null) {
907 order.setScCemasPriority(strPOPriority);
908 int priority = Integer.parseInt(strPOPriority);
909 if (!OB_PRIORITY.contains(Integer.valueOf(priority))) {
910 order.setPriority("5"); // if priority not 3,5 or 7 set default to 5
911 } else {
912 order.setPriority(Integer.toString(priority));
913 }
914 } else {
915 order.setPriority("5"); // default set to 5
916 }
917 prioritySet = true;
918 } else if (strPOPriority != null) {
919 // Check for new priority values for SW Maximo storefronts.
920 if (SWMaximoUtil.isSWMaxCustomer(so.getCustomerCode())) {
921 // For this case we have already determine earlier the correct priority so just assign it
922 order.setPriority(strPOPriority);
923 prioritySet = true;
924 }
925 // check if priority is one of values in OB priority list
926 else if (OB_PRIORITY.contains(Integer.valueOf(strPOPriority))) {
927 order.setPriority(strPOPriority);
928 prioritySet = true;
929 } else {
930 // Check if priority is one of Milstrip priorities. If yes, map to corresponding OB priority
931 // value
932 String priority = convertMilstripPriToOBPri(strPOPriority);
933 if (priority != null) {
934 order.setPriority(priority);
935 prioritySet = true;
936 }
937 }
938 } else {
939 // If source is Maximo or PurchasePlace set default to 5. Default is set to 5 for CEMAS as
940 // well (above). For other organizations
941 // take highest priority from the lines (code further down)
942 if (SystemType.MAXIMO.equals(source) || SystemType.PURCHASEPLACE.equals(source)) {
943 order.setPriority("5"); // default set to 5
944 prioritySet = true;
945 }
946 }
947
948 // fundCode
949 String strFundCode = so.getFundCode();
950 order.setScFundCode(strFundCode);
951
952 // signal
953 String strSignal = so.getSignal();
954 order.setScSignalCode(strSignal);
955
956 // MIPRCode
957 String strMIPRCode = so.getMIPRCode();
958 order.setScMipr(strMIPRCode);
959
960 // OrderDateRequired and Scheduled Delivery Date
961 String strOrderDateRequired = so.getOrderDateRequired();
962 System.out.println("strOrderDateRequired.order level.." + strOrderDateRequired);
963 if (strOrderDateRequired != null && !strOrderDateRequired.equals("")) {
964 try {
965 Date orderDateRequired = DateParser.parseDateString(strOrderDateRequired);
966 order.setScNeedDate(orderDateRequired);
967 order.setScheduledDeliveryDate(orderDateRequired);
968 } catch (Exception e) {
969 log.error("Error parsing OrderDateRequired", e);
970 TransmissionUtils.createTransmissionError("Error parsing OrderDateRequired", e);
971 throw new OBException("Error parsing OrderDateRequired", e);
972 }
973 }
974
975 // SAddr
976 String strsAddr = so.getSAddr();
977 order.setScSuppAddrDodaac(strsAddr);
978
979 // Document Type
980 final OBCriteria<DocumentType> documentType = OBDal.getInstance()
981 .createCriteria(DocumentType.class);
982
983 final List<DocumentType> documentTypeList;
984 DocumentType docType = null;
985 log.debug("Source from xml: " + source);
986
987 // WYOM-11964: transfer order not being set properly
988 if (so.getOrderType() != null && "Transfer".equalsIgnoreCase(so.getOrderType())) {
989 documentType.add(Restrictions.eq("name", "Transfer Order"));
990 documentTypeList = documentType.list();
991 if (!documentTypeList.isEmpty()) {
992 docType = documentTypeList.get(0);
993 }
994 } else if (so.getInvPull() != null && so.getInvPull().equalsIgnoreCase("yes")) {
995 documentType.add(Restrictions.eq("name",
996 ApplicationProperties.getProperty(ApplicationProperty.Storefront_Order)));
997 documentTypeList = documentType.list();
998 if (!documentTypeList.isEmpty()) {
999 docType = documentTypeList.get(0);
1000 }
1001
1002 } else if (so.getReplenishment() != null && so.getReplenishment().equalsIgnoreCase("yes")) {
1003 documentType.add(Restrictions.eq("name",
1004 ApplicationProperties.getProperty(ApplicationProperty.Replenishment_Order)));
1005 documentTypeList = documentType.list();
1006 if (!documentTypeList.isEmpty()) {
1007 docType = documentTypeList.get(0);
1008 }
1009 } else {
1010 documentType.add(Restrictions.eq("name", "Standard Order"));
1011 documentTypeList = documentType.list();
1012 docType = documentTypeList.get(0);
1013 }
1014
1015 /*
1016 * else if (SystemType.MAXIMO.equals(source) || SystemType.CEMAS.equals(source) ||
1017 * SystemType.PURCHASEPLACE.equals(source) || SystemType.WYOMING.equals(source)) {
1018 * documentType.add(Restrictions.eq("name", "Standard Order")); documentTypeList =
1019 * documentType.list(); docType = documentTypeList.get(0);
1020 *
1021 * } else { docType = null; }
1022 */
1023
1024 // Document Type
1025 order.setDocumentType(docType);
1026
1027 // Set DO Flag (This is based on the SC_CUSTOMER_PARTNER.DO_HEADER_LINE flag)
1028 String headerFlag = "N"; // N = Not applicable, H = Header, L = Line
1029 CustomerPartner custPart = CustomerUtil.getCustomerPartner(businessPartner1);
1030 if (custPart != null) {
1031 headerFlag = custPart.getHeaderLine();
1032 }
1033 order.setScDoFlag(headerFlag);
1034
1035 // Transaction Document
1036 order.setTransactionDocument(docType);
1037
1038 // Get next document no for this doctype
1039 String documentNo = OBUtils.getDocumentNo(order.getOrganization(), docType.getId(),
1040 docType.getName());
1041
1042 // Document no
1043 order.setDocumentNo(documentNo);
1044
1045 Contract contract = OBUtils.getContractByNo(so.getContractNumber());
1046 if (contract != null) {
1047 order.setDeliveryTerms(contract.getDefaultDeliveryTerms());
1048 order.setInvoiceTerms(contract.getDefaultInvoiceTerms());
1049 }
1050
1051 // Invoice Terms
1052 // Set invoice term for Sales order based on invoice term in business partner. If blank,
1053 // default
1054 // to default_invoice_terms from sc_contract; already set above. If this is blank as well,
1055 // pull
1056 // from ad_orginfo.em_sc_so_invoicerule. Finally, default is "D"
1057 if (businessPartner1.getInvoiceTerms() != null) {
1058 order.setInvoiceTerms(businessPartner1.getInvoiceTerms());
1059 }
1060
1061 // Order date,
1062 Date currentDate = new Date(System.currentTimeMillis());
1063 if (so.getDateOrdered() != null && !so.getDateOrdered().isEmpty()) {
1064 try {
1065 Date dateOrdered = DateParser.parseDateString(so.getDateOrdered());
1066 order.setOrderDate(dateOrdered);
1067 } catch (Exception e) {
1068 log.error("Error parsing DateOrdered", e);
1069 TransmissionUtils.createTransmissionError("Error parsing DateOrdered", e);
1070 }
1071 } else {
1072 order.setOrderDate(currentDate);
1073 }
1074
1075 // Accounting date,
1076 order.setAccountingDate(currentDate);
1077
1078 String payMethodName = so.getPaymentMethod();
1079
1080 boolean payMethodExists = payMethodexists(payMethodName);
1081
1082 log.debug("Payment Method: " + payMethodName);
1083 FIN_PaymentMethod payMethod;
1084 if (payMethodExists) {
1085 // to get payment method for APR
1086 OBCriteria<FIN_PaymentMethod> paymentMethod = OBDal.getInstance()
1087 .createCriteria(FIN_PaymentMethod.class);
1088 paymentMethod.add(Restrictions.eq("name", payMethodName));
1089 payMethod = (FIN_PaymentMethod) paymentMethod.uniqueResult();
1090 } else {
1091 payMethod = getPaymentMethod(businessPartner1);
1092 if (payMethod == null) {
1093 OBCriteria<FIN_PaymentMethod> paymentMethod = OBDal.getInstance()
1094 .createCriteria(FIN_PaymentMethod.class);
1095 paymentMethod.add(Restrictions.eq("name", "By Cash"));
1096 payMethod = (FIN_PaymentMethod) paymentMethod.uniqueResult();
1097 }
1098 }
1099 order.setPaymentMethod(payMethod);
1100
1101 // Currency
1102 Currency c = getCurrenyCode(businessPartner1);
1103 if (c == null) {
1104 final OBCriteria<Currency> currency = OBDal.getInstance().createCriteria(Currency.class);
1105 currency.add(Restrictions.eq("iSOCode", "USD"));
1106 final List<Currency> currencyList = currency.list();
1107 c = currencyList.get(0);
1108 }
1109 order.setCurrency(c);
1110
1111 if (order.getFormOfPayment() == null)
1112 order.setFormOfPayment("K");
1113 if (order.getDeliveryMethod() == null)
1114 order.setDeliveryMethod("S");
1115 if (order.getDeliveryTerms() == null)
1116 order.setDeliveryTerms("A");
1117 if (order.getFreightCostRule() == null)
1118 order.setFreightCostRule("I");
1119 // set the buyer assigned to the sales order - have to go through the person/customer
1120 // relationship
1121 OBCriteria<CustomerPartner> custPartnerCriteria = OBDal.getInstance()
1122 .createCriteria(CustomerPartner.class);
1123 custPartnerCriteria
1124 .add(Restrictions.eq(CustomerPartner.PROPERTY_BUSINESSPARTNER, order.getBusinessPartner()));
1125 List<CustomerPartner> custPartnerList = custPartnerCriteria.list();
1126
1127 CustomerPartner cp = null;
1128 if (custPartnerList.size() > 0) {
1129 cp = custPartnerList.get(0);
1130 }
1131 Organization org = data.getOrganization();
1132 if (log.isInfoEnabled() && org != null) {
1133 log.debug("Organization of the program: " + org.getName());
1134 }
1135 // Organization
1136 // if it is a storefront customer, then we want to get the org from the crossdock customer
1137 // table
1138 // otherwise get it from the customer's contract
1139 if (CustomerUtil.isStorefrontCustomer(businessPartner1)) {
1140 CustomerConfig cc = CustomerUtil
1141 .getCustomerConfig(CustomerUtil.getCustomerPartner(businessPartner1));
1142 org = cc.getOrganization();
1143 if (log.isInfoEnabled() && org != null) {
1144 log.debug("Organization of the storefront customer: " + org.getName());
1145 }
1146 }
1147
1148 // if we didn't find an org from the above steps, just use the customer's organization
1149 if (org == null) {
1150 order.setOrganization(businessPartner1.getOrganization());
1151 if (log.isInfoEnabled()) {
1152 log.debug("Organization of the busines partner: " + businessPartner1.getOrganization());
1153 }
1154 } else {
1155 order.setOrganization(org);
1156 }
1157
1158 // Client
1159 order.setClient(businessPartner1.getClient());
1160 // OLD - warehouseCriteria.add(Restrictions.eq("id", context.getWarehouse()));
1161
1162 // Retrieve record from ad_orginfo
1163 OrganizationInformation orgInfo = OBDal.getInstance().get(OrganizationInformation.class,
1164 order.getOrganization().getId());
1165
1166 // If could not pull invoice term from business partner, or sc_contract, check
1167 // ad_ad_orginfo.em_sc_so_invoicerule
1168 // If still blank, default is set to "D"
1169 if (order.getInvoiceTerms() == null) {
1170 order.setInvoiceTerms("D");
1171 if (orgInfo != null) {
1172 if (orgInfo.getScSoInvoicerule() != null) {
1173 order.setInvoiceTerms(orgInfo.getScSoInvoicerule());
1174 }
1175 }
1176 }
1177
1178 // Scheduled Delivery date
1179 if (strOrderDateRequired == null || strOrderDateRequired.equals("")) {
1180 // If not Tires
1181 if (order.getOrganization() == null || !order.getOrganization().getName().contains("TSI")) {
1182 order.setScheduledDeliveryDate(currentDate);
1183 }
1184 }
1185
1186 // Payment Term
1187 // 1) First pull from xmlheader.WyomPayTerms else
1188 // 2) If fast pay, then "O" else
1189 // 3) "Net xx" days. Lookup up
1190 // the value for "xx" in XMLheader.PayTermsNetDays.
1191 // H = Net 15 days
1192 // D = Net 20 days
1193 // A = Net 30 days (default value)
1194 // F = Net 45 days
1195 // K = Net 60 days
1196 // Z = Net 120 days else
1197 // 4) c_bpartner.c_paymentterm_id else
1198 // 5) ad_org_info.sc_so_payment_term else
1199 // 6) if OEMA, default is Net 30 days otherwise default is "CASH AGAINST DOCUMENTS"
1200
1201 PaymentTerm pTerm = null;
1202 if (so.getWyomPayTerms() != null && !so.getWyomPayTerms().isEmpty()) {
1203 pTerm = getPayTermsByName(so.getWyomPayTerms());
1204 }
1205 if (pTerm == null) {
1206 if (so.getPayTermsType() != null && !so.getPayTermsType().isEmpty()) {
1207 if (so.getPayTermsType().equalsIgnoreCase("21")) {
1208 pTerm = getPayTermsByName("Fast Pay");
1209 }
1210 }
1211 }
1212 if (pTerm == null) {
1213 if (so.getClauseAndNoteText() != null) {
1214 String text = so.getClauseAndNoteText();
1215 if (text.contains("Fast Pay") || text.contains("52.213-1") || text.contains("52.213-01")
1216 || text.contains("52.213-9009") || text.contains("52.212-9001")) {
1217 pTerm = getPayTermsByName("Fast Pay");
1218 }
1219 }
1220 }
1221 if (pTerm == null) {
1222 if ((pTerm = getPayTermsByName("Net " + so.getPayTermsNetDays() + " days")) != null) {
1223
1224 } else if ((pTerm = getPayTerms(businessPartner1)) != null) {
1225
1226 } else if (orgInfo != null) {
1227 if (orgInfo.getScSoPaymentterm() != null) {
1228 pTerm = orgInfo.getScSoPaymentterm();
1229 }
1230 }
1231 }
1232
1233 if (pTerm == null) {
1234 if (order.getOrganization().getName().contains("OEM")) {
1235 pTerm = getPayTermsByName("Net 30 days");
1236 } else {
1237 pTerm = getPayTermsByName("CASH AGAINST DOCUMENTS");
1238 }
1239 }
1240
1241 order.setPaymentTerms(pTerm);
1242
1243 // Price List
1244 PriceList pr = getPList(businessPartner1);
1245 if (pr == null) {
1246 OBCriteria<PriceList> priceList = OBDal.getInstance().createCriteria(PriceList.class);
1247 priceList.add(Restrictions.eq("name", "National Catalog"));
1248 List<PriceList> pl = priceList.list();
1249 if (pl.size() == 0) {
1250 priceList = OBDal.getInstance().createCriteria(PriceList.class);
1251 priceList.add(Restrictions.eq("name", "Generic Vendor"));
1252 pl = priceList.list();
1253 }
1254 pr = pl.get(0);
1255 }
1256 order.setPriceList(pr);
1257
1258 // Freight Amount
1259 order.setFreightAmount(new BigDecimal(0));
1260
1261 // Grand Total Amount
1262 order.setGrandTotalAmount(new BigDecimal(0));
1263
1264 // Summed Line Amount
1265 order.setSummedLineAmount(new BigDecimal(0));
1266
1267 order.setPartnerAddress(getPartnerAddress(businessPartner1));
1268
1269 // Billing Address
1270 if (billingAddress != null) {
1271 // set invoice address
1272 order.setInvoiceAddress(billingAddress);
1273 } else {
1274 setInvoiceAddressByDefultBillToAddress(order, businessPartner1);
1275 }
1276
1277 // set the address details from newly created address
1278 if (shipToAddress != null) {
1279 shipToAddress.setShipToAddress(true);
1280 order.setDeliveryLocation(shipToAddress);
1281 }
1282
1283 // Set Active
1284 order.setActive(true);
1285
1286 log.debug(order.getOrganization());
1287 log.debug(order.getOrganization().getId());
1288 log.debug(context.getOrganization());
1289
1290 if ("0".equals(order.getOrganization().getId()))
1291 order.setOrganization(OBUtils.getOrganization(context.getOrganization()));
1292
1293 order.setScPplcBuyer(getBuyer(ppBuyerID));
1294
1295 // set the program code for the sales order - have to go through the customer relationship
1296 // Also sets the cross dock permissions
1297 if (cp != null) {
1298 Program program = data.getProgram();
1299 order.setScCrossdock(CrossdockCheck.checkCustomer(order.getOrganization(), cp).getValue());
1300 order.setScProgramCode((program != null ? program.getProgramCode() : null));
1301 }
1302 if (order.isScInventoryPull()) {
1303 order.setWarehouse(CustomerUtil.getWarehouse(order.getBusinessPartner()));
1304 } else if (CrossdockFlag.CROSS_DOCK.getValue().equals(order.getScCrossdock())
1305 || CrossdockFlag.ONLY_CROSS_DOCK.getValue().equals(order.getScCrossdock())) {
1306 order.setWarehouse(CrossdockCheck.getWarehouse(order.getOrganization(), cp));
1307 }
1308 if (order.getWarehouse() == null) {
1309 // Warehouse
1310 final OBCriteria<Warehouse> warehouseCriteria = OBDal.getInstance()
1311 .createCriteria(Warehouse.class);
1312 warehouseCriteria.add(Restrictions.like(Warehouse.PROPERTY_NAME, "%virtual%").ignoreCase());
1313 // OLD - warehouseCriteria.add(Restrictions.eq("id", context.getWarehouse()));
1314 warehouseCriteria
1315 .add(Restrictions.eq(Warehouse.PROPERTY_CLIENT, businessPartner1.getClient()));
1316 final List<Warehouse> wh = warehouseCriteria.list();
1317 log.debug("whare house size:::" + wh.size());
1318
1319 final Warehouse warehouse1 = wh.get(0);
1320 order.setWarehouse(warehouse1);
1321
1322 }
1323
1324 order.setScContractType(so.getContractType());
1325
1326 // Create a save point before creating the order that way if one of the lines fails
1327 // we can rollback to this point and not have a partially created order.
1328 Connection conn = OBDal.getInstance().getConnection(false);
1329 Savepoint mySavepoint = conn.setSavepoint("MYSAVEPOINT");
1330
1331 // Save the Order Object
1332 OBDal.getInstance().save(order);
1333 log.debug("Order Header created");
1334
1335 if (so.getHeaderRefs() != null) {
1336 for (HeaderRef ref : so.getHeaderRefs().getHeaderRef()) {
1337 if (StringUtils.isEmpty(ref.getSegment()) || "N9Loop".equalsIgnoreCase(ref.getSegment()))
1338 continue;
1339 String ediref = String.format("%s^%s", ref.getSegment(), ref.getQualifier());
1340 RefDataName name = RefDataUtil.getRefDataName(ediref);
1341 RefDataValue value = null;
1342 if (name != null && name.isActive()) {
1343 value = RefDataUtil.getRefDataValue(name, ref.getValue());
1344 }
1345 String remark = ref.getDescription();
1346 if (remark == null)
1347 remark = "";
1348 if (value == null) {
1349 value = RefDataUtil.getRefDataValue(name, "see remarks");
1350 remark = (ref.getValue() + " " + remark).trim();
1351 }
1352 if (value == null) {
1353 value = RefDataUtil.getRefDataValue(name, "SEE_REMARKS");
1354 remark = (ref.getValue() + " " + remark).trim();
1355 }
1356 if (name == null || !name.isActive() || value == null) {
1357 name = RefDataUtil.getRefDataName(RefDataNames.UNDEFINED_REF_DATA);
1358 value = RefDataUtil.getRefDataValue(RefDataNames.UNDEFINED_REF_DATA,
1359 RefDataValues.A_UNDEF_REF_DATA_SEE_REMARKS);
1360 remark = ediref + ":" + ref.getQualifier() + " - " + remark;
1361 }
1362 RefDataUtil.updateRefData(RefDataObjectType.C_ORDER, order, name,
1363 RefDataSource.SYSTEM_LOAD_PROCESS, value, false, remark);
1364 }
1365 }
1366
1367 if (so.getHeaderAddresses() != null) {
1368 for (HeaderAddress add : so.getHeaderAddresses().getHeaderAddress()) {
1369 if (StringUtils.isEmpty(add.getSegment()))
1370 continue;
1371 String ediref = String.format("%s^%s", add.getSegment(), add.getAddressQualifier());
1372 RefDataName name = RefDataUtil.getRefDataName(ediref);
1373 RefDataValue value = null;
1374 if (name != null && name.isActive()) {
1375 value = RefDataUtil.getRefDataValue(name, add.getAddressCodeQualifier());
1376 }
1377
1378 String remark = add.getAddressCode();
1379 // Admin Code - pull from EDI C4 qualifier
1380 if (add.getAddressQualifier() != null && add.getAddressQualifier().equals("C4")) {
1381 order.setScAdminDodaac(remark);
1382 }
1383
1384 if (name == null || !name.isActive() || value == null || StringUtils.isEmpty(remark)) {
1385 name = RefDataUtil.getRefDataName(RefDataNames.UNDEFINED_ADDRESS_DATA);
1386 value = RefDataUtil.getRefDataValue(RefDataNames.UNDEFINED_ADDRESS_DATA,
1387 RefDataValues.A_UNDEF_ADDRESS_DATA_SEE_REMARKS);
1388 remark = ediref + "^";
1389 if (StringUtils.isEmpty(add.getAddressCode())) {
1390 remark += "NO CODE -- " + StringUtils.defaultString(add.getAddressDescription()) + " "
1391 + StringUtils.defaultString(add.getAddress1()) + " "
1392 + StringUtils.defaultString(add.getCity()) + " "
1393 + StringUtils.defaultString(add.getState()) + " "
1394 + StringUtils.defaultString(add.getCountry()) + " "
1395 + StringUtils.defaultString(add.getPostal());
1396 } else
1397 remark += add.getAddressCode();
1398 }
1399 RefDataUtil.updateRefData(RefDataObjectType.C_ORDER, order, name,
1400 RefDataSource.SYSTEM_LOAD_PROCESS, value, false, remark);
1401 }
1402 }
1403
1404 // For SW Storefronts populate the work center and requested by fields if provided
1405 if (so.getRequestedBy() != null) {
1406 order.setScRequestedBy(so.getRequestedBy());
1407 }
1408
1409 if (so.getWorkCenter() != null) {
1410 order.setScWorkCenter(so.getWorkCenter());
1411 }
1412
1413 // loop lines
1414 for (CustomerSOLineItem line : so.getCustomerSOLineItems().getCustomerSOLineItem()) {
1415 try {
1416 // Create an Order Line
1417 OrderLine oline = createLine(order, so, line, businessPartner1, order.getClient(),
1418 shipToAddress, source);
1419 order.getOrderLineList().add(oline);
1420 OBDal.getInstance().save(oline);
1421 if (order.getOrganization().getName().contains("OEM")) {
1422 // Add Reference Data for OEMA
1423 logger.logln("Add Reference Data for OEMA");
1424 SalesOrderDao.createAndAssignSOLReferenceData(oline, so, line);
1425 } else if (order.getOrganization().getName().contains("TSI")) {
1426 // Add Reference Data for TSI
1427 logger.logln("Add Reference Data for TSI");
1428 createRefDataPHOrderline(oline, line);
1429 SalesOrderDao.createAndAssignSOLReferenceData(oline, so, line);
1430 }
1431 } catch (Exception e) {
1432 e.printStackTrace();
1433 logger.logln("Error encountered while creating order line: " + e.getMessage());
1434 log.error("Error occurred in Openbravo while creating Order line!", e);
1435 errorCounter++;
1436 try {
1437 System.out.println("Remove order if any error encounter while creating order lines...");
1438 // mallik de 129 begin
1439 OBDal.getInstance().remove(order);
1440 OBDal.getInstance().commitAndClose();
1441 // mallik de 129 ends
1442 conn.rollback(mySavepoint);
1443 } catch (SQLException e1) {
1444 log.error("Error occurred while rollback", e1);
1445 // ignore rollback failure... nothing we can do.
1446 } catch (Exception ex) {
1447 log.error(ex);
1448 }
1449 TransmissionUtils.createTransmissionError("Error creating orderline", e);
1450 throw new OBException("Error creating orderline", e);
1451 }
1452 }
1453
1454 try {
1455 OrderStatusUpdater.calculateOrderDates(order);
1456 } catch (HibernateException he) {
1457 log.error("Unable to update scheduled delivery date because of the following error: "
1458 + he.getMessage(), he);
1459 logger.logln("Unable to update scheduled delivery date because of the following error: "
1460 + he.getMessage());
1461 logger.logln("Continuing to process the sales order anyway.");
1462 TransmissionUtils.createTransmissionError(
1463 "Unable to update scheduled delivery date because of the following error: "
1464 + he.getMessage(),
1465 he);
1466 }
1467
1468 // em_sc_freight_on_board and em_sc_inspPt
1469 // If freight on board are same for all lines, populate at header level with same value; same
1470 // goes for insp pt
1471 // If value exists at header level, copy to lines
1472 if (so.getFobPt() != null && !so.getFobPt().isEmpty()) {
1473 if (so.getFobPt().equalsIgnoreCase("OR")) {
1474 order.setSCFREIGHTONBOARD("SP");
1475 } else if (so.getFobPt().equalsIgnoreCase("DE")) {
1476 order.setSCFREIGHTONBOARD("DT");
1477 } else if (so.getFobPt().equalsIgnoreCase("SP") || so.getFobPt().equalsIgnoreCase("DT")) {
1478 order.setSCFREIGHTONBOARD(so.getFobPt());
1479 }
1480 }
1481
1482 if (so.getInspPt() != null && !so.getInspPt().isEmpty()) {
1483 if (so.getInspPt().equalsIgnoreCase("SP")) {
1484 order.setScInstpt("OR");
1485 } else if (so.getInspPt().equalsIgnoreCase("DE")) {
1486 order.setScInstpt("DT");
1487 } else if (so.getInspPt().equalsIgnoreCase("OR") || so.getInspPt().equalsIgnoreCase("DT")) {
1488 order.setScInstpt(so.getInspPt());
1489 }
1490 }
1491
1492 boolean sameFob = true;
1493 boolean sameInspPt = true;
1494 Set<String> fobSet = new TreeSet<String>();
1495 Set<String> inspPtSet = new TreeSet<String>();
1496 for (OrderLine orderline : order.getOrderLineList()) {
1497 if (orderline.getScFobpt() != null) {
1498 if (!fobSet.add(orderline.getScFobpt())) {
1499 sameFob = false;
1500 }
1501 } else {
1502 // if fobpt is blank at line, copy from header
1503 orderline.setScFobpt(order.getSCFREIGHTONBOARD());
1504 }
1505 if (orderline.getScInstpt() != null) {
1506 if (!inspPtSet.add(orderline.getScInstpt())) {
1507 sameInspPt = false;
1508 }
1509 } else {
1510 // if insppt is blank at line, copy from header
1511 orderline.setScInstpt(order.getScInstpt());
1512 }
1513 }
1514
1515 // if fob and insppt are blank at header, and all lines have same value, copy to header
1516 if (order.getSCFREIGHTONBOARD() == null || order.getSCFREIGHTONBOARD().isEmpty()) {
1517 if (sameFob) {
1518 order.setSCFREIGHTONBOARD(order.getOrderLineList().get(0).getScFobpt());
1519 }
1520 }
1521 if (order.getScInstpt() == null || order.getScInstpt().isEmpty()) {
1522 if (sameInspPt) {
1523 order.setScInstpt(order.getOrderLineList().get(0).getScInstpt());
1524 }
1525 }
1526
1527 CustomerRFQ customerRFQ = null;
1528 if (order.getOrderLineList().size() > 0) {
1529 if (order.getOrderLineList().get(0).getScProposalItem() != null) {
1530 customerRFQ = order.getOrderLineList().get(0).getScProposalItem().getRequestItem()
1531 .getCustomerRfq();
1532 }
1533 }
1534
1535 // EM_SC_RFPS_ID
1536 if (customerRFQ != null) {
1537 order.setScRfp(customerRFQ.getRfp());
1538 }
1539
1540 // em_sc_Customer_POC_Name
1541 order.setScCustomerPocName(so.getBuyerName());
1542
1543 // em_sc_customer_POC_phone
1544 order.setScCustomerPocPhone(so.getKeyPhoneNumber());
1545
1546 // em_sc_customer_POC_email
1547 order.setScCustomerPocEmail(so.getKeyEmail());
1548
1549 // If order priority is null, check priority on lines and take the highest
1550 if (!prioritySet) {
1551 List<Integer> priorityLines = new ArrayList<Integer>();
1552 for (CustomerSOLineItem soline : so.getCustomerSOLineItems().getCustomerSOLineItem()) {
1553 if (soline.getPOPriority() != null && !soline.getPOPriority().isEmpty()) {
1554 // if priority comes in as "Y"
1555 if (soline.getPOPriority().equalsIgnoreCase("Y")) {
1556 priorityLines.add(3);
1557 } else {
1558 priorityLines.add(Integer.valueOf(soline.getPOPriority()));
1559 }
1560 }
1561 }
1562 // Want highest priority
1563 if (priorityLines.size() > 0) {
1564 Arrays.sort(priorityLines.toArray());
1565 Integer maxPri = priorityLines.get(priorityLines.size() - 1);
1566 if (OB_PRIORITY.contains(maxPri)) {
1567 order.setPriority(maxPri.toString());
1568 prioritySet = true;
1569 } else {
1570 String priority = convertMilstripPriToOBPri(maxPri.toString());
1571 if (priority != null) {
1572 order.setPriority(priority);
1573 prioritySet = true;
1574 }
1575 }
1576 }
1577 if (!prioritySet) {
1578 order.setPriority("SC_9");
1579 }
1580 }
1581
1582 // Specific to OEMA
1583 if (order.getOrganization().getName().contains("OEM")) {
1584 logger.logln("Add Reference Data for OEM");
1585 order.setOrderReference(so.getContractNumber());
1586
1587 if (order.getScRfp() == null) {
1588 if (so.getContractNumber() != null && !so.getContractNumber().isEmpty()) {
1589 String contractNum = so.getContractNumber().replaceAll("-|\\s", "").trim();
1590
1591 OBCriteria<RFP> crit = OBDal.getInstance().createCriteria(RFP.class);
1592
1593 crit.add(Restrictions.sqlRestriction(
1594 "lower(replace(replace(contract_number, '-', ''), ' ', '')) = ?",
1595 contractNum.toLowerCase(), StringType.INSTANCE));
1596
1597 if (crit.list().size() == 1) {
1598 order.setScRfp(crit.list().get(0));
1599 }
1600 }
1601 }
1602 // paymentrule
1603 order.setFormOfPayment("B");
1604 if (businessPartner1.getFormOfPayment() != null) {
1605 order.setFormOfPayment(businessPartner1.getFormOfPayment());
1606 } else if (orgInfo != null) {
1607 if (orgInfo.getScSoPaymentrule() != null) {
1608 order.setFormOfPayment(orgInfo.getScSoPaymentrule());
1609 }
1610 }
1611
1612 // freightcostrule
1613 if (so.getShipmentPayMethod() != null && !so.getShipmentPayMethod().isEmpty()) {
1614 if (so.getShipmentPayMethod().equalsIgnoreCase("PP")) {
1615 order.setFreightCostRule("S");
1616 } else if (so.getShipmentPayMethod().equalsIgnoreCase("PS")) {
1617 order.setFreightCostRule("I");
1618 }
1619 }
1620
1621 order.setUserContact(OBUtils.getSOUserContact(order.getOrganization()));
1622 order.setDeliveryLocation(null);
1623
1624 // paymentrule
1625 order.setFormOfPayment("B");
1626 if (businessPartner1.getFormOfPayment() != null) {
1627 order.setFormOfPayment(businessPartner1.getFormOfPayment());
1628 } else if (orgInfo != null) {
1629 if (orgInfo.getScSoPaymentrule() != null) {
1630 order.setFormOfPayment(orgInfo.getScSoPaymentrule());
1631 }
1632 }
1633
1634 order.setUserContact(OBUtils.getSOUserContact(order.getOrganization()));
1635 order.setDeliveryLocation(null);
1636 order.setInvoiceAddress(order.getPartnerAddress());
1637
1638 // em_sc_rfq_number
1639 if (so.getRFQNumber() == null || so.getRFQNumber().isEmpty()) {
1640 if (customerRFQ != null) {
1641 order.setScRfqNumber(customerRFQ.getDocumentNo());
1642 }
1643 }
1644
1645 // em_sc_do_flag
1646 order.setScDoFlag(null);
1647
1648 order.setScIsapproved(true);
1649
1650 // WYOM-6577 Use Team Mgr (Org Lookup) to populate sales representative
1651 order.setSalesRepresentative(OBUtils.getSOUserContact(order.getOrganization()));
1652
1653 OBDal.getInstance().flush();
1654 // dpas priority rating
1655 String dpasRating = getDPASPriorityRatingForHeader(order);
1656 if (dpasRating != null) {
1657 order.setScDlaPriorityRating(dpasRating);
1658 }
1659 // Populate DPAS at line level.
1660 // Since looping through lines, determine em_sc_inv_pull at header level where if all
1661 // em_sc_inv_pull at lines are 'Y' set Y at header level as well
1662 boolean isInvPull = true;
1663 for (OrderLine orderline : order.getOrderLineList()) {
1664 RefData dpasRatingLineRefData = RefDataUtil.getRefData(RefDataObjectType.C_ORDERLINE,
1665 orderline, RefDataNames.DPAS_PRIORITY_RATING);
1666 if (dpasRatingLineRefData != null) {
1667 orderline.setScDpasRating(dpasRatingLineRefData.getRemark());
1668 }
1669 if (!orderline.isScInventoryPull()) {
1670 isInvPull = false;
1671 }
1672 }
1673 if (isInvPull) {
1674 order.setScInventoryPull(true);
1675 }
1676
1677 // populate em_sc_baseline_promise_date
1678 int linesCounter = 0;
1679 for (CustomerSOLineItem soline : so.getCustomerSOLineItems().getCustomerSOLineItem()) {
1680 if (soline.getContractualDeliveryDate() != null
1681 && !soline.getContractualDeliveryDate().isEmpty()) {
1682 try {
1683 order.getOrderLineList().get(linesCounter)
1684 .setScBaselinePromiseDate(dateFormat.parse(soline.getContractualDeliveryDate()));
1685 } catch (Exception e) {
1686 log.error("Error parsing Baseline Promise Date", e);
1687 TransmissionUtils.createTransmissionError("Error parsing Baseline Promise Date", e);
1688 // throw new OBException("Error parsing Baseline Promise Date", e);
1689 }
1690 }
1691 linesCounter++;
1692 }
1693
1694 Date maxPromisedDate = currentDate;
1695 Date linePromisedDate = new Date();
1696 for (OrderLine orderline : order.getOrderLineList()) {
1697 if (StringUtils.isNotEmpty(orderline.getScDpasRating())
1698 && orderline.getScDpasRating().startsWith("DX"))
1699 RefDataUtil.updateRefData(RefDataObjectType.C_ORDERLINE, orderline,
1700 RefDataNames.DPAS_PRIORITY_DX_, RefDataSource.SYSTEM_LOAD_PROCESS,
1701 RefDataValues.A_DPAS_DX_RATED_YES, false, null);
1702
1703 // populate Scheduled Delivery Date (DatePromised) at header
1704 // If PAI exists, current date + lead time
1705 // If PAI does not exist, use Contractual Delivery Date from xmlLine. Can use value from
1706 // BaselinePromiseDate as this c_orderline field will contain Contractual Delivery Date
1707
1708 if (orderline.getSCPURCHAGREEMENTITEM() != null) {
1709 Long leadTime = (long) (currentDate.getTime()
1710 + orderline.getSCPURCHAGREEMENTITEM().getLeadTime() * NUM_MS_IN_DAY);
1711 linePromisedDate.setTime(leadTime);
1712 } else {
1713 if (orderline.getScBaselinePromiseDate() != null) {
1714 linePromisedDate = orderline.getScBaselinePromiseDate();
1715 }
1716 }
1717 if (linePromisedDate.after(maxPromisedDate)) {
1718 maxPromisedDate = linePromisedDate;
1719 }
1720 }
1721 order.setScheduledDeliveryDate(maxPromisedDate);
1722
1723 // WPS-7191 Moving this code outside of if to run for all orgs other than TSI
1724 // CopyFromCRFQToSO.copyExternalCRFQLineNotes(order);
1725 CopyFromCRFQToSO.copyRefData(order);
1726 CopyFromCRFQToSO.updateCRFQStatus(order);
1727
1728 }
1729
1730 if (!order.getOrganization().getName().contains("TSI")) {
1731 CopyFromCRFQToSO.copyExternalCRFQLineNotes(order);
1732 }
1733
1734 // Specific to Tires
1735 if (order.getOrganization().getName().contains("TSI")) {
1736 logger.logln("Add Reference Data for TSI");
1737
1738 // DPAS Priority Rating
1739 order.setScDlaPriorityRating(getDPASPriorityRatingForHeader(order));
1740
1741 // Inv Pull
1742 order.setScInventoryPull(true);
1743
1744 // Delivery Date
1745 if (order.getScNeedDate() == null || order.getScheduledDeliveryDate() == null
1746 || order.getScNeedDate().equals("") || order.getScheduledDeliveryDate().equals("")) {
1747 Date monthFromToday = DateUtils.addDays(currentDate, 30);
1748 order.setScNeedDate(monthFromToday);
1749 order.setScheduledDeliveryDate(monthFromToday);
1750 }
1751
1752 // Distribution Center
1753 setTSIWarehouse(order, cp);
1754
1755 // Ship-to Location, Required Delivery Date
1756 double totalSellingPrice = 0.0;
1757 if (!order.getOrderLineList().isEmpty()) {
1758 for (OrderLine ol : order.getOrderLineList()) {
1759
1760 if (StringUtils.isNotEmpty(ol.getScDpasRating()) && ol.getScDpasRating().startsWith("DX"))
1761 RefDataUtil.updateRefData(RefDataObjectType.C_ORDERLINE, ol,
1762 RefDataNames.DPAS_PRIORITY_DX_, RefDataSource.SYSTEM_LOAD_PROCESS,
1763 RefDataValues.A_DPAS_DX_RATED_YES, false, null);
1764
1765 // Require COC/DD250
1766 BigDecimal orderedQty = (ol.getOrderedQuantity() != null) ? ol.getOrderedQuantity()
1767 : BigDecimal.ZERO;
1768 BigDecimal unitPrice = (ol.getUnitPrice() != null) ? ol.getUnitPrice() : BigDecimal.ZERO;
1769 totalSellingPrice += orderedQty.multiply(unitPrice).doubleValue();
1770
1771 // Ship-to
1772 logger.logln("Clear order's delivery location");
1773 order.setDeliveryLocation(null);
1774
1775 // Required Delivery Date
1776 findRequiredDeliveryDate(order, ol, order.getOrderDate());
1777
1778 // WYOM-11922: Populate Scheduled Delivery Date and Original Baseline Promise Date with
1779 // same value as Baseline Promise Date
1780 Date baselinePromiseDate = ol.getScBaselinePromiseDate();
1781 ol.setScheduledDeliveryDate(baselinePromiseDate);
1782 ol.setScOrigBaselinePromDate(baselinePromiseDate);
1783
1784 // Generate an alert if there is a DO/DX mismatch
1785 if (StringUtils.isNotEmpty(ol.getScDpasRating()) && ol.getScDpasRating().startsWith("DX")
1786 && !ol.getProduct().isScIsDx()) {
1787
1788 String description = "Order " + order.getDocumentNo() + " ("
1789 + order.getScRequisitionNumber() + ", " + ol.getProduct().getScFscg() + ""
1790 + ol.getProduct().getScNiin() + ", " + ol.getOrderedQuantity()
1791 + ") loaded as DX priority but is not a DX product.";
1792
1793 AlertUtils.createAlert(DODX_MISMATCH_ALERT_ID, description, order.getWarehouse());
1794
1795 } else if ((!StringUtils.isNotEmpty(ol.getScDpasRating())
1796 || !ol.getScDpasRating().startsWith("DX")) && ol.getProduct().isScIsDx()) {
1797
1798 String description = "Order " + order.getDocumentNo() + " ("
1799 + order.getScRequisitionNumber() + ", " + ol.getProduct().getScFscg() + ""
1800 + ol.getProduct().getScNiin() + ", " + ol.getOrderedQuantity()
1801 + ") loaded as DO priority but is a DX product.";
1802
1803 AlertUtils.createAlert(DODX_MISMATCH_ALERT_ID, description, order.getWarehouse());
1804 }
1805 OBDal.getInstance().save(ol);
1806 }
1807 }
1808
1809 // Require COC/DD250
1810 if (TSI_FMS_ORG_ID.equals(order.getOrganization().getId()) || totalSellingPrice > 100000) {
1811 order.setScRequiresCocDd250(true);
1812 } else {
1813 order.setScRequiresCocDd250(false);
1814 }
1815
1816 // Priority
1817 order.setPriority("5");
1818
1819 // Is FSL
1820 order.setScIsfsl(false);
1821 }
1822
1823 // Specific to POLCHEM
1824 if (order.getOrganization().getName().startsWith("POLCHEM")) {
1825 logger.logln("Add Reference Data for POLCHEM");
1826
1827 String dodaac = "";
1828 for (OrderLine ol : order.getOrderLineList()) {
1829 if (ol.getScShipToDodaac() != null) {
1830 dodaac = ol.getScShipToDodaac();
1831 if (dodaac.startsWith("NUK")) {
1832 dodaac = "N68733";
1833 }
1834 }
1835 }
1836
1837 // Inv Pull
1838 order.setScInventoryPull(true);
1839
1840 // Delivery Date
1841 if (order.getScNeedDate() == null || order.getScheduledDeliveryDate() == null
1842 || order.getScNeedDate().equals("") || order.getScheduledDeliveryDate().equals("")) {
1843 Date monthFromToday = DateUtils.addDays(currentDate, 30);
1844 order.setScNeedDate(monthFromToday);
1845 order.setScheduledDeliveryDate(monthFromToday);
1846 }
1847
1848 // Distribution Center
1849 setPOLCHEMWarehouse(order, dodaac);
1850
1851 // Ship-to Location, Required Delivery Date
1852 double totalSellingPrice = 0.0;
1853 if (!order.getOrderLineList().isEmpty()) {
1854 for (OrderLine ol : order.getOrderLineList()) {
1855
1856 if (!StringUtils.isEmpty(ol.getScShipToDodaac())) {
1857 String dodaacString = ol.getScShipToDodaac();
1858 OBCriteria<CustomerDodaac> dodaacCheck = OBDal.getInstance()
1859 .createCriteria(CustomerDodaac.class);
1860 dodaacCheck.add(Restrictions.eq(CustomerDodaac.PROPERTY_DODAAC, dodaacString));
1861 dodaacCheck
1862 .add(Restrictions.eq(CustomerDodaac.PROPERTY_ORGANIZATION, ol.getOrganization()));
1863 dodaacCheck.add(Restrictions.eq(CustomerDodaac.PROPERTY_ACTIVE, true));
1864 List<CustomerDodaac> dodaacCheckList = dodaacCheck.list();
1865 if (dodaacCheckList.size() > 1) {
1866 // New alert: DoDAAC mapped to multiple hubs
1867 String description = "DoDAAC " + dodaacString + " mapped to multiple hubs. ";
1868 description += "For Polchem Sales Order, " + order.getDocumentNo();
1869 description += " - Line " + ol.getLineNo().toString() + ", hub "
1870 + ol.getWarehouse().getName() + " has been assigned";
1871 AlertUtil.createAlert(POLCHEM_BUYER_ROLE_ID, SAIC_ALERT, description, null,
1872 order.getOrganization());
1873 }
1874 }
1875
1876 if (StringUtils.isNotEmpty(ol.getScDpasRating()) && ol.getScDpasRating().startsWith("DX"))
1877 RefDataUtil.updateRefData(RefDataObjectType.C_ORDERLINE, ol,
1878 RefDataNames.DPAS_PRIORITY_DX_, RefDataSource.SYSTEM_LOAD_PROCESS,
1879 RefDataValues.A_DPAS_DX_RATED_YES, false, null);
1880
1881 // Ship-to
1882 logger.logln("Clear order's delivery location");
1883 order.setDeliveryLocation(null);
1884
1885 // Required Delivery Date
1886 findRequiredDeliveryDate(order, ol, order.getOrderDate());
1887
1888 ol.setWarehouse(order.getWarehouse());
1889 order.setScOrigWarehouse(order.getWarehouse());
1890
1891 OBDal.getInstance().save(ol);
1892 }
1893 }
1894
1895 // Priority
1896 order.setPriority("5");
1897
1898 // Is FSL
1899 order.setScIsfsl(false);
1900 }
1901
1902 // create any additional sales order load rules (ref data)
1903 // for the sales order/sales order lines
1904 log.debug("adding additional sales order line instructions.");
1905 attachAdditionalSalesOrderLineInstructions(order);
1906
1907 OBDal.getInstance().save(order);
1908 OBDal.getInstance().flush();
1909 // Attach discounts to the sales order
1910 log.debug("Attaching discounts to the sales order.");
1911 attachOrderDiscounts(order);
1912
1913 OBDal.getInstance().save(order);
1914
1915 if (!ProcessEUtil.isTransfer(order) && order.getOrganization().getOrganizationInformationList()
1916 .get(0).isScCalcMonthlyDemand()) {
1917 // WYOM-8645: keep a running total of the current month demand
1918 DemandHistoryManager demandHistoryManager = new DemandHistoryManager();
1919 for (OrderLine orderLine : order.getOrderLineList()) {
1920 // increment the 'current month' demand for the based on order date
1921 demandHistoryManager.incrementCurrentMonthDemand(order.getOrderDate(),
1922 orderLine.getProduct(), order.getScOrigWarehouse(), orderLine.getOrganization(),
1923 orderLine.getOrderedQuantity());
1924 }
1925 }
1926
1927 // Commit first but don't close - WYOM-4800
1928
1929 try {
1930 // _bundle.getConnection().getConnection().commit();
1931 SessionHandler.getInstance().commitAndStart();
1932
1933 } catch (Exception e) {
1934 logger.logln("Error encountered committing the transaction: " + e.getMessage());
1935 log.error("Error occurred committing the transaction", e);
1936 errorCounter++;
1937 TransmissionUtils.createTransmissionError("Error occurred committing the transaction", e);
1938 throw new OBException("Error occurred committing the transaction", e);
1939 }
1940
1941 String orderId = order.getId(); // should have it from the result of the save and commit
1942 for (OrderLine orderLine : order.getOrderLineList()) {
1943 OBDal.getInstance().getSession().evict(orderLine);
1944 }
1945 OBDal.getInstance().getSession().evict(order);
1946 order = OBDal.getInstance().get(Order.class, orderId);
1947 // at this point the order will be pulled from the DB and all of its lines will also be pulled
1948 // from DB
1949 Hibernate.initialize(order.getOrderLineList()); // make sure the orderline list is populated
1950 // (may not be needed)
1951
1952 log.debug("OB was updated by " + order.getId());
1953 orderCreatedCounter++;
1954
1955 // Now trigger workflow to run autorec (The next status is dependent on type of contract for
1956 // the sales order - LK 2/22/12)
1957 log.debug("Triggering sales order workflow.");
1958 triggerWorkflow(order, _bundle);
1959 // Commit and close - WYOM-4800
1960 try {
1961 OBDal.getInstance().commitAndClose();
1962 } catch (Exception e) {
1963 logger.logln("Error encountered committing the transaction: " + e.getMessage());
1964 log.error("Error occurred committing the transaction", e);
1965 errorCounter++;
1966 TransmissionUtils.createTransmissionError("Error occurred committing the transaction", e);
1967 throw new OBException("Error occurred committing the transaction", e);
1968 }
1969
1970 return true;
1971 }
1972
1973 /**
1974 * Trigger sales order workflow
1975 *
1976 * @param order
1977 * @param pb
1978 */
1979 public Set<OBError> triggerWorkflow(Order order, ProcessBundle pb) {
1980 String autoRecStrategy = order.getOrganization().getScAutorecStrategy();
1981 String nextStatus = StatusHelper.HEADER_ACCEPTED;
1982 String docTypeName = order.getDocumentType().getName();
1983
1984 // treat storefront orders that are DVD as if non-storefront orders
1985 if (order.isScInventoryPull()
1986 && CustomerUtil.isStorefrontCustomer(order.getBusinessPartner())) {
1987 nextStatus = StatusHelper.HEADER_STOREFRONT_HOLD;
1988 } else if (autoRecStrategy != null && (autoRecStrategy.equals(AutoRecService.PVMRO_TYPE)
1989 || autoRecStrategy.equals(AutoRecService.TLSPV_TYPE_2014)
1990 || (autoRecStrategy.equals(AutoRecService.PVMRO_TYPE_STOREFRONT)
1991 || autoRecStrategy.equals(AutoRecService.TLSPV_TYPE_STOREFRONT_2014)
1992 && docTypeName.equalsIgnoreCase(AutoRecService.STANDARD_ORDER_DOC_TYPE))))
1993 nextStatus = StatusHelper.HEADER_READY_FOR_DLA;
1994
1995 // Add logic for OEMA - Status will go to On Hold - WYOM-4800
1996 else if (autoRecStrategy != null && autoRecStrategy.equals(AutoRecService.OEMA_TYPE)) {
1997 nextStatus = StatusHelper.HEADER_ON_HOLD;
1998
1999 } else if (autoRecStrategy != null && autoRecStrategy.equals(AutoRecService.TEIS_TYPE)) {
2000 nextStatus = StatusHelper.HEADER_ON_HOLD;
2001
2002 } else if (autoRecStrategy != null && autoRecStrategy.equals(AutoRecService.TSI_TYPE)) {
2003 nextStatus = StatusHelper.HEADER_ALLOCATED;
2004
2005 } else if (autoRecStrategy != null && autoRecStrategy.equals(AutoRecService.POLCHEM_TYPE)) {
2006 nextStatus = StatusHelper.HEADER_AWAITING_ALLOCATION;
2007 }
2008 return TriggerWorkflowHelper.triggerWorkflowSO(pb, order, nextStatus);
2009 }
2010
2011 /**
2012 * Attach additional sales order line instructions.
2013 *
2014 * @param order
2015 * the order
2016 */
2017 public void attachAdditionalSalesOrderLineInstructions(Order order) {
2018 RefDataName refDataName = RefDataUtil
2019 .getRefDataName(RefDataNames.ADDITIONAL_SALES_ORDER_LINE_INSTRUCTIONS);
2020 for (OrderLine orderline : order.getOrderLineList()) {
2021 SalesOrderLoadRuleActionProvider ruleProvider = new SalesOrderLoadRuleActionProvider();
2022 List<SalesOrderLoadRules> loadRules = ruleProvider.findSalesOrderLoadRuleActions(orderline);
2023 for (SalesOrderLoadRules loadRule : loadRules) {
2024 if (!RefDataValues.ADDNL_SOL_INSTR_OVERRIDE_DEFAULT_DISTRIBUTION_CENTER.getValue()
2025 .equals(loadRule.getRuleAction().getSearchKey())) {
2026 RefDataUtil.createRefData(RefDataObjectType.C_ORDERLINE, orderline, refDataName,
2027 RefDataSource.SYSTEM_LOAD_PROCESS, loadRule.getRuleAction(), false, null);
2028 String prefix = loadRule.getRuleAction().getCommercialName()
2029 + " instruction added to order due to match on ";
2030 List<String> matches = new ArrayList<String>();
2031 if (loadRule.getDODAAC() != null) {
2032 matches.add("DODAAC: " + loadRule.getDODAAC().getDodaac());
2033 }
2034 if (loadRule.getSKU() != null) {
2035 matches.add("SKU: " + loadRule.getSKU().getSKU());
2036 }
2037 if (loadRule.getProjectCodeStartsWith() != null) {
2038 matches.add("Project Code Starts With: " + loadRule.getProjectCodeStartsWith());
2039 }
2040 if (matches.isEmpty() && RefDataValues.ADDNL_SOL_INSTR_PALLETIZED.getValue()
2041 .equals(loadRule.getRuleAction().getSearchKey())) {
2042 // this is a palletization that did not match any load rules, so we need to specify why
2043 // it is palletized
2044 CustomerDodaac dodaac = ruleProvider.getDodaac(orderline);
2045 if (dodaac != null && dodaac.isRequirePalletization()) {
2046 matches
2047 .add("DODAAC: " + dodaac.getDodaac() + " is flagged as requiring palletization.");
2048 }
2049 if (orderline.getWarehouse() != null
2050 && orderline.getWarehouse().isScRequirePalletization()) {
2051 matches.add("Warehouse: " + orderline.getWarehouse().getName()
2052 + " is flagged as requiring palletization.");
2053 }
2054 if (ruleProvider.doesProductWeightRequirePalletization(orderline.getOrganization(),
2055 orderline.getProduct(), orderline.getOrderedQuantity())) {
2056 matches.add("SKU: " + orderline.getProduct().getSKU()
2057 + " has a weight restriction that was exceeded, requiring palletization.");
2058 }
2059 }
2060
2061 try {
2062 NotesUtil.createNoteForSO(order, prefix + StringUtils.join(matches, ", "));
2063 } catch (Exception e) {
2064 log.error("Issue creating Sales Order Line Instructions note");
2065 logger.logln("Issue creating Sales Order Line Instructions note");
2066 }
2067 // WYOM-8161: for orderline's who have a 'Ship to Staging' rule attached
2068 // modify the c_bpartner_location (ship to) and dodaac with the staging location
2069 // from the order's org info (if none found throws OBException)
2070 if (RefDataValues.ADDNL_SOL_INSTR_SHIP_TO_STAGING_LOCATION.getValue()
2071 .equals(loadRule.getRuleAction().getSearchKey())) {
2072 orderline.setPartnerAddress(loadRule.getStagingBpartnerLocation());
2073 if (loadRule.getStagingBpartnerLocation() != null) {
2074 if (loadRule.getStagingBpartnerLocation().getLocationAddress() != null
2075 && loadRule.getStagingBpartnerLocation().getLocationAddress()
2076 .getScLocationCode() != null
2077 && loadRule.getStagingBpartnerLocation().getLocationAddress().getScLocationCode()
2078 .length() <= 6) {
2079 orderline.setScShipToDodaac(
2080 loadRule.getStagingBpartnerLocation().getLocationAddress().getScLocationCode());
2081 } else if (loadRule.getStagingBpartnerLocation().getName() != null
2082 && loadRule.getStagingBpartnerLocation().getName().length() <= 6) {
2083 orderline.setScShipToDodaac(loadRule.getStagingBpartnerLocation().getName());
2084 }
2085 }
2086 }
2087 }
2088 }
2089 // WYOM-9778: for orderline's who have a 'Override Default Distribution Center' rule attached,
2090 // look for the Demand Type to match (OCONUS, CONUS, Both) and update warehouse at both order
2091 // and orderline level
2092 CustomerDodaac dodaac = new SalesOrderLoadRuleActionProvider().getDodaac(orderline);
2093 String projectCode = new SalesOrderLoadRuleActionProvider().getProjectCode(orderline);
2094 List<SalesOrderLoadRules> loadRulesODDC = new SalesOrderLoadRuleActionProvider()
2095 .findOverrideDefaultDistributionCenterSOLoadRules(orderline.getOrganization(),
2096 orderline.getProduct(), dodaac, projectCode, false, null);
2097 for (SalesOrderLoadRules loadRule : loadRulesODDC) {
2098 if (!StringUtils.isEmpty(loadRule.getDemandType()) && loadRule.getCurrentWarehouse() != null
2099 && loadRule.getNEWWarehouse() != null) {
2100 String demandType = loadRule.getDemandType();
2101 // is conus can be null, so check it as null safe
2102 boolean orderLineIsConus = Boolean.TRUE.equals(orderline.isScIsconus());
2103 boolean updateWarehouse = false;
2104 String remark = "";
2105 if ("3".equals(demandType)
2106 && (orderline.getWarehouse()).equals(loadRule.getCurrentWarehouse())) {
2107 updateWarehouse = true;
2108 remark = "Both";
2109 } else if ("1".equals(demandType) && orderLineIsConus
2110 && (orderline.getWarehouse()).equals(loadRule.getCurrentWarehouse())) {
2111 updateWarehouse = true;
2112 remark = "CONUS";
2113 } else if ("2".equals(demandType) && !orderLineIsConus
2114 && (orderline.getWarehouse()).equals(loadRule.getCurrentWarehouse())) {
2115 updateWarehouse = true;
2116 remark = "OCONUS";
2117 }
2118 if (updateWarehouse) {
2119 // Add Line Ref Data
2120 RefDataUtil.createRefData(RefDataObjectType.C_ORDERLINE, orderline, refDataName,
2121 RefDataSource.SYSTEM_LOAD_PROCESS, loadRule.getRuleAction(), false, remark);
2122 String prefix = loadRule.getRuleAction().getCommercialName()
2123 + " instruction added to order due to match on ";
2124 List<String> matches = new ArrayList<String>();
2125 if (loadRule.getDODAAC() != null) {
2126 matches.add("DODAAC: " + loadRule.getDODAAC().getDodaac());
2127 }
2128 if (loadRule.getSKU() != null) {
2129 matches.add("SKU: " + loadRule.getSKU().getSKU());
2130 }
2131 if (loadRule.getProjectCodeStartsWith() != null) {
2132 matches.add("Project Code Starts With: " + loadRule.getProjectCodeStartsWith());
2133 }
2134 // Add note to Sales Order
2135 try {
2136 NotesUtil.createNoteForSO(order, prefix + StringUtils.join(matches, ", "));
2137 } catch (Exception e) {
2138 log.error("Issue creating Sales Order Line Instructions note");
2139 logger.logln("Issue creating Sales Order Line Instructions note");
2140 }
2141 order.setWarehouse(loadRule.getNEWWarehouse());
2142 OBDal.getInstance().save(order);
2143 orderline.setWarehouse(loadRule.getNEWWarehouse());
2144 OBDal.getInstance().save(orderline);
2145 }
2146 }
2147 }
2148 }
2149 }
2150
2151 /**
2152 * Gets the price list Name
2153 *
2154 * @param order
2155 * ID
2156 * @return docStatus
2157 * @throws ServletException
2158 */
2159 public PriceList getPList(BusinessPartner bPartner) throws ServletException {
2160 PriceList pl = bPartner.getPriceList();
2161 if (pl == null || !pl.isSalesPriceList() || !pl.isDefault()) {
2162 CustomerPartner cp = OBUtils.getCustomerPartner(bPartner);
2163 if (cp != null) {
2164 DOMAIN dom = cp.getDomain();
2165 if (dom != null) {
2166 PriceListVersion plv = dom.getPriceListVersion();
2167 if (plv != null)
2168 pl = plv.getPriceList();
2169 }
2170 }
2171 }
2172 return pl;
2173 }
2174
2175 /**
2176 * Sets Invoice address by the default billto address
2177 *
2178 * @param order
2179 * @param businessPartnerId
2180 * @throws ServletException
2181 */
2182 private void setInvoiceAddressByDefultBillToAddress(Order order, BusinessPartner businessPartner)
2183 throws ServletException {
2184 order.setInvoiceAddress(getBPLocation(businessPartner, true, false));
2185 }
2186
2187 /**
2188 * Gets the payment terms Name
2189 *
2190 * @param order
2191 * ID
2192 * @return docStatus
2193 * @throws ServletException
2194 */
2195 public Currency getCurrenyCode(BusinessPartner bPartner) throws ServletException {
2196 if (bPartner.getPriceList() != null)
2197 return bPartner.getPriceList().getCurrency();
2198 else
2199 return null;
2200 }
2201
2202 /**
2203 * There are a few different places to look in order to determine which Payment term to use.
2204 *
2205 * 1) if the business partner is a vendor (isvendor flag), then look for a non-null value in
2206 * po_paymentterm_id in c_bpartner. If it is null, then that is the c_paymentterm_id for the
2207 * correct payment term (in c_paymentterm) to use.
2208 *
2209 * 2) If the business partner is a customer (iscustomer flag), then look for a non-null value in
2210 * c_paymentterm_id in c_bpartner. If it is null, then that is the c_paymentterm_id for the
2211 * correct payment term (in c_paymentterm) to use
2212 *
2213 *
2214 *
2215 * 3) If both of those fields are nulls, then we need to look for a default value in
2216 * c_paymentterm. Check the isdefault flag (as well as isvalid). If more than one are marked as
2217 * default and valid, take the first one found.
2218 *
2219 * We will stress that one payment term should be marked as default. But if you cannot find one
2220 * marked as default, then merely take the first payment term you read and use that.
2221 */
2222 public PaymentTerm getPayTerms(BusinessPartner bPartner) throws ServletException {
2223 PaymentTerm term = null;
2224 if (bPartner.isCustomer()) {
2225 term = bPartner.getPaymentTerms();
2226 } else if (bPartner.isVendor()) {
2227 term = bPartner.getPOPaymentTerms();
2228 }
2229 if (term == null) {
2230 OBCriteria<PaymentTerm> crit = OBDal.getInstance().createCriteria(PaymentTerm.class);
2231 crit.add(Restrictions.eq(PaymentTerm.PROPERTY_DEFAULT, true));
2232 crit.add(Restrictions.eq(PaymentTerm.PROPERTY_VALID, true));
2233 List<PaymentTerm> terms = crit.list();
2234 if (terms.size() > 0)
2235 term = terms.get(0);
2236 }
2237 return term;
2238 }
2239
2240 public PaymentTerm getPayTermsByName(String name) {
2241 PaymentTerm pTerm = null;
2242 final OBCriteria<PaymentTerm> paymentTerm = OBDal.getInstance()
2243 .createCriteria(PaymentTerm.class);
2244
2245 paymentTerm.add(Restrictions.eq(PaymentTerm.PROPERTY_NAME, name).ignoreCase());
2246 final List<PaymentTerm> pt = paymentTerm.list();
2247 logger.logln("Payment Terms found for " + name + " :" + pt.size());
2248 if (pt.size() > 0) {
2249 pTerm = pt.get(0);
2250 }
2251 return pTerm;
2252 }
2253
2254 // Given a Milstrip Priority, map to valid OB priority to populate in priorityrule field
2255 public String convertMilstripPriToOBPri(String strPOpriority) {
2256
2257 // Default is lowest priority
2258 String priority = null;
2259 if (MILSTRIP_PRIORITY_HIGH.contains(strPOpriority)) {
2260 priority = "3";
2261 } else if (MILSTRIP_PRIORITY_MEDIUM.contains(strPOpriority)) {
2262 priority = "5";
2263 } else if (MILSTRIP_PRIORITY_LOW.contains(strPOpriority)) {
2264 priority = "7";
2265 } else if (MILSTRIP_NO_PRIORITY.equals(strPOpriority)) {
2266 priority = "SC_9";
2267 }
2268 return priority;
2269 }
2270
2271 /**
2272 * Sets the Partner address by default shipto address
2273 *
2274 * @param order
2275 * @param businessPartnerId
2276 * @throws ServletException
2277 */
2278 public void setPartnerAddressByDefultShipToAddress(Order order, BusinessPartner businessPartner)
2279 throws ServletException {
2280 Location loc = getBPLocation(businessPartner, false, true);
2281 if (loc == null)
2282 return;
2283 order.setPartnerAddress(loc);
2284 order.setDeliveryLocation(loc);
2285 }
2286
2287 /**
2288 * Sets the Partner address by default shipto address
2289 *
2290 * @param order
2291 * @param businessPartnerId
2292 * @throws ServletException
2293 */
2294 private void setVendorAddressByDefultShipToAddress(OrderLine orderline,
2295 BusinessPartner businessPartner) {
2296 orderline.setPartnerAddress(getBPLocation(businessPartner, false, true));
2297 }
2298
2299 /**
2300 * Gets BP location ID for this BP
2301 *
2302 * @param c_bpartner_Id
2303 * @param isDefaultBilling
2304 * @param isDefaultShipping
2305 * @return bpartner_location_id
2306 * @throws ServletException
2307 */
2308 public Location getBPLocation(BusinessPartner businessPartner, boolean defaultBilling,
2309 boolean defaultShipping) {
2310 OBCriteria<Location> crit = OBDal.getInstance().createCriteria(Location.class);
2311 crit.add(Restrictions.eq(Location.PROPERTY_BUSINESSPARTNER, businessPartner));
2312 if (defaultBilling)
2313 crit.add(Restrictions.eq(Location.PROPERTY_INVOICETOADDRESS, true));
2314 if (defaultShipping)
2315 crit.add(Restrictions.eq(Location.PROPERTY_SHIPTOADDRESS, true));
2316 crit.add(Restrictions.eq(Location.PROPERTY_ACTIVE, true));
2317 List<Location> locations = crit.list();
2318 if (locations.size() > 0)
2319 return locations.get(0);
2320 else
2321 return null;
2322 }
2323
2324 public Location getPartnerAddress(BusinessPartner businessPartner) {
2325 OBCriteria<Location> crit = OBDal.getInstance().createCriteria(Location.class);
2326 crit.add(Restrictions.eq(Location.PROPERTY_BUSINESSPARTNER, businessPartner));
2327 crit.add(Restrictions.eq(Location.PROPERTY_INVOICETOADDRESS, true));
2328 crit.add(Restrictions.eq(Location.PROPERTY_ACTIVE, true));
2329 Location customerLocation = null;
2330 Location otherLoc = null;
2331 for (Location loc : crit.list()) {
2332 org.openbravo.model.common.geography.Location locAddr = loc.getLocationAddress();
2333 if (locAddr != null && "098BA".equals(locAddr.getScLocationType()))
2334 return loc;
2335 else if (locAddr != null && locAddr.getScLocationCode() != null
2336 && locAddr.getScLocationCode().startsWith("CC")) {
2337 customerLocation = loc;
2338 } else {
2339 otherLoc = loc;
2340 }
2341 }
2342
2343 if (customerLocation != null)
2344 return customerLocation;
2345 else
2346 return otherLoc;
2347 }
2348
2349 /**
2350 * Sets TSI Warehouse
2351 *
2352 */
2353 public void setTSIWarehouse(Order order, CustomerPartner cp) {
2354
2355 Warehouse warehouse = null;
2356
2357 // Warehouse from Customer Partner's Crossdock Customer
2358 if (cp != null) {
2359
2360 // Check Customer Dodaac to see if Warehouse is not null
2361 String dodaac = order.getScRequisitionNumber().substring(0, 6);
2362 OBCriteria<CustomerDodaac> dodaacCrit = OBDal.getInstance()
2363 .createCriteria(CustomerDodaac.class);
2364 dodaacCrit.add(Restrictions.eq(CustomerDodaac.PROPERTY_DODAAC, dodaac));
2365 dodaacCrit.add(Restrictions.eq(CustomerDodaac.PROPERTY_CUSTOMERPARTNER, cp));
2366 if (dodaacCrit.list() != null && dodaacCrit.list().size() > 0) {
2367 CustomerDodaac custDodaac = dodaacCrit.list().get(0);
2368 if (custDodaac.getWarehouse() != null) {
2369 warehouse = custDodaac.getWarehouse();
2370 order.setWarehouse(warehouse);
2371 }
2372 }
2373
2374 // Check Customer Crossdock if warehouse not found on dodaac
2375 if (warehouse == null) {
2376 OBCriteria<CustomerConfig> custConfigCriteria = OBDal.getInstance()
2377 .createCriteria(CustomerConfig.class);
2378 custConfigCriteria.add(Restrictions.eq(CustomerConfig.PROPERTY_CUSTOMERPARTNER, cp));
2379 List<CustomerConfig> ccList = custConfigCriteria.list();
2380 if (!ccList.isEmpty()) {
2381 CustomerConfig cc = ccList.get(0);
2382 if (cc.getWarehouse() != null) {
2383 warehouse = cc.getWarehouse();
2384 order.setWarehouse(cc.getWarehouse());
2385 }
2386 }
2387 }
2388 }
2389
2390 if (warehouse == null) {
2391
2392 OBCriteria<Warehouse> whCrit = OBDal.getInstance().createCriteria(Warehouse.class);
2393
2394 if (order.getOrganization().getName().startsWith("TSI"))
2395 whCrit.add(Restrictions.eq(Warehouse.PROPERTY_NAME, "Tires Fort Worth"));
2396
2397 if (whCrit.list() != null && whCrit.list().size() > 0) {
2398 Warehouse wh = whCrit.list().get(0);
2399 order.setWarehouse(wh);
2400 }
2401 }
2402
2403 for (OrderLine ol : order.getOrderLineList()) {
2404 ol.setWarehouse(order.getWarehouse());
2405 OBDal.getInstance().save(ol);
2406
2407 }
2408
2409 order.setScOrigWarehouse(order.getWarehouse());
2410 OBDal.getInstance().save(order);
2411 }
2412
2413 /**
2414 * Sets POLCHEM Warehouse
2415 *
2416 */
2417 public void setPOLCHEMWarehouse(Order order, String dodaac) {
2418 if (order != null && !StringUtils.isEmpty(dodaac)) {
2419 StringBuilder hqlString = new StringBuilder();
2420 hqlString.append("SELECT cc.warehouse");
2421 hqlString.append(" FROM SC_CrossdockCustomer cc, SC_CUSTOMER_DODAAC cd");
2422 hqlString.append(" WHERE cc.active = true AND cd.active = true");
2423 hqlString.append(" AND cc.organization.id =");
2424 hqlString.append("'" + order.getOrganization().getId() + "'");
2425 hqlString.append(" AND cd.organization.id =");
2426 hqlString.append("'" + order.getOrganization().getId() + "'");
2427 hqlString.append(" AND cc.customerPartner IS NOT NULL AND cd.customerPartner IS NOT NULL");
2428 hqlString.append(" AND cc.customerPartner = cd.customerPartner");
2429 hqlString.append(" AND cc.warehouse IS NOT NULL");
2430 hqlString.append(" AND cd.dodaac = ");
2431 hqlString.append("'" + dodaac + "'");
2432 Session session = OBDal.getInstance().getSession();
2433 Query query = session.createQuery(hqlString.toString());
2434 List<Warehouse> warehouses = query.list();
2435 if (warehouses != null && !warehouses.isEmpty() && warehouses.size() > 0) {
2436 order.setWarehouse(warehouses.get(0));
2437 }
2438
2439 if (!order.getOrderLineList().isEmpty()) {
2440 for (OrderLine ol : order.getOrderLineList()) {
2441 ol.setWarehouse(order.getWarehouse());
2442 OBDal.getInstance().save(ol);
2443 }
2444 }
2445
2446 order.setScOrigWarehouse(order.getWarehouse());
2447 OBDal.getInstance().save(order);
2448
2449 }
2450 }
2451
2452 /**
2453 * Creates an OrderLine
2454 *
2455 * @param order
2456 * (Header)
2457 * @param shipToAddress
2458 * @throws Exception
2459 */
2460 public OrderLine createLine(Order order, CustomerSO so, CustomerSOLineItem line,
2461 BusinessPartner businessPartner, Client cName, Location shipToAddress, SystemType source)
2462 throws Exception {
2463
2464 Product product = null;
2465 String productName = line.getSAICPartNumber();
2466 String partNumber = line.getPartNumber();
2467 String vendCode = line.getVendorCode();
2468
2469 if (vendCode != null) {
2470 try {
2471 vendorSynchronization(vendCode);
2472 } catch (Exception e) {
2473 log.error("Unable to retrieve vendor for line " + line.getLineNumber(), e);
2474 TransmissionUtils.createTransmissionError(
2475 "Unable to retrieve vendor for line " + line.getLineNumber(), e);
2476 throw new OBException("Unable to retrieve vendor for line " + line.getLineNumber(), e);
2477 }
2478 }
2479
2480 log.debug("partNumber" + partNumber);
2481 log.debug("productName" + productName);
2482
2483 Date promiseDate = line.getPromiseDate() == null ? null : line.getPromiseDate().toDate();
2484 String purchaseAgreementItemId = line.getPurchaseAgreementItemId();
2485
2486 String deliveryOrder = line.getDeliveryOrder();
2487 if (deliveryOrder == null) {
2488 deliveryOrder = order.getScDelOrd();
2489 }
2490 String proposalItemId = line.getProposalItemId();
2491 try {
2492 product = SalesOrderDao.findProduct(order.getOrganization(), so, line, productName,
2493 partNumber, proposalItemId, logger, order);
2494
2495 if (product == null) {
2496 String msg = "Product " + productName + " not found in OB!";
2497 OBException exc = new OBException(msg);
2498 log.error(msg, exc);
2499 errorCounter++;
2500 TransmissionUtils.createTransmissionError(msg, exc);
2501 throw exc;
2502 }
2503
2504 } catch (Exception exc) {
2505 String msg = "Product " + productName
2506 + " is a order line, and exists in DB, but we had a failure in synching this product to OB!";
2507 log.error(msg, exc);
2508 errorCounter++;
2509 TransmissionUtils.createTransmissionError(msg, exc);
2510 throw new OBException(msg, exc);
2511 }
2512 proposalItemId = SalesOrderDao.findProposalItemId(order.getOrganization(), so, line, product);
2513 BigDecimal vendorPrice = line.getVendorCost() == null ? BigDecimal.ZERO : line.getVendorCost();
2514 BigDecimal sellPrice = line.getSellingPrice();
2515 BigDecimal invPrice = line.getInvoicePrice();
2516 BigDecimal quantity = new BigDecimal(line.getQuantity());
2517
2518 String Manufacturer = line.getManufacturerName();
2519 String PartDescription = line.getPartDescription();
2520 String SupplierPartNumber = line.getSupplierPartNumber();
2521 String DateRequired = line.getDateRequired();
2522 String NSN = line.getNSN();
2523 String TicketNumber = line.getTicketNumber();
2524 String proID = line.getProductID();
2525 String RequisitionNumber = line.getRequisitionNumber();
2526 String InvPull = line.getInvPull();
2527 String Comments = line.getComments();
2528 String LineNumber = line.getLineNumber();
2529 String UnitOfMeasure = line.getUnitOfMeasure();
2530 String fobpt = line.getFobPt();
2531 String inspPt = line.getInspPt();
2532 String additionalPkgInstructions = line.getAdditionalPkgInstructions();
2533 String extraAttributes = line.getExtraAttributes();
2534
2535 log.debug("ProductId......" + proID);
2536
2537 // Create OrderLine
2538 final OrderLine orderLine = OBProvider.getInstance().get(OrderLine.class);
2539
2540 // Setting Order header
2541 orderLine.setSalesOrder(order);
2542
2543 // Business Partner
2544 orderLine.setBusinessPartner(businessPartner);
2545
2546 // BP Location
2547 if (shipToAddress != null) {
2548 orderLine.setPartnerAddress(shipToAddress);
2549 } else if (!order.getOrganization().getName().contains("OEM")) {
2550 log.debug("setting vendor address as default ship to address");
2551 setVendorAddressByDefultShipToAddress(orderLine, businessPartner);
2552 }
2553
2554 // Product
2555 orderLine.setProduct(product);
2556
2557 try {
2558 orderLine.setLineNo(Long.parseLong(LineNumber.trim()));
2559 } catch (NumberFormatException e) {
2560 // For OEMA, sometimes line no can be alpha numeric. This value will be captured in
2561 // em_sc_customer_line_number. Since LineNo in SO line only accepts integer, assign sequence
2562 // integer starting with 1 to lineNo field.
2563 long linenum = order.getOrderLineList().size() + 1;
2564 orderLine.setLineNo(linenum);
2565 }
2566 if (line.getWyomingLineNo() != null && !line.getWyomingLineNo().isEmpty()) {
2567 orderLine.setScCustomerLineNo(line.getWyomingLineNo());
2568 } else {
2569 orderLine.setScCustomerLineNo(LineNumber);
2570 }
2571
2572 RequestItem ri = null;
2573 StringBuffer highlights = new StringBuffer();
2574 highlights.append(extraAttributes).append(" ");
2575 // proposal Id
2576 if (proposalItemId != null && !proposalItemId.isEmpty()) {
2577 ProposalItem pr = OBDal.getInstance().get(ProposalItem.class, proposalItemId);
2578 orderLine.setScProposalItem(pr);
2579
2580 // Highlights
2581 if (pr.getRequestItem() != null) {
2582 ri = pr.getRequestItem();
2583 if (pr.getRequestItem().getHighlights() != null) {
2584 highlights.append(pr.getRequestItem().getHighlights());
2585 }
2586 }
2587
2588 // set the purchase agreement item as well. However, if provided, it will be replaced below
2589 orderLine.setSCPURCHAGREEMENTITEM(pr.getPurchaseAgreementItem());
2590 } else {
2591 // orderLine.setScProposalItem("");
2592 // if purchase agreement item provided, it will be populated below
2593 orderLine.setSCPURCHAGREEMENTITEM(null);
2594 }
2595
2596 if (highlights.length() > 0) {
2597 orderLine.setScHighlights(highlights.toString());
2598 }
2599
2600 // purchase agreement item id
2601 if (purchaseAgreementItemId != null && !purchaseAgreementItemId.isEmpty()) {
2602 // retrieve PAI object to set to orderline
2603 PurchaseAgreementItem paItem = OBDal.getInstance().get(PurchaseAgreementItem.class,
2604 purchaseAgreementItemId);
2605 orderLine.setSCPURCHAGREEMENTITEM(paItem);
2606 }
2607
2608 // Promised Date line
2609 Date currentDate = new Date(System.currentTimeMillis());
2610 if (promiseDate != null) {
2611 orderLine.setScheduledDeliveryDate(promiseDate);
2612 } else {
2613 orderLine.setScheduledDeliveryDate(currentDate);
2614 }
2615
2616 orderLine.setScDelOrd(deliveryOrder);
2617
2618 // selling price of the product
2619 orderLine.setScSellPrice(sellPrice);
2620
2621 // Invoice Price
2622 orderLine.setScInvPrice(invPrice);
2623
2624 // Budget Unit Cost
2625 orderLine.setScBudgetUnitCost(invPrice);
2626
2627 // Vendor Price
2628 orderLine.setScVendPrice(vendorPrice);
2629
2630 // Order date
2631 orderLine.setOrderDate(order.getOrderDate());
2632
2633 // SAIC NEW Changes
2634
2635 // Manufacturer
2636 orderLine.setScMfrName(Manufacturer);
2637
2638 // ProductId
2639 log.debug("ProductId......" + proID);
2640 orderLine.setScCustomerPartNum(proID);
2641
2642 // RequisitionNumber
2643 orderLine.setScRequisitionNumber(RequisitionNumber);
2644
2645 // PartDescription
2646 if ((PartDescription != null) && (PartDescription.length() > 2000)) {
2647 orderLine.setDescription(PartDescription.substring(0, 2000));
2648 } else {
2649 orderLine.setDescription(PartDescription);
2650 }
2651
2652 // SupplierPartNumber
2653 orderLine.setScVendorproductno(SupplierPartNumber);
2654
2655 // DateRequired
2656 System.out.println("DateRequired..." + DateRequired);
2657 // Mallik-begins-DE233
2658 if (DateRequired != null && !DateRequired.equals("")) {
2659 log.debug("DateRequired..if...." + DateRequired);
2660 Date dateRequired = dateFormat.parse(DateRequired);
2661 orderLine.setScRequiredDeliveryDate(dateRequired);
2662 orderLine.setScNeedDate(dateRequired);
2663 } else {
2664
2665 String strOrderDateRequired = so.getOrderDateRequired();
2666 System.out.println("strOrderDateRequired.lines level.." + strOrderDateRequired);
2667 if (strOrderDateRequired != null && !strOrderDateRequired.equals("")) {
2668 try {
2669 Date orderDateRequired = DateParser.parseDateString(strOrderDateRequired);
2670 orderLine.setScRequiredDeliveryDate(orderDateRequired);
2671 orderLine.setScNeedDate(orderDateRequired);
2672 } catch (Exception e) {
2673 log.error("Error parsing DateRequired", e);
2674 TransmissionUtils.createTransmissionError("Error parsing DateRequired", e);
2675 throw new OBException("Error parsing DateRequired", e);
2676 }
2677 }
2678
2679 // Mallik-ends-DE233
2680 }
2681
2682 // NSN
2683 // WPS-701: get NSN from the product record
2684 NSN = "";
2685 if (product.getScNiin() != null && product.getScFscg() != null) {
2686 String strNIIN_clean = product.getScNiin().replaceAll("-", "").trim();
2687 String strFSCG_clean = product.getScFscg().trim();
2688
2689 if (strNIIN_clean.length() >= 9) {
2690 NSN = strFSCG_clean + "-" + strNIIN_clean.substring(0, 2) + "-"
2691 + strNIIN_clean.substring(2, 5) + "-" + strNIIN_clean.substring(5, 9);
2692 }
2693 }
2694 orderLine.setScNationalStockNumber(NSN);
2695
2696 // TicketNumber
2697 orderLine.setScCustomerRefNum(TicketNumber);
2698
2699 // Pricelist
2700 orderLine.setListPrice(sellPrice);
2701
2702 // pricelimit
2703 orderLine.setPriceLimit(vendorPrice);
2704
2705 // pricestd
2706 orderLine.setStandardPrice(sellPrice);
2707
2708 // InvPull
2709
2710 boolean booleanInvPull = false;
2711 if (InvPull != null && InvPull.equalsIgnoreCase("yes")) {
2712 booleanInvPull = true;
2713 } else if (order.getOrganization().getName().contains("OEM")) {
2714 // For OEMA, if record exists in m_product_org for org, set inv pull to Y
2715 OBCriteria<ProductOrg> prodOrgCriteria = OBDal.getInstance().createCriteria(ProductOrg.class);
2716 prodOrgCriteria
2717 .add(Restrictions.eq(ProductOrg.PROPERTY_ORGANIZATION, order.getOrganization()))
2718 .add(Restrictions.eq(ProductOrg.PROPERTY_PRODUCT, product));
2719 final List<ProductOrg> prodOrgList = prodOrgCriteria.list();
2720 if (prodOrgList.size() > 0) {
2721 booleanInvPull = true;
2722 } else if (ri != null) {
2723 // If line had a supporting proposal that was based upon Stock
2724 // (sc_selected_bids.bid_type = 'BID_STOCK'), then set "Y".
2725 OBCriteria<SelectedBids> sbidsCriteria = OBDal.getInstance()
2726 .createCriteria(SelectedBids.class);
2727 sbidsCriteria.add(Restrictions.eq(SelectedBids.PROPERTY_REQUESTITEM, ri))
2728 .add(Restrictions.eq(SelectedBids.PROPERTY_BIDTYPE, "BID_STOCK"));
2729 final List<SelectedBids> sbidsList = sbidsCriteria.list();
2730 if (sbidsList.size() > 0) {
2731 booleanInvPull = true;
2732 }
2733 }
2734 }
2735 orderLine.setScInventoryPull(booleanInvPull);
2736
2737 // Comments
2738 orderLine.setSCComments(Comments);
2739
2740 // UOM
2741 UOM uom = null;
2742
2743 UOM defaultUOM = product != null ? product.getUOM() : null;
2744
2745 if (UnitOfMeasure == null) {
2746 throw new Exception(
2747 "Unit of Measure was not provided for customer order #: " + order.getScPppoNumber());
2748 } else {
2749 uom = SalesOrderDao.getUOM(UnitOfMeasure, cName);
2750 }
2751
2752 if (uom == null) {
2753 throw new Exception("Invalid Unit of Measure provided ('" + UnitOfMeasure + "') for order #: "
2754 + order.getScPppoNumber());
2755 }
2756
2757 if (defaultUOM != null && !uom.equals(defaultUOM)) {
2758 throw new Exception("Unit of Measure mismatch ('" + UnitOfMeasure + "' instead of '"
2759 + defaultUOM.getSymbol() + "') for order #: " + order.getScPppoNumber());
2760 }
2761
2762 orderLine.setUOM(uom);
2763 log.debug("Setting UOM of " + uom + " for product " + product + ":"
2764 + (product != null ? product.getSKU() : ""));
2765
2766 // Ordered Qty
2767 orderLine.setOrderedQuantity(quantity);
2768 log.debug("qtyOrdered: " + quantity);
2769
2770 // Line Amount
2771 BigDecimal calculatedAmt = quantity.multiply(vendorPrice);
2772 orderLine.setLineNetAmount(calculatedAmt);
2773
2774 // Currency
2775 orderLine.setCurrency(order.getCurrency());
2776
2777 // Actual Price
2778 orderLine.setUnitPrice(invPrice);
2779
2780 // Organization
2781 orderLine.setOrganization(order.getOrganization());
2782
2783 // Warehouse
2784 orderLine.setWarehouse(order.getWarehouse());
2785
2786 // Qty's
2787 orderLine.setReservedQuantity(new BigDecimal(0));
2788 orderLine.setDeliveredQuantity(new BigDecimal(0));
2789 orderLine.setInvoicedQuantity(new BigDecimal(0));
2790
2791 // Prices
2792 orderLine.setFreightAmount(new BigDecimal(0));
2793
2794 if (so.getRequisitionNumber() != null && so.getRequisitionNumber().length() >= 6) {
2795 // Ordering Dodaac on the Sales Order Line window
2796 String dodaac = so.getRequisitionNumber().substring(0, 6);
2797 if (dodaac.startsWith("NUK")) {
2798 dodaac = "N68733";
2799 }
2800 orderLine.setScOrderingDodaac(dodaac);
2801 } else {
2802 logger.log(
2803 "Error setting Ordering Dodaac. Requesition number is null or has less than 6 chars!");
2804 }
2805 // Gross Weight and Gross Cube on the Sales Order Line window
2806 setGrossWeightAndGrossCube(quantity, orderLine);
2807 // Tax
2808 OBCriteria<TaxRate> obcTaxRate = OBDal.getInstance().createCriteria(TaxRate.class);
2809
2810 obcTaxRate.add(Restrictions.eq("name", "NO TAX"));
2811
2812 List<TaxRate> taxRateList = obcTaxRate.list();
2813 if (taxRateList.size() == 0) {
2814 obcTaxRate = OBDal.getInstance().createCriteria(TaxRate.class);
2815
2816 obcTaxRate.add(Restrictions.eq("name", "Default"));
2817
2818 taxRateList = obcTaxRate.list();
2819
2820 }
2821 final TaxRate tax_Rate = taxRateList.get(0);
2822 orderLine.setTax(tax_Rate);
2823
2824 // Set Active
2825 orderLine.setActive(true);
2826
2827 // Set Crossdock Permission
2828 orderLine.setScCrossdock(CrossdockCheck.check(orderLine).getValue());
2829
2830 // Set the Status on the line here to NW
2831 orderLine.setScStatus(StatusHelper.LINE_NEW);
2832
2833 // GP 06/11/2013 - populating NSN, description, MFR part number and MFR name for CEMAS orders
2834 if (FrontEndHelper.getFrontEnd(order).equalsIgnoreCase("CEMAS")) {
2835 orderLine.setScNationalStockNumber(product.getScFscg() + product.getScNiin());
2836 orderLine.setScCagePartNum(product.getScMfrPartNumber());
2837 orderLine.setDescription(product.getDescription());
2838 orderLine.setScMfrName(product.getScMfrName());
2839 }
2840 // delivery location
2841 // Check LineAddresses loop in xml line
2842 // Ship To addresses are stored here from EDI (qualifiers: ST/31/AE - search in this order)
2843 // For OEMA & TSI & POLCHEM, ship to locations are stored at line level
2844
2845 // Mark For address - pull from EDI with Z7 qualifier
2846 if (line.getLineAddresses() != null) {
2847
2848 HashMap<String, LineAddress> lineAddressesMap = new HashMap<String, LineAddress>();
2849 LineAddress foundLineAddress = null;
2850 StringBuffer deliveryInfo = new StringBuffer();
2851 for (LineAddress lineAddress : line.getLineAddresses().getLineAddress()) {
2852 lineAddressesMap.put(lineAddress.getAddressQualifier(), lineAddress);
2853 deliveryInfo.append(lineAddress.getAddressQualifier()).append(": ")
2854 .append(lineAddress.getAddress1()).append(", ")
2855 .append(lineAddress.getAddress2() != null && lineAddress.getAddress2().length > 0
2856 ? lineAddress.getAddress2(0) : "")
2857 .append(lineAddress.getCity()).append(", ").append(lineAddress.getState()).append(", ")
2858 .append(lineAddress.getPostal()).append("\n");
2859 }
2860
2861 Location shipToAddressLine = null;
2862 List<String> keyArray = new ArrayList<String>();
2863
2864 // IF not TSI/Polchem
2865 if (order.getOrganization() != null && !order.getOrganization().getName().contains("TSI")
2866 && !order.getOrganization().getName().startsWith("POLCHEM")) {
2867 keyArray = Arrays.asList("ST", "31", "AE");
2868 }
2869 // IF TSI/Polchem
2870 if (order.getOrganization().getName().contains("TSI")
2871 || order.getOrganization().getName().startsWith("POLCHEM")) {
2872
2873 // Loops through REF Qualifiers
2874 Boolean useAE = false;
2875 if (line.getLineRefs() != null) {
2876 for (LineRef lRef : line.getLineRefs().getLineRef()) {
2877 logger.logln("Start looping through REF segments");
2878 if (lRef.getSegment() != null && lRef.getQualifier() != null && lRef.getValue() != null
2879 && "REF".equals(lRef.getSegment())) {
2880
2881 // Log Qualifiers and check T4 for "J" or "K" or "L" or "M"
2882 logger.logln("Qualifier" + lRef.getQualifier() + ": " + lRef.getValue());
2883 if ("T4".equals(lRef.getQualifier())
2884 && ("J".equals(lRef.getValue()) || "K".equals(lRef.getValue())
2885 || "L".equals(lRef.getValue()) || "M".equals(lRef.getValue()))) {
2886 logger.logln("T4 Qualifier is J or K or L or M - use AE");
2887 useAE = true;
2888 }
2889 }
2890 }
2891 }
2892
2893 // If T4 Qualifier is "J" or "K" or "L" or "M", use "AE" Qualifier for ship-to, else use
2894 // "Z7"-> "AE -> "ST"
2895 keyArray = (useAE) ? Arrays.asList("AE", "Z7", "ST") : Arrays.asList("Z7", "AE", "ST");
2896 }
2897
2898 // Loops through keyArray to check for keys in lineAddressMap
2899 if (!keyArray.isEmpty()) {
2900 for (String key : keyArray) {
2901 if (foundLineAddress == null && lineAddressesMap.containsKey(key)
2902 && lineAddressesMap.get(key).getN4Exists() != null
2903 && lineAddressesMap.get(key).getN4Exists().equalsIgnoreCase("Y")) {
2904 if (OrderUtil.isValidDpmsAddress(order, lineAddressesMap.get(key))) {
2905 foundLineAddress = lineAddressesMap.get(key);
2906 break;
2907 } else {
2908 foundLineAddress = null;
2909 }
2910 }
2911 }
2912 }
2913
2914 String shipToDodaac = null;
2915 // If TSI or POLCHEM and foundLineAddress still doesn't exist, set DPMS flag
2916 if (foundLineAddress == null && (order.getOrganization().getName().startsWith("TSI")
2917 || order.getOrganization().getName().startsWith("POLCHEM"))) {
2918 orderLine.setScDpmsRequired(true);
2919 }
2920
2921 if (foundLineAddress != null) {
2922 String shippingAddressCity = foundLineAddress.getCity();
2923 String shippingAddressRegion = foundLineAddress.getState();
2924 String shippingAddressPostalCode = foundLineAddress.getPostal();
2925 if (foundLineAddress.getPostalAdd() != null && !foundLineAddress.getPostalAdd().isEmpty()) {
2926 shippingAddressPostalCode = shippingAddressPostalCode + "-"
2927 + foundLineAddress.getPostalAdd();
2928 }
2929 String shippingAddressStreet = foundLineAddress.getAddressDescription();
2930 String shippingAddress2 = foundLineAddress.getAddress1();
2931 String shippingAddress3 = foundLineAddress.getAddress2() != null
2932 && foundLineAddress.getAddress2().length > 0 ? foundLineAddress.getAddress2(0) : null;
2933 String shippingAddressCountry = foundLineAddress.getCountry();
2934 String shippingLocationType = "098" + foundLineAddress.getAddressQualifier();
2935 String shippingAddressCode = null;
2936 if ("10".equals(foundLineAddress.getAddressCodeQualifier())) {
2937 // WYOM-8553: if the address code qualifier is 10, then it is a DODAAC and should not
2938 // be used for location synchronization
2939 shipToDodaac = foundLineAddress.getAddressCode();
2940 } else {
2941 shippingAddressCode = foundLineAddress.getAddressCode();
2942 }
2943 String bpLocationID = foundLineAddress.getBPLocationID();
2944
2945 try {
2946 shipToAddressLine = locationSynchronization(shippingAddressCode, businessPartner,
2947 shippingAddressStreet, shippingAddressCity, shippingAddressRegion,
2948 shippingAddressPostalCode, shippingAddressCountry, shippingAddress2, shippingAddress3,
2949 shippingLocationType, source, bpLocationID);
2950 if (shipToAddressLine != null && shipToAddressLine.getLocationAddress() != null
2951 && shipToAddressLine.getLocationAddress().getScLocationCode() == null) {
2952 shipToAddressLine.getLocationAddress()
2953 .setScLocationCode(foundLineAddress.getAddressCode());
2954 OBDal.getInstance().save(shipToAddressLine.getLocationAddress());
2955 }
2956 } catch (Exception e) {
2957 log.error("Error setting Ship To address for line " + orderLine.getLineNo() + ": "
2958 + e.getMessage());
2959 logger.logln("Error setting Ship To address for line " + orderLine.getLineNo());
2960 }
2961 OBDal.getInstance().flush();
2962 }
2963
2964 orderLine.setScIsconus(false);
2965
2966 if (shipToAddressLine != null) {
2967 orderLine.setPartnerAddress(shipToAddressLine);
2968 orderLine.setScMarkForLocation(shipToAddressLine);
2969
2970 // Is CONUS (US Country Code and not Hawaii or Alaska)
2971 if (shipToAddressLine.getLocationAddress().getCountry() != null
2972 && shipToAddressLine.getLocationAddress().getCountry().getId().equals("100")
2973 && shipToAddressLine.getLocationAddress().getRegionName() != null
2974 && !shipToAddressLine.getLocationAddress().getRegionName().equals("HI")
2975 && !shipToAddressLine.getLocationAddress().getRegionName().equals("AK")) {
2976 orderLine.setScIsconus(true);
2977 }
2978
2979 // If Requisition Number Starts with NUK: DODAAC = N68733 which Is CONUS
2980 if (so.getRequisitionNumber() != null && so.getRequisitionNumber().startsWith("NUK")) {
2981 orderLine.setScIsconus(true);
2982 }
2983
2984 if (order.getOrganization().getName().startsWith("POLCHEM")) {
2985 if (!Boolean.TRUE.equals(orderLine.isScIsconus())) {
2986 orderLine.setScDpmsRequired(true);
2987 }
2988 if (shipToAddressLine.getLocationAddress().getCountry() != null
2989 && shipToAddressLine.getLocationAddress().getCountry().getId().equals("100")) {
2990 if (shipToAddressLine.getLocationAddress().getRegionName() != null
2991 && (shipToAddressLine.getLocationAddress().getRegionName().equals("HI")
2992 || shipToAddressLine.getLocationAddress().getRegionName().equals("AK"))) {
2993 orderLine.setScDpmsRequired(true);
2994 }
2995 if (shipToAddressLine.getLocationAddress().getCityName() != null && (shipToAddressLine
2996 .getLocationAddress().getCityName().equalsIgnoreCase("APO")
2997 || shipToAddressLine.getLocationAddress().getCityName().equalsIgnoreCase("FPO"))) {
2998 orderLine.setScDpmsRequired(true);
2999 }
3000 }
3001
3002 if (so.getRequisitionNumber() != null && (so.getRequisitionNumber().startsWith("B")
3003 || so.getRequisitionNumber().startsWith("D")
3004 || so.getRequisitionNumber().startsWith("P")
3005 || so.getRequisitionNumber().startsWith("T")
3006 || so.getRequisitionNumber().startsWith("K"))) {
3007 orderLine.setScDpmsRequired(true);
3008 }
3009
3010 }
3011
3012 } else {
3013 if (order.getOrganization().getName().contains("OEM")) {
3014 orderLine.setPartnerAddress(null);
3015 }
3016 if (order.getOrganization().getName().startsWith("POLCHEM")) {
3017 orderLine.setScDpmsRequired(true);
3018 }
3019 }
3020
3021 orderLine.setScShipToDodaac(shipToDodaac);
3022
3023 if (deliveryInfo.length() > 0) {
3024 orderLine.setScDeliveryInfo(deliveryInfo.toString());
3025 }
3026
3027 // Conditions to trigger DPMS & clear ship-to
3028 if (so.getRequisitionNumber() != null) {
3029 // Check DoDAACs that require DPMS
3030 if (so.getRequisitionNumber().length() >= 6) {
3031 String dodaac = so.getRequisitionNumber().substring(0, 6);
3032 if (dodaac.startsWith("NUK")) {
3033 dodaac = "N68733";
3034 }
3035 OBCriteria<CustomerDodaac> dodaacCriteria = OBDal.getInstance()
3036 .createCriteria(CustomerDodaac.class);
3037 dodaacCriteria.add(Restrictions.eq(CustomerDodaac.PROPERTY_DODAAC, dodaac));
3038 dodaacCriteria.add(
3039 Restrictions.eq(CustomerDodaac.PROPERTY_ORGANIZATION, orderLine.getOrganization()));
3040 List<CustomerDodaac> custDodaacList = dodaacCriteria.list();
3041 if (!custDodaacList.isEmpty()) {
3042 CustomerDodaac custDodaac = custDodaacList.get(0);
3043 if (Boolean.TRUE.equals(custDodaac.isRequireDpms())) {
3044 logger.logln("DoDAAC requires Address Verification");
3045 orderLine.setScDpmsRequired(true);
3046 }
3047 }
3048 }
3049 // Check for EMALL
3050 if ((so.getRequisitionNumber().length() >= 14)
3051 && "E".equals(so.getRequisitionNumber().substring(13, 14))) {
3052 orderLine.setScDpmsRequired(true);
3053 }
3054 }
3055 // Check other DPMS conditions
3056 if (order.getOrganization().getName().contains("TSI")
3057 || order.getOrganization().getName().startsWith("POLCHEM")) {
3058
3059 if (order.getOrganization().getName().startsWith("TSI FMS")
3060 || (Boolean.TRUE.equals(orderLine.isScDpmsRequired()))) {
3061 logger.logln("DPMS trigger - clear shipTo and set Address Verification flag");
3062 orderLine.setPartnerAddress(null);
3063 orderLine.setScDpmsRequired(true);
3064 } else {
3065 orderLine.setScDpmsRequired(false);
3066 }
3067 }
3068 }
3069
3070 // Specific for Tires
3071 if (order.getOrganization() != null && order.getOrganization().getName().contains("TSI")) {
3072 // Inv Pull
3073 orderLine.setScInventoryPull(true);
3074
3075 // Gov't Priority
3076 orderLine.setScGovPriority(CAT_3);
3077 String lineRefValue = "";
3078
3079 if (line.getLineRefs() != null) {
3080 for (LineRef lRef : line.getLineRefs().getLineRef()) {
3081 if ((lRef.getSegment() != null) && (lRef.getQualifier() != null)
3082 && (lRef.getValue() != null) && ("REF").equals(lRef.getSegment())) {
3083
3084 lineRefValue = lRef.getValue().trim();
3085
3086 // PH Qualifier
3087 if (("PH").equals(lRef.getQualifier())) {
3088
3089 if (lineRefValue.matches("(01|02|03)")) {
3090 orderLine.setScGovPriority(CAT_1);
3091 logger.logln("Set Gov Priority to CAT1");
3092 }
3093 }
3094
3095 // P4 Qualifier
3096 if (("P4").equals(lRef.getQualifier()) && lineRefValue.startsWith("9")) {
3097 orderLine.setScGovPriority(CAT_2);
3098 logger.logln("Set Gov Priority to CAT2");
3099 }
3100
3101 // WPS-1609: description for "XY" segment can be both - "REQUIRED DELIVERY" and
3102 // "NONSTANDARD RDD" - for the values we are matching
3103 // XY Qualifier
3104 if (("XY").equals(lRef.getQualifier()) && (lRef.getDescription() != null)
3105 && ((lRef.getDescription().startsWith("REQUIRED DELIVERY"))
3106 || (lRef.getDescription().startsWith("NONSTANDARD RDD")))) {
3107 if (lineRefValue.matches("(444|555|777|(N|E).*)")) {
3108 orderLine.setScGovPriority(CAT_2);
3109 logger.logln("Set Gov Priority to CAT2");
3110 } else {
3111 // if not 444, 555, or 777 then it is a julian date and we need to check if
3112 // it is 8 days from order date
3113 Date relDate = order.getOrderDate() != null ? order.getOrderDate() : currentDate;
3114 Date relDatePlus8 = DateUtils.addDays(relDate, 8);
3115
3116 // first try and see if it is a non-julian date
3117 Date lineRefXYDate = DateParser.parseDateString(lineRefValue);
3118
3119 if (lineRefXYDate == null) {
3120 // conversion failed so see if a Julian date
3121 try {
3122 int dateVal = Integer.parseInt(lineRefValue);
3123 int refLength = lineRefValue.length();
3124
3125 if (refLength == 4)
3126 lineRefXYDate = CustomerReceiptLoader.convertOrdinalToDate(lineRefValue);
3127 else if (refLength == 3 && dateVal < 367)
3128 lineRefXYDate = DateUtil.convertOrdinalToDate(dateVal);
3129 } catch (Exception e) {
3130
3131 }
3132 }
3133
3134 if (lineRefXYDate != null
3135 && (lineRefXYDate.before(relDatePlus8) || relDatePlus8.equals(lineRefXYDate))) {
3136 orderLine.setScGovPriority(CAT_2);
3137 logger.logln("Set Gov Priority to CAT2");
3138 }
3139 }
3140 }
3141
3142 // DS Qualifier to capture DPAS Priority Rating
3143 if (("DS").equals(lRef.getQualifier())) {
3144 if (lineRefValue != null) {
3145 if (lineRefValue.length() > 6) {
3146 orderLine.setScDpasRating(lineRefValue.substring(0, 6));
3147 } else {
3148 orderLine.setScDpasRating(lineRefValue);
3149 }
3150 }
3151 }
3152
3153 // WYOM-11380 - W8 Qualifier to append it to the requisition number
3154 if (("W8").equals(lRef.getQualifier())) {
3155 if (!StringUtils.isEmpty(lineRefValue)) {
3156 order.setScRequisitionNumber(order.getScRequisitionNumber() + lineRefValue);
3157 orderLine.setScRequisitionNumber(RequisitionNumber + lineRefValue);
3158 }
3159 }
3160
3161 }
3162 }
3163 }
3164
3165 }
3166
3167 // Specific for POLCHEM
3168 if (order.getOrganization() != null
3169 && order.getOrganization().getName().startsWith("POLCHEM")) {
3170
3171 // Handling of FSL Orders, orders without requisition number
3172 // If no RequisitionNumber found, generate one
3173 if (StringUtils.isEmpty(order.getScRequisitionNumber())) {
3174
3175 // FSL Type
3176 String fslType = "";
3177 if (orderLine.getScShipToDodaac() != null) {
3178 String dodaac = orderLine.getScShipToDodaac();
3179 OBCriteria<CustomerDodaac> dodaacCriteria = OBDal.getInstance()
3180 .createCriteria(CustomerDodaac.class);
3181 dodaacCriteria.add(Restrictions.eq(CustomerDodaac.PROPERTY_DODAAC, dodaac));
3182 dodaacCriteria.add(
3183 Restrictions.eq(CustomerDodaac.PROPERTY_ORGANIZATION, orderLine.getOrganization()));
3184 List<CustomerDodaac> custDodaacList = dodaacCriteria.list();
3185 if (custDodaacList != null && !custDodaacList.isEmpty()) {
3186 CustomerDodaac customerDodaac = custDodaacList.get(0);
3187 if (!StringUtils.isEmpty(customerDodaac.getFSLType())) {
3188 fslType = customerDodaac.getFSLType();
3189 }
3190 }
3191 }
3192
3193 // Julian Date
3194 Date newDate = new Date(System.currentTimeMillis());
3195 java.util.Calendar cal = java.util.Calendar.getInstance();
3196 cal.setTime(newDate);
3197 String year, day;
3198 year = String.valueOf(cal.get(java.util.Calendar.YEAR)).substring(3);
3199 day = String.valueOf(cal.get(java.util.Calendar.DAY_OF_YEAR));
3200 String julianDate = year + day;
3201
3202 // Sequential Number
3203 String sequentialNumber = OBUtils.getDocumentNo(order.getClient().getId(),
3204 "FSL Order Sequence Number");
3205 int seqNo = Integer.parseInt(sequentialNumber);
3206 if (seqNo > 9999) {
3207 OBCriteria<Sequence> obcSeq = OBDal.getInstance().createCriteria(Sequence.class);
3208 obcSeq.add(Restrictions.eq(Sequence.PROPERTY_NAME, "FSL Order Sequence Number"));
3209 if (obcSeq != null && obcSeq.list().size() > 0) {
3210 Sequence seq = obcSeq.list().get(0);
3211 seq.setNextAssignedNumber(new Long(2));
3212 OBDal.getInstance().save(seq);
3213 OBDal.getInstance().flush();
3214 sequentialNumber = "1";
3215 }
3216 }
3217 sequentialNumber = StringUtils.leftPad(sequentialNumber, 4, "0");
3218
3219 // Generated Requisition Number
3220 String reqNumGenerated = fslType + julianDate + sequentialNumber;
3221 order.setScRequisitionNumber(reqNumGenerated);
3222 orderLine.setScRequisitionNumber(reqNumGenerated);
3223 }
3224
3225 // Inv Pull
3226 orderLine.setScInventoryPull(true);
3227
3228 // Gov't Priority
3229 orderLine.setScGovPriority(CAT_3);
3230 String lineRefValue = "";
3231
3232 if (line.getLineRefs() != null) {
3233 for (LineRef lRef : line.getLineRefs().getLineRef()) {
3234 if ((lRef.getSegment() != null) && (lRef.getQualifier() != null)
3235 && (lRef.getValue() != null) && ("REF").equals(lRef.getSegment())) {
3236
3237 lineRefValue = lRef.getValue();
3238
3239 // PH Qualifier
3240 if (("PH").equals(lRef.getQualifier())) {
3241
3242 if (lineRefValue.matches("(01|02|03)")) {
3243 orderLine.setScGovPriority(CAT_1);
3244 logger.logln("Set Gov Priority to CAT1");
3245 }
3246
3247 if (lineRefValue.matches("(04|05|06|07|08)")) {
3248 orderLine.setScGovPriority(CAT_2);
3249 logger.logln("Set Gov Priority to CAT2");
3250 }
3251
3252 }
3253
3254 }
3255 }
3256 }
3257
3258 }
3259
3260 // Save the OrderLine Object
3261 OBDal.getInstance().save(orderLine);
3262
3263 orderLine.setScPid(getPurchItemDesc(orderLine, line));
3264
3265 // WYOM-7685: if the product is managed by a 3PL, do not create a reservation
3266 // (as the 3PL manages what stock to pick and when based off instruction in the
3267 // IPIC)
3268
3269 // ReserveStock
3270 if (order.isScInventoryPull()
3271 && !Boolean.TRUE.equals(orderLine.getProduct().isScIs3plWarehoused())) {
3272 orderLine.setCreateReservation(StorefrontUtils.CREATE_RESERVATION_AUTO);
3273 orderLine.setWarehouseRule(StockUtils.getWareHouseRule(StockUtils.OWNERSHIP_WRULE));
3274 ReservationUtils.createReserveFromSalesOrderLine(orderLine, true);
3275 }
3276
3277 // Wyom-1615 If SF's pull order has a line that is > or = $2400, send the buyer an alert - IS
3278 if (order.isScInventoryPull() && (quantity != null && sellPrice != null)
3279 && (quantity.intValue() * sellPrice.intValue()) >= 2400) {
3280 AlertUtil.createBuyerAlert(order, "Inventory pull sales order exceeds $2400", "2025");
3281 }
3282
3283 // fob
3284 if (fobpt != null && !fobpt.isEmpty()) {
3285 if (fobpt.equalsIgnoreCase("OR")) {
3286 orderLine.setScFobpt("SP");
3287 } else if (fobpt.equalsIgnoreCase("DE")) {
3288 orderLine.setScFobpt("DT");
3289 } else if (fobpt.equalsIgnoreCase("SP") || fobpt.equalsIgnoreCase("DT")) {
3290 orderLine.setScFobpt(fobpt);
3291 }
3292 }
3293
3294 // insp pt
3295 if (inspPt != null && !inspPt.isEmpty()) {
3296 if (inspPt.equalsIgnoreCase("SP")) {
3297 orderLine.setScInstpt("OR");
3298 } else if (inspPt.equalsIgnoreCase("DE")) {
3299 orderLine.setScInstpt("DT");
3300 } else if (inspPt.equalsIgnoreCase("OR") || inspPt.equalsIgnoreCase("DT")) {
3301 orderLine.setScInstpt(inspPt);
3302 }
3303 }
3304
3305 // additional packaging instructions
3306 orderLine.setScAddnlPkgInstruct(additionalPkgInstructions);
3307
3308 String mfrCageCode = line.getMfrCage();
3309 String mfrPartNumber = line.getNewManufacturerPartnumber();
3310 String supplierCageCode = line.getSupplierCageCode();
3311 orderLine.setScMfrcage(mfrCageCode);
3312 orderLine.setScCagePartNum(mfrPartNumber);
3313 orderLine.setScCageCode(supplierCageCode);
3314
3315 log.debug("Order Line was Created");
3316 return orderLine;
3317
3318 }
3319
3320 // Gross Weight and Gross Cube on the Sales Order Lines window
3321 public void setGrossWeightAndGrossCube(BigDecimal quantity, OrderLine orderLine) {
3322 Product product = orderLine.getProduct();
3323 if (product != null) {
3324 if (product.getWeight() != null) {
3325 orderLine.setScGrossWeight(quantity.multiply(product.getWeight()));
3326 }
3327 if (product.getVolume() != null) {
3328 orderLine.setScGrossCube(quantity.multiply(product.getVolume()));
3329 }
3330 }
3331 }
3332
3333 /**
3334 * Finds the baseline ship by and promise dates for the orderLine.
3335 *
3336 * @param order
3337 * the order
3338 * @param orderLine
3339 * the order line
3340 * @param relativeDate
3341 * the relative date
3342 * @return bool
3343 */
3344 public OrderLine findRequiredDeliveryDate(Order order, OrderLine orderLine, Date relativeDate) {
3345 // Required Delivery Date
3346 if (orderLine.getScGovPriority() != null) {
3347
3348 int deliveryDaysToAdd = -1, shipDaysToAdd = -1;
3349
3350 // Gets the record in AD_ORGINFO to find delivery/shipBy days based on CAT
3351 OBCriteria<OrganizationInformation> orgInfoCriteria = OBDal.getInstance()
3352 .createCriteria(OrganizationInformation.class, "orgInfo");
3353 orgInfoCriteria.createAlias("orgInfo.organization", "organization");
3354 orgInfoCriteria.add(Restrictions.eq("organization.id", order.getOrganization().getId()));
3355 List<OrganizationInformation> orgInfoList = orgInfoCriteria.list();
3356
3357 if (!orgInfoList.isEmpty() && orderLine.getScGovPriority() != null) {
3358
3359 if (CAT_1.equals(orderLine.getScGovPriority())
3360 && orgInfoList.get(0).getScCatOneDeliveryDays() != null
3361 && orgInfoList.get(0).getScCatOneDeliveryDays() != null) {
3362 deliveryDaysToAdd = orgInfoList.get(0).getScCatOneDeliveryDays().intValue();
3363 shipDaysToAdd = orgInfoList.get(0).getScCatOneShipByDays().intValue();
3364 }
3365 if (CAT_2.equals(orderLine.getScGovPriority())
3366 && orgInfoList.get(0).getScCatTwoDeliveryDays() != null
3367 && orgInfoList.get(0).getScCatTwoDeliveryDays() != null) {
3368 deliveryDaysToAdd = orgInfoList.get(0).getScCatTwoDeliveryDays().intValue();
3369 shipDaysToAdd = orgInfoList.get(0).getScCatTwoShipByDays().intValue();
3370 }
3371 if (CAT_3.equals(orderLine.getScGovPriority())
3372 && orgInfoList.get(0).getScCatThreeDeliveryDays() != null
3373 && orgInfoList.get(0).getScCatThreeDeliveryDays() != null) {
3374 deliveryDaysToAdd = orgInfoList.get(0).getScCatThreeDeliveryDays().intValue();
3375 shipDaysToAdd = orgInfoList.get(0).getScCatThreeShipByDays().intValue();
3376 }
3377 }
3378
3379 if (logger != null) {
3380 logger.logln("Delivery days to add: " + Integer.toString(deliveryDaysToAdd));
3381 logger.logln("Ship days to add: " + Integer.toString(shipDaysToAdd));
3382 }
3383
3384 // Sets Baseline ShipBy/Promise Date
3385 if (deliveryDaysToAdd > -1) {
3386 Date deliveryToSet = DateUtils.addDays(relativeDate, deliveryDaysToAdd);
3387
3388 // Finds the date after the holiday or weekend (if holiday/weekend)
3389 deliveryToSet = notHolidayOrWeekend(deliveryToSet, order.getOrganization());
3390 orderLine.setScBaselinePromiseDate(deliveryToSet);
3391 }
3392
3393 if (shipDaysToAdd > -1) {
3394 Date shipByToSet = DateUtils.addDays(relativeDate, shipDaysToAdd);
3395
3396 // Finds the date after the holiday or weekend (if holiday/weekend)
3397 shipByToSet = notHolidayOrWeekend(shipByToSet, order.getOrganization());
3398 orderLine.setScBaselineShipByDate(shipByToSet);
3399 }
3400 }
3401
3402 OBDal.getInstance().save(orderLine);
3403 return orderLine;
3404 }
3405
3406 /**
3407 * Checks if a date is a weekend
3408 *
3409 * @param date
3410 * @return bool
3411 */
3412 private Boolean isWeekend(Date date) {
3413 Boolean bool = false;
3414
3415 java.util.Calendar cal = java.util.Calendar.getInstance();
3416 cal.setTime(date);
3417 if (cal.get(java.util.Calendar.DAY_OF_WEEK) == java.util.Calendar.SATURDAY
3418 || cal.get(java.util.Calendar.DAY_OF_WEEK) == java.util.Calendar.SUNDAY) {
3419 bool = true;
3420 }
3421
3422 return bool;
3423 }
3424
3425 /**
3426 * Checks if a date is a holiday
3427 *
3428 * @param cal
3429 * @param date
3430 * @return !holidayCriteria.list().isEmpty()
3431 */
3432 private Boolean isHoliday(Calendar cal, Date date) {
3433
3434 // Initializes criteria to check if holiday in found calendar
3435 OBCriteria<NonBusinessDay> holidayCriteria = OBDal.getInstance()
3436 .createCriteria(NonBusinessDay.class);
3437 holidayCriteria.add(Restrictions.eq(NonBusinessDay.PROPERTY_CALENDAR, cal));
3438 holidayCriteria.add(Restrictions.eq(NonBusinessDay.PROPERTY_NONBUSINESSDAYDATE, date));
3439
3440 return !holidayCriteria.list().isEmpty();
3441 }
3442
3443 /**
3444 * Returns a date after the holiday or weekend
3445 *
3446 * @param date
3447 * @return dateToReturn
3448 */
3449 public Date notHolidayOrWeekend(Date date, Organization org) {
3450
3451 Date dateToReturn = date;
3452
3453 // Get parent org until matches with c_calendar
3454 int safeguardCounter = 0;
3455 Organization findParent = org;
3456 Calendar cCalendar = null;
3457
3458 try {
3459
3460 // Loops through until finds a calendar for a parent org
3461 while (findParent != null && cCalendar == null && safeguardCounter < 1000) {
3462
3463 OBCriteria<Calendar> calCriteria = OBDal.getInstance().createCriteria(Calendar.class);
3464 calCriteria.add(Restrictions.eq(Calendar.PROPERTY_ORGANIZATION, findParent));
3465 List<Calendar> calList = calCriteria.list();
3466
3467 // If found, exit while loop
3468 if (!calList.isEmpty()) {
3469 cCalendar = calList.get(0);
3470 }
3471
3472 findParent = OrgUtil.getParentOrg(findParent);
3473 safeguardCounter++;
3474 }
3475
3476 // Reset counter for second while loop
3477 safeguardCounter = 0;
3478
3479 // Loops until dateToReturn is not a weekend/holiday
3480 while ((isWeekend(dateToReturn) || isHoliday(cCalendar, dateToReturn)) && cCalendar != null
3481 && safeguardCounter < 1000) {
3482
3483 // Adds a day to dateToReturn if holiday or weekend
3484 dateToReturn = DateUtils.addDays(dateToReturn, 1);
3485 safeguardCounter++;
3486 }
3487
3488 } catch (Exception e) {
3489 if (logger != null)
3490 logger.logln("Error checking if date is a holiday or weekend: " + e.getMessage());
3491 throw new OBException("Error checking if date is a holiday or weekend", e);
3492
3493 }
3494 return dateToReturn;
3495 }
3496
3497 /**
3498 * Create Ref Date for the Orderline (PH segment)
3499 *
3500 * @param oline
3501 * @param line
3502 */
3503 private void createRefDataPHOrderline(OrderLine oline, CustomerSOLineItem line) {
3504 if (line.getLineRefs() != null) {
3505 for (LineRef lRef : line.getLineRefs().getLineRef()) {
3506 if ((lRef.getSegment() != null) && (lRef.getQualifier() != null)
3507 && (lRef.getValue() != null) && ("REF").equals(lRef.getSegment())) {
3508
3509 String lineRefValue = lRef.getValue();
3510
3511 // PH Qualifier
3512 if (("PH").equals(lRef.getQualifier())) {
3513
3514 try {
3515 RefDataValues refDataValue = RefDataValues.A_UNDEF_REF_DATA_SEE_REMARKS;
3516 if (refDataValue != null)
3517 RefDataUtil.createRefData(RefDataObjectType.C_ORDERLINE, oline,
3518 RefDataNames.TRANS_PRIORITY, RefDataSource.SYSTEM_LOAD_PROCESS, refDataValue,
3519 false, lineRefValue);
3520 } catch (Exception e) {
3521 logger.logln("Error trying to add ref data for the PH qualifier.");
3522 }
3523 }
3524 }
3525 }
3526 }
3527 }
3528
3529 /**
3530 * Gets the UOM of a product
3531 *
3532 * @param order
3533 * ID
3534 * @return docStatus
3535 * @throws ServletException
3536 * @throws SQLException
3537 * @throws NoConnectionAvailableException
3538 */
3539 private Location getLocation(BusinessPartner businessPartner, String lineCountry, String lineCity,
3540 String linestate, String lineaddress1, String linePostalCode)
3541 throws ServletException, SQLException, NoConnectionAvailableException {
3542 if ((lineCountry == null || StringUtils.isEmpty(lineCountry))
3543 && StringUtils.isNotEmpty(linestate)) {
3544 // Get Country from Region
3545 // Get Region
3546 OBCriteria<Region> regCrit = OBDal.getInstance().createCriteria(Region.class);
3547 regCrit.add(Restrictions.eq(Region.PROPERTY_NAME, linestate));
3548 List<Region> regList = regCrit.list();
3549 if (regList.size() > 0) {
3550 Country country = regList.get(0).getCountry();
3551 if (country != null) {
3552 lineCountry = country.getISOCountryCode();
3553 }
3554 }
3555 }
3556 StringBuilder whereClause = new StringBuilder(
3557 "as bloc inner join bloc.locationAddress as location where location.addressLine1 = :address1 and bloc.shipToAddress=true and location.cityName = :city");
3558 if (linePostalCode != null) {
3559 whereClause.append(" and location.postalCode = :postal");
3560 }
3561 if (linestate != null) {
3562 whereClause.append(" and location.region.name = :state");
3563 }
3564 if (lineCountry != null) {
3565 whereClause.append(" and location.country.iSOCountryCode = :country");
3566 }
3567 OBQuery<Location> query = OBDal.getInstance().createQuery(Location.class,
3568 whereClause.toString());
3569 query.setNamedParameter("address1", lineaddress1);
3570 query.setNamedParameter("city", lineCity);
3571 if (linePostalCode != null) {
3572 query.setNamedParameter("postal", linePostalCode);
3573 }
3574 if (linestate != null) {
3575 query.setNamedParameter("state", linestate);
3576 }
3577 if (lineCountry != null) {
3578 query.setNamedParameter("country", lineCountry);
3579 }
3580 List<Location> locations = query.list();
3581 if (locations.size() > 0) {
3582 for (Location loc : locations) {
3583 if (businessPartner.equals(loc.getBusinessPartner())) {
3584 return loc;
3585 }
3586 }
3587 return null;
3588 } else {
3589 return null;
3590 }
3591 }
3592
3593 /**
3594 * When provided a location code, this method will see if that location exists in the database. If
3595 * not and if the JMS Message contained the other required address fields (city, state, zip,
3596 * etc.), then this method will create the location. If the location doesn't exist and not enough
3597 * details to create a new address, then this method will return an SalesOrderLoadException which
3598 * should be bubbled up to the user.
3599 *
3600 * @param JMSLocationName
3601 * @param businessPartner
3602 * @param shippingAddressStreet
3603 * @param shippingAddressCity
3604 * @param shippingAddressRegion
3605 * @param shippingAddressPostalCode
3606 * @param shippingAddressCountry
3607 * @param source
3608 * @return
3609 * @throws IOException
3610 * @throws HibernateException
3611 * @throws ServletException
3612 * @throws SQLException
3613 * @throws NoConnectionAvailableException
3614 */
3615 private Location locationSynchronization(String JMSLocationName, BusinessPartner businessPartner,
3616 String shippingAddressStreet, String shippingAddressCity, String shippingAddressRegion,
3617 String shippingAddressPostalCode, String shippingAddressCountry, String shippingAddress2,
3618 String shippingAddress3, String shippingLocationType, SystemType source, String bpLocationId)
3619 throws IOException, HibernateException, ServletException, SQLException,
3620 NoConnectionAvailableException, SalesOrderLoadException {
3621
3622 // check in the business partner location table first, that's the best match
3623
3624 if (StringUtils.isNotEmpty(bpLocationId)) {
3625 Location loc = OBDal.getInstance().get(Location.class, bpLocationId);
3626 if (loc != null)
3627 return loc;
3628 }
3629
3630 OBCriteria<Location> locationCriteria = OBDal.getInstance().createCriteria(Location.class);
3631 locationCriteria.add(Restrictions.eq(Location.PROPERTY_NAME, JMSLocationName));
3632 locationCriteria.add(Restrictions.eq(Location.PROPERTY_BUSINESSPARTNER, businessPartner));
3633 List<Location> businessPartnerList = locationCriteria.list();
3634 if (businessPartnerList.size() > 0) {
3635 log.debug("Location " + JMSLocationName + " exists in OB");
3636 return businessPartnerList.get(0);
3637 } else {
3638 OBCriteria<org.openbravo.model.common.geography.Location> geoLocationCriteria = OBDal
3639 .getInstance().createCriteria(org.openbravo.model.common.geography.Location.class);
3640
3641 // Get the location out of Openbravo
3642 geoLocationCriteria.add(Restrictions.eq(
3643 org.openbravo.model.common.geography.Location.PROPERTY_SCLOCATIONCODE, JMSLocationName));
3644 List<org.openbravo.model.common.geography.Location> geoLocation = geoLocationCriteria.list();
3645 if (geoLocation.size() > 0) {
3646 List<Location> businessPartnerLocationList = geoLocation.get(0)
3647 .getBusinessPartnerLocationList();
3648
3649 // If there exists a bp location for this business partner, use it
3650 if (businessPartnerLocationList != null && businessPartnerLocationList.size() > 0) {
3651 for (Location loc : businessPartnerLocationList) {
3652 if (loc.getBusinessPartner().equals(businessPartner))
3653 return loc;
3654 }
3655 }
3656
3657 // If the business partner is not associated to any bp locations, create
3658 return createBPartnerLocation(businessPartner, geoLocation.get(0), false, false);
3659
3660 } else {
3661 log.debug("Location " + JMSLocationName + " does not exist in OB");
3662
3663 // Check for location address based on address or create Location Address if not found
3664 if (shippingAddressStreet != null && !shippingAddressStreet.equals("")
3665 && shippingAddressCity != null && !shippingAddressCity.equals("")) {
3666
3667 // Try to get location based on address first before creating a new location - LK
3668 Location foundLocation = getLocation(businessPartner, shippingAddressCountry,
3669 shippingAddressCity, shippingAddressRegion, shippingAddressStreet,
3670 shippingAddressPostalCode);
3671
3672 if (foundLocation == null) {
3673 // could not find location in database now create it
3674 org.openbravo.model.common.geography.Location billTolocationAddress = createLocation(
3675 JMSLocationName, shippingAddressCountry, shippingAddressCity, shippingAddressRegion,
3676 shippingAddressStreet, shippingAddressPostalCode, shippingAddress2,
3677 shippingAddress3, shippingLocationType, source);
3678
3679 if (billTolocationAddress == null) {
3680 return null;
3681 } else {
3682 // Create new BP Location
3683 return createBPartnerLocation(businessPartner, billTolocationAddress, false, true);
3684 }
3685 } else
3686 return foundLocation; // found location
3687 } else {
3688 throw new SalesOrderLoadException("No location provided");
3689 }
3690 }
3691 }
3692 }
3693
3694 /**
3695 * Creates a BP Location
3696 *
3697 * @param businessPartner1
3698 * @param locationAddress
3699 * @throws HibernateException
3700 * @throws ServletException
3701 */
3702 private Location createBPartnerLocation(
3703 org.openbravo.model.common.businesspartner.BusinessPartner businessPartner1,
3704 org.openbravo.model.common.geography.Location locationAddress, boolean is_default_billing,
3705 boolean is_default_shipping) throws HibernateException, ServletException {
3706 // New Business Partner Location Address
3707 org.openbravo.model.common.businesspartner.Location businessPartnerLocation = OBProvider
3708 .getInstance().get(org.openbravo.model.common.businesspartner.Location.class);
3709 businessPartnerLocation.setLocationAddress(locationAddress);
3710 businessPartnerLocation.setBusinessPartner(businessPartner1);
3711 businessPartnerLocation.setActive(true);
3712
3713 log.debug("locationAddress: " + locationAddress);
3714 log.debug("businessPartner: " + businessPartner1.getId());
3715
3716 if (is_default_billing) {
3717
3718 businessPartnerLocation.setInvoiceToAddress(true);
3719 } else {
3720
3721 businessPartnerLocation.setInvoiceToAddress(false);
3722 }
3723
3724 if (is_default_shipping) {
3725 businessPartnerLocation.setShipToAddress(true);
3726 } else {
3727 businessPartnerLocation.setShipToAddress(false);
3728 }
3729
3730 locationAddress.getBusinessPartnerLocationList().add(businessPartnerLocation);
3731
3732 // Save the newly created BusinessPartnerLocation
3733 OBDal.getInstance().save(businessPartnerLocation);
3734
3735 return businessPartnerLocation;
3736 }
3737
3738 /**
3739 * Creates a location address to be set to BP location
3740 *
3741 * @param country_id
3742 * @param cityName
3743 * @param regionName
3744 * @param street
3745 * @param postcode
3746 * @param source
3747 * @return location address created
3748 * @throws HibernateException
3749 * @throws ServletException
3750 */
3751 private org.openbravo.model.common.geography.Location createLocation(String locationCode,
3752 String country_id, String cityName, String regionName, String street, String postcode,
3753 String shippingAddress2, String shippingAddress3, String shippingLocationType,
3754 SystemType source) throws HibernateException, ServletException {
3755
3756 final org.openbravo.model.common.geography.Location locationAddress = OBProvider.getInstance()
3757 .get(org.openbravo.model.common.geography.Location.class);
3758
3759 Organization masterOrg = null;
3760 OBCriteria<Organization> orgCrit = OBDal.getInstance().createCriteria(Organization.class);
3761 orgCrit.add(Restrictions.eq(Organization.PROPERTY_ID, "0"));
3762 List<Organization> orgList = orgCrit.list();
3763 if (orgList.size() > 0) {
3764 masterOrg = orgList.get(0);
3765 }
3766
3767 Country currentCountry = null;
3768 if (StringUtils.isEmpty(country_id)) {
3769 currentCountry = OBUtils.getCountryFromState(regionName);
3770 if (currentCountry == null) {
3771 return null;
3772 }
3773 } else {
3774 // Check if country exists
3775 OBCriteria<Country> obcCountry = OBDal.getInstance().createCriteria(Country.class);
3776 if (country_id.length() > 2)
3777 country_id = country_id.substring(0, 2);
3778 obcCountry.add(Restrictions.eq("iSOCountryCode", country_id));
3779 List<Country> countryList = obcCountry.list();
3780 if (countryList.size() == 0) {
3781 currentCountry = OBProvider.getInstance().get(Country.class);
3782 currentCountry.setName(country_id);
3783 currentCountry.setISOCountryCode(country_id);
3784 currentCountry.setOrganization(masterOrg);
3785
3786 // Save the newly created Country
3787 OBDal.getInstance().save(currentCountry);
3788 } else {
3789 currentCountry = countryList.get(0);
3790 }
3791 }
3792 // Set Country
3793 locationAddress.setCountry(currentCountry);
3794
3795 log.debug("Country: " + currentCountry);
3796
3797 if (regionName != null && !regionName.equals("")) {
3798
3799 // 11/08/12 GP - MAXIMO regions can be 2 char or more
3800 if (SystemType.MAXIMO.equals(source)) {
3801 CustomerRFQLoader rfqLoader = new CustomerRFQLoader();
3802 String region_descr = regionName;
3803 // String region_abbr = "";
3804 if (region_descr.length() > 2)
3805 regionName = rfqLoader.getRegionByDescription(region_descr, _bundle);
3806 else
3807 regionName = region_descr;
3808 } else {
3809 // Check if region exists
3810 if (regionName.length() > 60)
3811 regionName = regionName.substring(0, 60);
3812 }
3813 OBCriteria<Region> obcRegion = OBDal.getInstance().createCriteria(Region.class);
3814 obcRegion.add(Restrictions.eq("name", regionName));
3815 List<Region> regionList = obcRegion.list();
3816 if (regionList.size() == 0) {
3817 // New Region
3818 Region newRegion = OBProvider.getInstance().get(Region.class);
3819 newRegion.setName(regionName);
3820 newRegion.setCountry(currentCountry);
3821 newRegion.setOrganization(masterOrg);
3822
3823 // Save the newly created Region
3824 OBDal.getInstance().save(newRegion);
3825
3826 // Set Region
3827 locationAddress.setRegion(newRegion);
3828 locationAddress.setRegionName(regionName);
3829 } else {
3830 Region region = regionList.get(0);
3831 // Set Region
3832 locationAddress.setRegion(region);
3833 locationAddress.setRegionName(regionName);
3834 }
3835
3836 } else {
3837 // To avoid null pointer exception
3838 locationAddress.setRegionName("");
3839 }
3840 log.debug("Region: " + regionName);
3841
3842 if (cityName != null && !cityName.equals("")) {
3843 if (cityName.length() > 60)
3844 cityName = cityName.substring(0, 60);
3845 // Check if city exists
3846 OBCriteria<City> obcCity = OBDal.getInstance().createCriteria(City.class);
3847 obcCity.add(Restrictions.eq("name", cityName));
3848 List<City> cityList = obcCity.list();
3849 if (cityList.size() == 0) {
3850 // New City
3851 City newCity = OBProvider.getInstance().get(City.class);
3852 newCity.setName(cityName);
3853
3854 // Save the newly created City
3855 OBDal.getInstance().save(newCity);
3856
3857 // Set City
3858 locationAddress.setCity(newCity);
3859 locationAddress.setCityName(cityName);
3860 } else {
3861 City city = cityList.get(0);
3862 // Set City
3863 locationAddress.setCity(city);
3864 locationAddress.setCityName(cityName);
3865 }
3866 }
3867 log.debug("City: " + cityName);
3868
3869 if (street != null && !street.equals("")) {
3870 if (street.length() > 60)
3871 street = street.substring(0, 60);
3872 // Set AddressLine1
3873 locationAddress.setAddressLine1(street);
3874 } else {
3875 // To avoid null pointer exception
3876 locationAddress.setAddressLine1("");
3877 }
3878
3879 // shippingAddress2; this comes from HeaderAddress/LineAddress tag in SO xml
3880 if (shippingAddress2 != null && !shippingAddress2.equals("")) {
3881 // Set AddressLine2
3882 if (shippingAddress2.length() > 60)
3883 locationAddress.setAddressLine2(shippingAddress2.substring(0, 60));
3884 else
3885 locationAddress.setAddressLine2(shippingAddress2);
3886 } else {
3887 // To avoid null pointer exception
3888 locationAddress.setAddressLine2("");
3889 }
3890
3891 // shippingAddress3; this comes from HeaderAddress/LineAddress tag in SO xml
3892 if (shippingAddress3 != null && !shippingAddress3.equals("")) {
3893 // Set em_sc_address3
3894 if (shippingAddress3.length() > 60)
3895 locationAddress.setScAddress3(shippingAddress3.substring(0, 60));
3896 else
3897 locationAddress.setScAddress3(shippingAddress3);
3898 } else {
3899 // To avoid null pointer exception
3900 locationAddress.setScAddress3("");
3901 }
3902
3903 // shippingLocationType; this comes from HeaderAddress/LineAddress tag in SO xml
3904 if (shippingLocationType != null && !shippingLocationType.isEmpty()) {
3905 // Set em_sc_location_type
3906 locationAddress.setScLocationType(shippingLocationType);
3907 }
3908
3909 // locationCode
3910 if (!StringUtils.isEmpty(locationCode) && locationCode.length() <= 10) {
3911 locationAddress.setScLocationCode(locationCode);
3912 }
3913
3914 if (postcode != null && !postcode.equals("")) {
3915 if (postcode.length() > 10)
3916 postcode = postcode.substring(0, 10);
3917 // Set PostalCode
3918 locationAddress.setPostalCode(postcode);
3919 } else {
3920 // To avoid null pointer exception
3921 locationAddress.setPostalCode("");
3922 }
3923
3924 locationAddress.setOrganization(masterOrg);
3925 // Save the newly created Location
3926 OBDal.getInstance().save(locationAddress);
3927
3928 // Commit
3929 // OBDal.getInstance().commitAndClose();
3930
3931 // Return the created location
3932
3933 return locationAddress;
3934 }
3935
3936 /**
3937 * @param JMSCustomerName
3938 * @param customerCode
3939 * @return
3940 * @throws IOException
3941 * @throws HibernateException
3942 * @throws ServletException
3943 *
3944 * @deprecated
3945 */
3946 public BusinessPartner customerSynchronization(String customerCode)
3947 throws IOException, HibernateException, ServletException {
3948 OBQuery<CustomerPartner> query = OBDal.getInstance().createQuery(CustomerPartner.class,
3949 "as cp where cp.businessPartner.searchKey = :vendorCode");
3950 query.setNamedParameter("vendorCode", customerCode);
3951 List<CustomerPartner> partners = query.list();
3952 if (partners.size() > 0)
3953 return partners.get(0).getBusinessPartner();
3954 else
3955 return null;
3956 }
3957
3958 /**
3959 * @param connection
3960 * @param vendorCode
3961 * @return
3962 * @throws Exception
3963 */
3964 private BusinessPartner vendorSynchronization(String vendorCode)
3965 throws IOException, HibernateException, ServletException {
3966 OBQuery<CustomerPartner> query = OBDal.getInstance().createQuery(CustomerPartner.class,
3967 "as cp where cp.businessPartner.searchKey = :vendorCode");
3968 query.setNamedParameter("vendorCode", vendorCode);
3969 List<CustomerPartner> partners = query.list();
3970 if (partners.size() == 0)
3971 return null;
3972 else
3973 return partners.get(0).getBusinessPartner();
3974 }
3975
3976 private boolean payMethodexists(String paymentMethod) throws ServletException {
3977 OBCriteria<FIN_PaymentMethod> crit = OBDal.getInstance()
3978 .createCriteria(FIN_PaymentMethod.class);
3979 crit.add(Restrictions.eq(FIN_PaymentMethod.PROPERTY_NAME, paymentMethod));
3980 List<FIN_PaymentMethod> methods = crit.list();
3981 return methods.size() > 0;
3982 }
3983
3984 /**
3985 * @param objBPartner
3986 * @return
3987 * @throws ServletException
3988 */
3989 private FIN_PaymentMethod getPaymentMethod(BusinessPartner bPartner) throws ServletException {
3990 if (bPartner.isCustomer()) {
3991 return bPartner.getPaymentMethod();
3992 } else if (bPartner.isVendor()) {
3993 return bPartner.getPOPaymentMethod();
3994 } else
3995 throw new OBException("Unable to find proper payment method for " + bPartner);
3996 }
3997
3998 public User getBuyer(String buyerId) {
3999 final OBCriteria<User> buyer = OBDal.getInstance().createCriteria(User.class);
4000 buyer.add(Restrictions.eq(User.PROPERTY_SCPPLCUSERCODE, buyerId));
4001 System.out.println(buyer);
4002
4003 return (User) buyer.uniqueResult();
4004 }
4005
4006 public String getDPASPriorityRatingForHeader(Order so) {
4007 String dpasPriorityRating = null;
4008 RefData dpasRatingRefData = RefDataUtil.getRefData(RefDataObjectType.C_ORDER, so,
4009 RefDataNames.DPAS_PRIORITY_RATING);
4010 if (dpasRatingRefData != null) {
4011 if (dpasRatingRefData.getRemark() != null) {
4012 // Only capture value. The value and description had been concatenated from EDI
4013 // REF^DS^DOA4^DPAS PRIORITY RATING
4014 int index = dpasRatingRefData.getRemark().indexOf(" ");
4015 if (index != -1) {
4016 dpasPriorityRating = dpasRatingRefData.getRemark().substring(0, index);
4017 } else {
4018 dpasPriorityRating = dpasRatingRefData.getRemark();
4019 }
4020 }
4021 }
4022 return dpasPriorityRating;
4023 }
4024
4025 /**
4026 * Get Alliance SAIC Account Resp for OEMA orders
4027 *
4028 * @param salesorder
4029 * @return
4030 */
4031
4032 private User getAllianceResp(Order so) {
4033 String programCode = so.getScProgramCode();
4034 final OBCriteria<Program> progCriteria = OBDal.getInstance().createCriteria(Program.class);
4035 progCriteria.add(Restrictions.eq(Program.PROPERTY_PROGRAMCODE, programCode));
4036 Program program = (Program) progCriteria.uniqueResult();
4037
4038 if (program != null) {
4039 List<OEMAAllianceProgram> allianceProg = program.getSCOEMAALLIANCEPROGRAMList();
4040 if (allianceProg.size() != 0) {
4041 return allianceProg.get(0).getSAICAccountResp();
4042 }
4043 }
4044
4045 return null;
4046 }
4047
4048 @Override
4049 public TransmissionType getTransmissionType(WyomingMessage message) {
4050 return TransmissionType.SALES_ORDER;
4051 }
4052
4053 @Override
4054 protected String getJMSQueueName() {
4055 return ApplicationProperties.getProperty(ApplicationProperty.INBOUND_SO_QUEUE_NAME);
4056 }
4057
4058 @Override
4059 public SAICProcessResult postProcessMessages() throws RuntimeException {
4060 return null;
4061
4062 }
4063
4064 private PurchItemDesc getPurchItemDesc(OrderLine oLine, CustomerSOLineItem line) {
4065 if (oLine.getProduct() == null || StringUtils.isEmpty(line.getPID()))
4066 return null;
4067 PurchItemDesc pid = PIDUtil.findPIDData(oLine.getProduct(), line.getPID(), null,
4068 oLine.getOrganization());
4069 if (pid == null) {
4070 pid = PIDUtil.createPIDData(oLine.getProduct(), line.getPID(), null, oLine.getOrganization());
4071 RefDataUtil.updateRefData(RefDataObjectType.C_ORDERLINE, oLine, RefDataNames.NEW_PID,
4072 RefDataSource.SYSTEM_LOAD_PROCESS, RefDataValues.A_NEW_PID_YES, false, null);
4073 }
4074 return pid;
4075 }
4076
4077}