Example usage for org.apache.ibatis.session SqlSession rollback

List of usage examples for org.apache.ibatis.session SqlSession rollback

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSession rollback.

Prototype

void rollback();

Source Link

Document

Discards pending batch statements and rolls database connection back.

Usage

From source file:net.cbtltd.rest.AbstractProduct.java

protected PriceList getPriceList(String productid, String pos, Boolean test, String version, String xsl,
        SqlSession sqlSession, boolean fromxml) {

    Date timestamp = new Date();
    String message = "/product/" + productid + "/pricelist?pos=" + pos + "&xsl=" + xsl + "&test=" + test;
    LOG.debug(message);//from  ww w  .  j a v  a2s.c o  m
    PriceList result = null;
    Property product;
    try {
        product = (fromxml) ? getPropertyForXMLFeed(sqlSession, pos, productid, test, version)
                : getProperty(sqlSession, pos, productid, test, version);
        result = new PriceList(NameId.Type.Product.name(), productid, null,
                createPricelist(sqlSession, product, null, null, null), xsl);
    } catch (Throwable x) {
        sqlSession.rollback();
        if (x != null && x.getMessage() != null && !x.getMessage().startsWith(Error.data_unchanged.name())) {
            LOG.error(message + "\n" + x.getMessage());
        }
        result = new PriceList(NameId.Type.Product.name(), productid, message + " " + x.getMessage(), null,
                xsl);
    }
    //   finally {sqlSession.close();}
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractProduct.java

/**
 * Creates, updates or deletes a product.
 *
 * @param action the product parameter.//from  www  .  j av  a  2 s . c o m
 * @param pos the point of sale code.
 * @param xsl the style sheet.
 * @return the product.
 */
protected static synchronized Property setProperty(Property action, String pos, String xsl) {
    Date timestamp = new Date();
    String message = "\nPOST product?pos=" + pos + "&xsl=" + xsl + " params " + action.getId() + " "
            + action.toString();
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Property result = new Property();

    try {
        Party party = Constants.getParty(sqlSession, pos);
        String partyid = party.getId(); //Constants.decryptPos(pos); //TODO: only for managers

        Product product = null;
        if (action.hasAltpartyid()) {
            product = sqlSession.getMapper(ProductMapper.class).altread(action);
        } else if (action.hasId()) {
            product = sqlSession.getMapper(ProductMapper.class).read(action.getId());
        }

        if (product == null) { //new product
            product = new Product();
            product.setActorid(partyid);
            product.setAltid(action.getAltid());
            product.setAltpartyid(action.getAltpartyid());
            product.setType(Product.Type.Accommodation.name());
            product.setSupplierid(action.hasSupplierid() ? action.getSupplierid() : partyid);
            product.setUnit(Unit.DAY);
            sqlSession.getMapper(ProductMapper.class).create(product);
            RelationService.replace(sqlSession, Relation.ORGANIZATION_PRODUCT, product.getSupplierid(),
                    product.getId());
        }

        product.setAltitude(action.getAltitude());
        product.setBathroom(action.getBathroom());
        product.setChild(action.getChild());
        product.setCode(action.getCode());
        product.setCommission(action.getCommissionValue());
        product.setCurrency(action.hasCurrency() ? action.getCurrency() : Currency.Code.USD.name());
        product.setDiscount(action.getDiscount());
        product.setInfant(action.getInfant());
        product.setLanguage(action.hasLanguage() ? action.getLanguage() : Language.Code.en.name());

        //         Location location = null;
        //         if (action.hasLocationid()) {location = sqlSession.getMapper(LocationMapper.class).read(action.getLocationid());}
        //         else {location = PartnerService.getLocation(sqlSession, action.getCity(), action.getRegion(), action.getCountry(), action.getLatitude(), action.getLongitude(), action.getAltitude());}
        //         if (location == null) {throw new ServiceException(Error.location_id, product.getLocationid());}
        //
        //         product.setLocationid(location.getId());
        //         product.setLatitude(action.getLatitude());
        //         product.setLongitude(action.getLongitude());
        //         if (product.noLatLng()) {
        //            product.setLatitude(location == null ? null : location.getLatitude());
        //            product.setLongitude(location == null ? null : location.getLongitude());
        //         }      
        //         product.setName(action.hasName() ? action.getName() : location == null ? product.getId() : location.getName() + " " + product.getId());

        product.setLocationid(action.getLocationid());
        product.setLatitude(action.getLatitude());
        product.setLongitude(action.getLongitude());
        product.setName(action.getName());
        product.setOwnerid(action.hasOwnerid() ? action.getOwnerid() : partyid);
        product.setPerson(action.getPerson());
        product.setPhysicaladdress(action.getPhysicaladdress());
        product.setQuantity(action.getQuantity());
        product.setRank(0.0);
        product.setRating(action.getRating());
        product.setRoom(action.getRoom());
        product.setState(action.hasState() ? action.getState() : Product.CREATED);
        product.setToilet(action.getToilet());
        product.setWebaddress(action.getWebaddress());

        sqlSession.getMapper(ProductMapper.class).update(product);

        if (action.getAttributes() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<Attribute> attributes = action.getAttributes().attribute;
            for (Attribute attribute : attributes) {
                Collection<String> values = attribute.values.value;
                if (values != null) {
                    for (String value : values) {
                        kvs.add(value);
                    }
                }
            }
            RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, product.getId(), kvs);
        }

        if (action.getImages() != null && HasUrls.LIVE) {
            ArrayList<NameId> images = new ArrayList<NameId>();
            Collection<String> urls = action.getImages().getImage();
            if (urls != null) {
                for (String url : urls) {
                    images.add(new NameId("", url));
                }
                UploadFileService.uploadImages(sqlSession, NameId.Type.Product, product.getId(), Language.EN,
                        images);
            }

        }

        if (action.getKeyvalues() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<KeyValue> keyvalues = action.getKeyvalues();
            for (KeyValue keyvalue : keyvalues) {
                kvs.add(keyvalue.getKey() + Model.DELIMITER + keyvalue.getValue());
            }
            RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, action.getId(), kvs);
        }

        LOG.debug("\nPricetable " + action.getPricetable());
        if (action.getPricetable() != null) {
            Collection<Price> prices = action.getPricetable().price;
            LOG.debug("\nPrices " + prices);
            for (Price price : prices) {
                if (price.noValue() || price.getValue() <= 0.0) {
                    throw new ServiceException(Error.price_data, "Invalid Value");
                }
                //               if (price.noDuration(0.0, Time.DAY)) {throw new ServiceException(Error.price_data, "Invalid Duration");}
                price.setEntitytype(NameId.Type.Product.name());
                price.setEntityid(product.getId());
                price.setPartyid(product.getSupplierid());
                price.setName(price.noName() ? Price.RACK_RATE : price.getName());
                price.setType(NameId.Type.Reservation.name());
                LOG.debug("\nParameter " + price);

                Price exists = sqlSession.getMapper(PriceMapper.class).exists(price);
                if (exists == null) {
                    sqlSession.getMapper(PriceMapper.class).create(price);
                } else {
                    price.setId(exists.getId());
                }
                LOG.debug("\nExists " + exists);

                price.setUnit(price.getUnit() == null ? Unit.DAY : price.getUnit());
                price.setState(Price.CREATED);
                price.setAvailable(price.getAvailable() == null ? 1 : price.getAvailable());
                price.setQuantity(price.noQuantity() ? 0.0 : price.getQuantity());
                price.setMinimum(price.getMinimum() == null ? 0.0 : price.getMinimum());
                sqlSession.getMapper(PriceMapper.class).update(price);
                LOG.debug("\nPrice " + price);
            }
        }

        if (action.getReviews() != null) {
            Collection<Review> reviews = action.getReviews().review;
            for (Review review : reviews) {
                Event<Rate> event = new Event<Rate>();
                event.setActivity(NameId.Type.Reservation.name());
                event.setActorid(partyid);
                event.setDate(review.getDate());
                event.setName(SessionService.pop(sqlSession, action.getOrganizationid(), Serial.RATE));
                event.setNotes(review.getNotes());
                event.setOrganizationid(product.getOrganizationid());
                event.setProcess(Event.Type.Rate.name());
                event.setState(review.getState() == null ? Event.CREATED : review.getState());
                event.setType(Event.NOMINAL);
                if (event.hasId()) {
                    sqlSession.getMapper(EventMapper.class).update(event);
                } else {
                    event.setName(SessionService.pop(sqlSession, event.getOrganizationid(), Serial.RATE));
                    sqlSession.getMapper(EventMapper.class).create(event);
                }

                if (review.getRatings() != null) {
                    Collection<Rating> ratings = review.getRatings();
                    for (Rating rating : ratings) {
                        Rate rate = new Rate();
                        rate.setCustomerid(partyid);
                        rate.setEventid(event.getId());
                        rate.setName(rating.getName());
                        rate.setQuantity(rating.getCount());
                        rate.setProductid(product.getId());
                        rate.setType(Rate.RATING);
                        sqlSession.getMapper(RateMapper.class).create(rate);
                    }
                }
            }
        }

        if (action.hasDescription()) {
            product.setPublicText(new Text(product.getPublicId(), product.getPublicLabel(), Text.Type.HTML,
                    new Date(), action.getDescription(), product.getLanguage()));
        }
        if (action.hasContents()) {
            product.setContentsText(new Text(product.getContentsId(), product.getContentsLabel(),
                    Text.Type.HTML, new Date(), action.getDescription(), product.getLanguage()));
        }
        if (action.hasOptions()) {
            product.setOptionsText(new Text(product.getOptionsId(), product.getOptionsLabel(), Text.Type.HTML,
                    new Date(), action.getOptions(), product.getLanguage()));
        }
        if (action.hasCheckin()) {
            product.setCheckinText(new Text(product.getCheckinId(), product.getCheckinLabel(), Text.Type.HTML,
                    new Date(), action.getCheckin(), product.getLanguage()));
        }
        if (action.hasConditions()) {
            product.setConditionsText(new Text(product.getConditionsId(), product.getConditionsLabel(),
                    Text.Type.HTML, new Date(), action.getConditions(), product.getLanguage()));
        }
        TextService.update(sqlSession, product.getTexts());

        //         RelationService.replace(sqlSession, Relation.PRODUCT_VALUE, action.getId(), action.getValues());
        RelationService.create(sqlSession, Relation.PRODUCT_ATTRIBUTE, action.getId(),
                action.getAttributemap());
        RelationService.unload(sqlSession, Downloaded.PRODUCT_DOWNLOAD, action.getId(), null);

        sqlSession.commit();
        result.setId(product.getId());
    } catch (Throwable x) {
        sqlSession.rollback();
        result.setMessage(message + " " + x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservation.java

/**
 * Creates, updates or cancels a reservation.
 *
 * @param action the reservation parameter.
 * @param pos the POS code.//w  w w.  j  a v  a2 s .  com
 * @param xsl the style sheet.
 * @return the provisional reservation.
 */
protected static synchronized Reservation setReservation(Reservation action, String pos, String xsl) {
    Date timestamp = new Date();
    String message = "POST reservation?pos=" + pos + "&xsl=" + xsl + "\nparams " + action.paramString();
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Reservation result = null;
    try {

        String partyid = Constants.decryptPos(pos);

        Product product = getProduct(sqlSession, pos, action.getProductid(), License.DEFAULT_WAIT);
        if (product == null) {
            throw new ServiceException(Error.product_id, action.getProductid());
        }

        if (action.notValidState()) {
            throw new ServiceException(Error.reservation_state, action.getId() + " " + action.getState());
        }

        if (action.noId()) { //new reservation
            result = action;
            result.setName(SessionService.pop(sqlSession, product.getSupplierid(), Serial.RESERVATION));
            //set booking id in the name field

            result.setAltpartyid(product.getAltpartyid());
            result.setAltid(action.getAltid());
            //            result.setName("Booking Id "+action.getAltid());
            result.setOrganizationid(product.getSupplierid());
            result.setActorid(Party.NO_ACTOR);

            //TODO:COnfirm with Chirayu
            if (action.getAgentid() != null) {
                result.setAgentid(action.getAgentid());
            } else {
                result.setAgentid(partyid);
            }

            result.setDate(new Date());
            result.setDuedate(result.getDate());
            result.setDonedate(null);
            result.setUnit(product.getUnit());
            result.setCurrency(product.getCurrency());
            result.setState(action.getState());
            sqlSession.getMapper(ReservationMapper.class).create(result);
            if (State.Cancelled.name().equalsIgnoreCase(action.getState())) {
                // incase a reservation is created and cancelled
                // immediately.
                // TODO:validate with chirayu.

                MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, result);
                sqlSession.commit();
                return result;
            }
        } else {

            result = sqlSession.getMapper(ReservationMapper.class).read(action.getId());

        }

        if (result == null) {
            throw new ServiceException(Error.reservation_id, action.getId());
        }

        if (action.getEmailaddress() != null) {
            Party customer = getParty(sqlSession, action.getEmailaddress(), action.getFamilyname(),
                    action.getFirstname());
            RelationService.replace(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(), partyid,
                    customer.getId());
            RelationService.replace(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(),
                    product.getSupplierid(), customer.getId());
            result.setCustomerid(customer.getId());
            result.setEmailaddress(action.getEmailaddress());
        }

        if (action.getFromdate() != null || action.getTodate() != null) {
            if (action.noDuration(0.9, Time.DAY)) {
                throw new ServiceException(Error.date_invalid, action.getProductFromToDate());
            }
            result.setFromdate(action.getFromdate());
            result.setTodate(action.getTodate());
        }

        if (action.getArrivaltime() != null) {
            result.setArrivaltime(action.getArrivaltime());
        } else {
            result.setArrivaltime(Reservation.ARRIVALTIME);
        }

        if (action.getDeparturetime() != null) {
            result.setDeparturetime(action.getDeparturetime());
        } else {
            result.setDeparturetime(Reservation.DEPARTURETIME);
        }

        Double quote = action.getQuote();
        Double taxrate = action.getTaxrate();
        String currency = action.getCurrency();

        //if (quote != null) {result.setQuote(quote);}
        if (taxrate != null) {
            result.setTaxrate(taxrate);
        }
        if (currency != null) {
            result.setCurrency(currency);
        }

        if (action.hasNotes()) {
            result.setNotes(action.getNotes());
        }

        result.setState(action.getState());

        ReservationService.computePrice(sqlSession, result, null);
        if (quote != 0) {
            Double oldquote = action.getQuote();
            action.setQuote(quote);
            if (action.getQuotedetail() != null) {
                for (net.cbtltd.shared.Price pricedetail : action.getQuotedetail()) {
                    if (pricedetail.hasType(net.cbtltd.shared.Price.TAX_EXCLUDED)
                            || pricedetail.hasType(net.cbtltd.shared.Price.TAX_INCLUDED)
                            || pricedetail.hasType(net.cbtltd.shared.Price.TAX_ON_TAX)) {
                        pricedetail.setValue(pricedetail.getValue() * quote / oldquote);
                    }
                }
            }
        }

        //TODO: save tax allocations
        if (result.notCurrency(product.getCurrency())) {
            result.setQuote(WebService.getRate(sqlSession, result.getCurrency(), product.getCurrency())
                    * result.getQuote());
        }
        result.setCost(result.getQuote() * ReservationService.getDiscountfactor(sqlSession, result));
        result.setDeposit(ReservationService.getDeposit(sqlSession, result)); //.getOrganizationid(), action.getFromdate()));
        if (result.getDeposit() != null && result.getDeposit().isNaN()) {
            result.setDeposit(0.0);
        }

        sqlSession.getMapper(ReservationMapper.class).update(result);

        if (action.getKeyvalues() != null) {
            ArrayList<String> kvs = new ArrayList<String>();
            Collection<KeyValue> keyvalues = action.getKeyvalues();
            for (KeyValue keyvalue : keyvalues) {
                kvs.add(keyvalue.getKey() + Model.DELIMITER + keyvalue.getValue());
            }
            RelationService.replace(sqlSession, Relation.RESERVATION_VALUE, action.getId(), kvs);
        }

        result.setAlert(getAlert(sqlSession, result));
        String textid = NameId.Type.Party.name() + product.getSupplierid() + Text.Code.Contract.name();
        String terms = TextService.notes(sqlSession, textid, Language.EN);
        result.setTerms(terms);

        result.setCollisions(ReservationService.getCollisions(sqlSession, result));
        if (result.hasCollisions()) {
            throw new ServiceException(Error.product_not_available, result.getProductFromToDate());
        }

        //System.out.println("\nALTID " + product.hasAltpartyid() + " " + product.getAltpartyid());

        if (product.hasAltpartyid()) {
            try {
                PartnerService.createReservation(sqlSession, result);
            } catch (ServiceException e) {
                //   LOG.error(e.getMessage(),e);
                LOG.error(e.getMessage());
            }
        }

        MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, result);
        sqlSession.commit();

        if (result.isActive() && product.noAltpartyid()) {
            EmailService.provisionalReservation(sqlSession, result);
        }

    } catch (Throwable x) {
        x.printStackTrace();
        sqlSession.rollback();
        result = new Reservation();
        result.setMessage(message + "\nsetReservation failed " + x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);

    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservation.java

protected static synchronized ReservationResponse createReservationPayment(String pos, String productId,
        String fromDate, String toDate, String emailAddress, String familyName, String firstName, String notes,
        String cardNumber, String cardExpiryMonth, String cardExpiryYear, String amount, String currency,
        String phoneNumber, Integer cardType, Integer cvc, Integer adult, Integer child, String address,
        String country, String state, String city, String zip, Integer birthDay, Integer birthMonth,
        Integer birthYear, String altId) {
    resetValue(address);/*w  w w  .  j ava  2 s  .  com*/
    resetValue(country);
    resetValue(city);
    resetValue(state);
    SqlSession sqlSession = RazorServer.openSession();
    ReservationResponse response = new ReservationResponse();
    PaymentTransaction paymentTransaction = null;
    PendingTransaction pendingTransaction = null;
    Reservation reservation = new Reservation();
    boolean reservationFinished = false;
    GatewayHandler handler = null;
    try {
        if (StringUtils.isEmpty(pos) || StringUtils.isEmpty(productId) || StringUtils.isEmpty(fromDate)
                || StringUtils.isEmpty(toDate) || StringUtils.isEmpty(emailAddress)
                || StringUtils.isEmpty(familyName) | StringUtils.isEmpty(firstName)
                || StringUtils.isEmpty(phoneNumber) || cardType == null || child == null
                || StringUtils.isEmpty(currency) || birthDay == null || birthMonth == null || birthYear == null
                || amount == null || zip == null) {
            throw new ServiceException(Error.parameter_absent);
        }

        if (adult == null || adult < 1) {
            throw new ServiceException(Error.missing_adult_parameter);
        }
        if (StringUtils.isEmpty(cardNumber) || StringUtils.isEmpty(cardExpiryMonth)
                || StringUtils.isEmpty(cardExpiryYear) || cvc == null) {
            //            throw new ServiceException(Error.credit_card_error);
        }
        //yyyy-mm-dd
        if (fromDate.compareToIgnoreCase(toDate) > 0) {
            throw new ServiceException(Error.date_range);
        }

        Date birthDate = null;
        if (birthYear != null && birthMonth != null && birthDay != null) {
            birthDate = stringToDate(birthYear, birthMonth - 1, birthDay);
        }

        boolean encodable = false;
        if (state != null) {
            encodable = CommonUtils
                    .iso88591Encodable(new String[] { firstName, familyName, address, country, city, state });
        } else {
            encodable = CommonUtils
                    .iso88591Encodable(new String[] { firstName, familyName, address, country, city });
        }

        if (!encodable) {
            throw new ServiceException(Error.parameter_invalid);
        }

        //   String[] ignoreIds = {"179805", "90640", "179769","179791","179792","179793","179795","179801","179802", "179896", "179797",
        //      "179799", "179800", "179803", "179804"};  

        // Credit card initialization
        CreditCard creditCard = new CreditCard();
        creditCard.setFirstName(firstName);
        creditCard.setLastName(familyName);
        creditCard.setMonth(cardExpiryMonth);
        cardNumber = cardNumber.trim();
        creditCard.setNumber(cardNumber);
        creditCard.setType(CreditCardType.get(cardType));
        creditCard.setYear(cardExpiryYear);
        creditCard.setSecurityCode(cvc.toString());

        // Initialization of necessary instances
        Product product = sqlSession.getMapper(ProductMapper.class).read(productId);
        if (!product.getState().equals(Product.CREATED)) {
            throw new ServiceException(Error.product_inactive);
        }
        int supplierId = Integer.valueOf(product.getSupplierid());
        PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(supplierId);
        if (propertyManagerInfo == null) {
            throw new ServiceException(Error.database_cannot_find_property_manager, String.valueOf(supplierId));
        }

        response.setPropertyName(product.getName());
        response.setPropertyAddress(ReservationService.getPropertyLocation(sqlSession, product));

        // Initialization end
        Party channelPartnerParty = JSONService.getParty(sqlSession, pos);
        //      Party channelPartnerParty = JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive
        if (channelPartnerParty == null) {
            throw new ServiceException(Error.reservation_agentid);
        }
        //         Party customer = JSONService.getCustomer(sqlSession, emailAddress, familyName, firstName, product.getSupplierid(), phoneNumber, channelPartnerParty);
        Party customer = processCustomer(sqlSession, emailAddress, familyName, firstName, product, phoneNumber,
                channelPartnerParty, product.getSupplierid(), channelPartnerParty, address, country, city, zip,
                state, birthDate);
        Party propertyManager = sqlSession.getMapper(PartyMapper.class)
                .read(propertyManagerInfo.getPropertyManagerId().toString());
        response.setPropertyManagerName(propertyManager.getName());
        response.setPropertyManagerEmail(propertyManager.getEmailaddress());
        response.setPropertyManagerPhone(propertyManager.getDayphone());

        // Reservation processing
        reservation = PaymentHelper.prepareReservation(channelPartnerParty, customer, product,
                propertyManagerInfo, fromDate, toDate, notes, productId, adult, child);

        // END INITIALIZATION BLOCK

        Double amountToCheck = PaymentHelper.roundAmountTwoDecimals(amount);
        Double amountDifference = PaymentHelper.amountDifference(sqlSession, reservation, amountToCheck,
                currency);
        if (amountDifference > 1 && (BPThreadLocal.get() == null || !BPThreadLocal.get())) {
            throw new ServiceException(Error.price_not_match,
                    "passed: " + amountToCheck + currency + ", difference: " + amountDifference);
        }

        if (propertyManagerInfo.getFundsHolder() == ManagerToGateway.bookingnet_HOLDER) {
            //            amount = PaymentHelper.convertToDefaultMbpCurrency(sqlSession, reservation, propertyManagerInfo, PaymentHelper.roundAmountTwoDecimals(amount), currency).toString();
            currency = PaymentHelper.DEFAULT_bookingnet_CURRENCY;
        } else {
            //            amount = PaymentService.convertCurrency(sqlSession, currency, reservation.getCurrency(), PaymentHelper.roundAmountTwoDecimals(amount)).toString();
            currency = product.getCurrency();
        }
        if (reservation.getAltpartyid() == null
                || !Arrays.asList(livePricingIds).contains(reservation.getAltpartyid())) {
            ReservationService.computePrice(sqlSession, reservation, currency);
            Double deposit = ReservationService.getDeposit(reservation, propertyManagerInfo);
            reservation.setDeposit(deposit);
            reservation.setCost(
                    reservation.getQuote() * ReservationService.getDiscountfactor(sqlSession, reservation));
        } else {
            LOG.error("PartnerService.readPrice started");
            PartnerService.readPrice(sqlSession, reservation, product.getAltid(), currency);

            if ((reservation.getPrice() == null || reservation.getPrice() <= 0)
                    || (reservation.getQuote() == null || reservation.getQuote() <= 0)) {
                throw new ServiceException(Error.price_missing, "Price was resturned null or 0");
            }

            ReservationService.computeLivePrice(sqlSession, reservation, null, currency);

            LOG.error("PartnerService.readPrice finished");

        }

        if (reservation.getPrice() == 0.0) {
            throw new ServiceException(Error.price_data);
        }

        // END PRICE BLOCK

        boolean available = sqlSession.getMapper(ReservationMapper.class).available(reservation);
        if (!available) {
            throw new ServiceException(Error.product_not_available);
        }
        reservation.setState(Reservation.State.Provisional.name());

        reservation
                .setName(SessionService.pop(sqlSession, reservation.getOrganizationid(), Serial.RESERVATION));

        reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation));
        if (reservation.hasCollisions()) {
            throw new ServiceException(Error.product_not_available, reservation.getProductFromToDate());
        }

        if (StringUtils.isNotEmpty(altId)) {
            reservation.setAltid(altId);
        }
        sqlSession.getMapper(ReservationMapper.class).create(reservation);

        ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard);

        // END AVAILABILITY BLOCK

        ManagerToGateway managerToGateway = null;
        PaymentGatewayProvider paymentGatewayProvider = null;
        Map<String, String> resultMap = null;
        int paymentGatewayId = -1;
        // Processing charge type
        String chargeType = PaymentHelper.getChargeType(propertyManagerInfo, reservation);
        Double firstPayment = PaymentHelper.getFirstPayment(reservation, propertyManagerInfo);
        Double secondPayment = PaymentHelper.getSecondPayment(reservation, propertyManagerInfo);

        response.setDownPayment(firstPayment);

        Double amountToCharge = PaymentHelper.isFullPaymentMethod(chargeType) ? firstPayment + secondPayment
                : firstPayment;
        if (PaymentHelper.isApiPaymentMethod(chargeType)) {
            if (StringUtils.isEmpty(reservation.getState())) {
                reservation.setState(Reservation.State.Confirmed.name());
            }
            resultMap = PartnerService.createReservationAndPayment(sqlSession, reservation, creditCard);
            if (resultMap != null && PaymentHelper.isDepositPaymentMethod(chargeType)
                    && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName,
                        firstName, cardNumber, phoneNumber, reservation, product,
                        propertyManagerInfo.getPropertyManagerId(), propertyManagerInfo, secondPayment, null,
                        resultMap, null);
                sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction);
                sqlSession.commit();
            }
        } else if (chargeType.equalsIgnoreCase(PaymentHelper.FULL_PAYMENT_METHOD)
                || chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD)) {
            /* 
             * The following line is bad because this is the final payment. Once it was charged, we have no information about renter's CC
             * and in case of cancellation (deposit and full payment) or second payment (deposit payment) we have no CC information about renter.
             * Thus, there is always needed to create the payment profile in payment gateway and store returned information to database.
             * 
             * resultMap = handler.createPaymentByCreditCard(product.getCurrency(), firstPayment);
             */

            // Payment gateway initialization
            managerToGateway = sqlSession.getMapper(ManagerToGatewayMapper.class).readBySupplierId(supplierId);
            paymentGatewayId = managerToGateway.getPaymentGatewayId();
            paymentGatewayProvider = PaymentGatewayHolder.getPaymentGateway(paymentGatewayId);
            handler = PaymentHelper.initializeHandler(propertyManagerInfo, managerToGateway, creditCard);

            if (!paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge,
                        reservation, handler, currency, creditCard, paymentGatewayId);
            }

            // Pending transaction processing
            if (resultMap != null && chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD)
                    && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName,
                        firstName, cardNumber, phoneNumber, reservation, product, supplierId,
                        propertyManagerInfo, secondPayment, paymentGatewayProvider, resultMap,
                        paymentGatewayId);

                sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction);
            }
        } else if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) {
            setReservationState(reservation, chargeType);
            response.setReservationInfo(new ReservationInfo(reservation));
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            sqlSession.commit();
        } else {
            throw new ServiceException(Error.payment_method_unsupported);
        }

        if (propertyManagerInfo.getPropertyManagerId() != Integer.valueOf(RazorConfig.getNextpaxNovasolId())) {
            paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation,
                    propertyManagerInfo, firstPayment, managerToGateway, cardNumber,
                    Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false);
        }

        if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) {
            sendEmails(sqlSession, paymentTransaction, chargeType);
            return response;
        }

        // END PAYMENT BLOCK

        if (resultMap != null && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)
                || (paymentGatewayProvider != null
                        && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS))) {
            if (product.hasAltpartyid() && !PaymentHelper.isApiPaymentMethod(chargeType)) {
                if (reservation.getState() == null) {
                    reservation.setState(Reservation.State.Confirmed.name());
                }
                try {
                    PartnerService.createReservation(sqlSession, reservation);
                } catch (ServiceException e) {
                    LOG.error(e.getMessage());
                }
            }

            MonitorService.update(sqlSession, Data.Origin.JQUERY, NameId.Type.Reservation, reservation);

            if (paymentGatewayProvider != null
                    && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                if (paymentGatewayId != -1 && paymentGatewayProvider != null
                        && (!reservation.getState().equals(Reservation.State.Cancelled.name()))) {
                    resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge,
                            reservation, handler, currency, creditCard, paymentGatewayId);
                    paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation,
                            propertyManagerInfo, firstPayment, managerToGateway, cardNumber,
                            Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false);
                    if (resultMap == null
                            || !resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) {
                        LOG.error("An error occurred while processing your payment");
                        PartnerService.cancelReservation(sqlSession, reservation);
                        reservation.setState(Reservation.State.Cancelled.name());
                        if (resultMap != null) {
                            response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG));
                        } else {
                            response.setErrorMessage("Something went wrong with payment processing");
                        }
                    } else {
                        PartnerService.confirmReservation(sqlSession, reservation);
                    }
                }
            }

            // END PARTNER RESERVATION BLOCK

            // refund transaction made in case of PMS rejected the reservation
            if (paymentTransaction != null && reservation.getState() != null
                    && reservation.getState().equals(Reservation.State.Cancelled.name())) {
                List<PaymentTransaction> paymentTransactions = new ArrayList<PaymentTransaction>();
                paymentTransactions.add(paymentTransaction);
                refundAmount(sqlSession, supplierId, paymentTransactions, firstPayment);
                cancelPendingTransactions(sqlSession, reservation);
                reservationFinished = true;
                throw new ServiceException(Error.pms_reservation_reject);
            } else if (paymentTransaction == null && paymentGatewayProvider != null
                    && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) {
                cancelPendingTransactions(sqlSession, reservation);
                reservationFinished = true;
                throw new ServiceException(Error.pms_reservation_reject);
            } else {
                setReservationState(reservation, chargeType);
                reservationFinished = true;
            }

            ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard);
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            // Pending transaction end
            sendEmails(sqlSession, paymentTransaction, chargeType);

            // END VERIFICATION BLOCK
        } else {
            reservation.setState(Reservation.State.Cancelled.name());
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            if (resultMap != null && resultMap.get(GatewayHandler.ERROR_MSG) != null) {
                LOG.error("An error occurred while processing your payment");
                response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG));
            } else {
                LOG.error("An error occurred while processing your payment");
                response.setErrorMessage("Something went wrong with payment processing");
            }
        }
        sqlSession.commit();
    } catch (ServiceException ex) {
        response.setErrorMessage(ex.getDetailedMessage());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        LOG.error(ex.getDetailedMessage());

        if (reservationFinished) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
    } catch (Throwable x) {
        x.printStackTrace();
        response.setErrorMessage(x.getMessage());
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        LOG.error(x.getMessage());

        if (reservationFinished) {
            sqlSession.commit();
        } else {
            sqlSession.rollback();
        }
    } finally {
        sqlSession.close();
    }

    try {
        sqlSession = RazorServer.openSession();
        if (paymentTransaction != null) {
            sqlSession.getMapper(PaymentTransactionMapper.class).create(paymentTransaction);
            sqlSession.commit();
        }
    } catch (Throwable x) {
        response.setErrorMessage(x.getMessage());
        LOG.error(x.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }

    try {
        sqlSession = RazorServer.openSession();
        roundReservationDoubleValues(reservation);
        sendAdminEmail(sqlSession, paymentTransaction);
    } catch (Exception x) {
        if (!response.isError()) {
            response.setErrorMessage("Unable to round the values for reservation. :" + x.getMessage());
        }
        LOG.error("Unable to round the values for reservation.");
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }

    response.setReservationInfo(new ReservationInfo(reservation));
    return response;
}

From source file:net.cbtltd.rest.AbstractReservation.java

protected static synchronized CancelReservationResponse cancelBooking(String reservationPos) throws Exception {
    SqlSession sqlSession = RazorServer.openSession();
    CancelReservationResponse cancelReservationResponse = new CancelReservationResponse();
    try {//from  w w w.  j  a v  a  2s . c  o m
        if (reservationPos == null) {
            throw new ServiceException(Error.parameter_absent, "reservationId");
        }

        String reservationId = Model.decrypt(reservationPos);
        Reservation reservation = sqlSession.getMapper(ReservationMapper.class).read(reservationId);
        if (reservation == null) {
            throw new ServiceException(Error.database_cannot_find, "reservation");
        }
        if (reservation.getState().equals(Reservation.State.Cancelled.name())) {
            throw new ServiceException(Error.reservation_cancelled);
        }

        int propertyManagerId = Integer.valueOf(reservation.getOrganizationid());
        PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(propertyManagerId);
        if (propertyManagerInfo == null) {
            throw new ServiceException(Error.database_cannot_find, "property manager info");
        }

        double cancellationAmount = ReservationService.calculateCancellationAmount(sqlSession, reservation,
                propertyManagerInfo);
        boolean refund = cancellationAmount < 0;

        ManagerToGateway managerToGateway = sqlSession.getMapper(ManagerToGatewayMapper.class)
                .readBySupplierId(propertyManagerId);
        Map<String, String> transactionResult = null;

        // initialize property manager and agent
        Party propertyManager = sqlSession.getMapper(PartyMapper.class)
                .read(propertyManagerInfo.getPropertyManagerId().toString());
        Party renter = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
        Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
        String propertyAddress = ReservationService.getPropertyLocation(sqlSession, product);

        double absAmount = Math.abs(cancellationAmount);
        reservation.setState(Reservation.State.Cancelled.name());
        if (propertyManagerInfo.getFundsHolder() == ManagerToGateway.bookingnet_HOLDER) {
            cancelPendingTransaction(sqlSession, reservation);
            if (managerToGateway == null) {
                if (refund) {
                    EmailService.cancelWithoutGatewayToPMRefund(propertyManager, renter, reservation, absAmount,
                            propertyAddress);
                } else {
                    EmailService.cancelWithoutGatewayToPMCharge(propertyManager, renter, reservation, absAmount,
                            propertyAddress);
                }
                insertCancellationPaymentTransaction(sqlSession, cancellationAmount, managerToGateway,
                        reservation, propertyManagerInfo, null, null, null, null, null, "");
                SharedService.onReservationStateChange(sqlSession, reservation, product);
            } else {
                List<PaymentTransaction> paymentTransactions = sqlSession
                        .getMapper(PaymentTransactionMapper.class)
                        .readByReservationId(Integer.valueOf(reservationId));
                CreditCard creditCard = new CreditCard();
                creditCard.setNumber(String.valueOf(paymentTransactions.get(0).getPartialIin()));
                GatewayHandler gatewayHandler = PaymentHelper.initializeHandler(propertyManagerInfo,
                        managerToGateway, creditCard);
                if (absAmount >= 1) {
                    if (refund) {
                        transactionResult = gatewayHandler.createRefund(paymentTransactions, absAmount);
                        EmailService.cancelWithGatewayToPMRefund(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                        EmailService.cancelWithGatewayToRenterRefund(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                    } else {
                        transactionResult = gatewayHandler.createPaymentByProfile(sqlSession,
                                reservation.getCurrency(), absAmount, Integer.valueOf(reservationId));
                        EmailService.cancelWithGatewayToPMCharge(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                        EmailService.cancelWithGatewayToRenterCharge(propertyManager, renter, reservation,
                                absAmount, propertyAddress);
                    }
                    if (transactionResult != null) {
                        insertCancellationPaymentTransaction(sqlSession, cancellationAmount, managerToGateway,
                                reservation, propertyManagerInfo,
                                transactionResult.get(GatewayHandler.TRANSACTION_ID),
                                transactionResult.get(GatewayHandler.ERROR_MSG),
                                Integer.valueOf(creditCard.getNumber()), null,
                                transactionResult.get(GatewayHandler.STATE),
                                paymentTransactions.get(0).getCurrency());
                    }
                }
                // set cancelled flag to true
                for (PaymentTransaction paymentTransaction : paymentTransactions) {
                    if (paymentTransaction.getStatus().equals(GatewayHandler.ACCEPTED)) {
                        updateTransactionToCancelled(sqlSession, paymentTransaction);
                    }
                }
                if (paymentTransactions.get(0) != null) {
                    ReservationService.createEvent(sqlSession, paymentTransactions.get(0), reservation,
                            creditCard);
                }
            }
        } else {
            EmailService.cancelPMWithoutFundsHolder(sqlSession, propertyManager, renter, reservation,
                    propertyAddress);
            EmailService.cancelRenterWithoutFundsHolder(propertyManager, renter, reservation, propertyAddress);
            SharedService.onReservationStateChange(sqlSession, reservation, product);
        }

        if (transactionResult != null && transactionResult.get(GatewayHandler.ERROR_MSG) != null) {
            cancelReservationResponse.setErrorMessage(transactionResult.get(GatewayHandler.ERROR_MSG));
        }
        sqlSession.getMapper(ReservationMapper.class).update(reservation);
        sqlSession.commit();
        if (product.hasAltpartyid()) {
            PartnerService.cancelReservation(sqlSession, reservation);
        }
    } catch (Exception e) {
        cancelReservationResponse.setErrorMessage(e.getMessage());
        LOG.error(e.getMessage());
        sqlSession.rollback();
    } finally {
        sqlSession.close();
    }
    return cancelReservationResponse;
}

From source file:net.cbtltd.rest.AbstractReservation.java

/**
 * Creates, updates or cancels a reservation.
 *
 * @param action the reservation parameter.
 * @param pos the POS code.// w w w .  ja v  a  2 s.co m
 * @param xsl the style sheet.
 * @return the provisional reservation.
 */
protected static synchronized Reservation cancelUnPaidBookings(Reservation action, String pos, String xsl) {
    Date timestamp = new Date();
    String message = "POST reservation?pos=" + pos + "&xsl=" + xsl + "\nparams " + action.paramString();
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Reservation result = null;
    try {

        @SuppressWarnings("unused")
        String partyid = Constants.decryptPos(pos);

        Product product = getProduct(sqlSession, pos, action.getProductid(), License.DEFAULT_WAIT);
        if (product == null) {
            throw new ServiceException(Error.product_id, action.getProductid());
        }

        if (action.notValidState()) {
            throw new ServiceException(Error.reservation_state, action.getId() + " " + action.getState());
        }

        if (!action.noId()) { //existing reservation
            result = sqlSession.getMapper(ReservationMapper.class).read(action.getId());
        }

        if (result == null) {
            throw new ServiceException(Error.reservation_id, action.getId());
        }

        int propertyManagerId = Integer.valueOf(action.getOrganizationid());
        PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                .readbypmid(propertyManagerId);

        PropertyManagerCancellationRule cancellationRule = PaymentHelper.getRuleForCurrentDate(sqlSession,
                action, propertyManagerInfo.getPropertyManagerId());
        double cancellationTransactionFee = 0;
        if (cancellationRule != null) {
            cancellationTransactionFee = cancellationRule.getCancellationTransactionFee() == null ? 0
                    : cancellationRule.getCancellationTransactionFee();
            @SuppressWarnings("unused")
            double amountToRenter = PaymentHelper.getCancellationAmountWithoutFee(action, cancellationRule,
                    action.getCurrency());
        }

        if (cancellationTransactionFee == 0) {
            result.setState(Reservation.State.Cancelled.name());
            sqlSession.getMapper(ReservationMapper.class).update(result);
            MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, result);
        }
        sqlSession.commit();
    } catch (Throwable x) {
        x.printStackTrace();
        sqlSession.rollback();
        result = new Reservation();
        result.setMessage(message + "\nsetReservation failed " + x.getMessage());
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);

    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Creates a provisional reservation.//w ww  .ja v a2 s. co m
 *
 * @param productid the productid
 * @param fromdate the fromdate
 * @param todate the todate
 * @param emailaddress the emailaddress
 * @param familyname the familyname
 * @param firstname the firstname
 * @param notes the reservation notes
 * @param quote the quoted price for the stay
 * @param tax the total tax on the quoted price for the stay
 * @param currency the currency code of the quote
 * @param pos the pos
 * @param test the test
 * @param xsl the xsl
 * @return the provisional
 */
protected static Provisional getProvisional(String productid, String fromdate, String todate,
        String emailaddress, String familyname, String firstname, String notes, String quote, String tax,
        String currency, String pos, Boolean test, String xsl) {
    Date timestamp = new Date();
    String message = "/reservation/" + productid + "/" + fromdate + "/" + todate + "/" + emailaddress + "/"
            + familyname + "/" + firstname + "/" + notes + "/" + quote + "/" + tax + "/" + currency + "?pos="
            + pos + "&test=" + test + "&xsl=" + xsl;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Provisional result = null;
    try {
        Party agent = Constants.getParty(sqlSession, pos);

        Product product = getProduct(sqlSession, pos, productid, License.DEFAULT_WAIT); //sqlSession.getMapper(ProductMapper.class).read(productid);
        if (product == null || !product.hasState(Constants.CREATED)) {
            throw new ServiceException(Error.product_id, productid);
        }
        if (product.notType(Product.Type.Accommodation.name())) {
            throw new ServiceException(Error.product_type, productid + " is not Accommodation");
        }
        if (product.noRank()) {
            throw new ServiceException(Error.product_not_online, productid);
        }

        if (emailaddress == null || emailaddress.isEmpty() || !Party.isEmailAddress(emailaddress)) {
            throw new ServiceException(Error.party_emailaddress, emailaddress);
        }
        if (fromdate == null || fromdate.isEmpty() || todate == null || todate.isEmpty()) {
            throw new ServiceException(Error.date_invalid, fromdate + " to " + todate);
        }
        if (!Constants.parseDate(todate).after(Constants.parseDate(fromdate))) {
            throw new ServiceException(Error.date_format, fromdate + " to " + todate);
        }
        if (familyname == null || familyname.isEmpty()) {
            throw new ServiceException(Error.family_name, familyname);
        }
        Party customer = sqlSession.getMapper(PartyMapper.class).readbyemailaddress(emailaddress);
        if (customer == null) {
            customer = new Party();
            customer.setEmailaddress(emailaddress);
            customer.setName(familyname, firstname);
            sqlSession.getMapper(PartyMapper.class).create(customer);
            RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(), agent.getId(),
                    customer.getId());
            RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(),
                    product.getSupplierid(), customer.getId());
        }

        Reservation reservation = new Reservation();
        reservation.setOrganizationid(product.getSupplierid());
        reservation.setActorid(Party.NO_ACTOR);
        reservation.setAgentid(agent.getId());
        reservation.setCustomerid(customer.getId());
        reservation.setFromdate(Constants.parseDate(fromdate));
        reservation.setTodate(Constants.parseDate(todate));
        reservation.setDate(new Date());
        reservation.setArrivaltime("14:00");
        reservation.setDeparturetime("10:00");
        reservation.setDuedate(reservation.getDate());
        reservation.setDonedate(null);
        reservation.setUnit(product.getUnit());
        reservation.setCurrency(product.getCurrency());
        reservation.setNotes(notes == null || notes.isEmpty() ? "XML Reservation Request" : notes);
        reservation.setState(Reservation.State.Provisional.name());
        reservation.setProductid(productid);
        ReservationService.computePrice(sqlSession, reservation, null);

        if (quote != null && tax != null) {
            Double oldquote = reservation.getQuote();
            if (currency != null && !product.hasCurrency(currency)) {
                reservation.setQuote(WebService.getRate(sqlSession, currency, product.getCurrency())
                        * ((oldquote == null) ? 0.0 : oldquote));
            }
            Double newquote = Double.valueOf(quote);
            reservation.setQuote(newquote);
            if (reservation.hasQuotedetail()) {
                for (net.cbtltd.shared.Price price : reservation.getQuotedetail()) {
                    if (price.hasType(net.cbtltd.shared.Price.TAX_EXCLUDED)
                            || price.hasType(net.cbtltd.shared.Price.TAX_INCLUDED)
                            || price.hasType(net.cbtltd.shared.Price.TAX_ON_TAX)) {
                        price.setValue(price.getValue() * newquote / oldquote);
                    }
                }
            }
        }

        //TODO: save tax allocations
        reservation.setCost(
                reservation.getQuote() * ReservationService.getDiscountfactor(sqlSession, reservation));

        String textid = NameId.Type.Party.name() + product.getSupplierid() + Text.Code.Contract.name();
        String terms = TextService.notes(sqlSession, textid, Language.EN);

        if (!test) {
            reservation.setName(
                    SessionService.pop(sqlSession, reservation.getOrganizationid(), Serial.RESERVATION));
            sqlSession.getMapper(ReservationMapper.class).create(reservation);

            reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation));
            if (reservation.hasCollisions()) {
                throw new ServiceException(Error.product_not_available,
                        productid + " " + fromdate + " " + todate);
            }

            message = "The provisional reservation number is " + reservation.getName();
            sqlSession.commit();
            EmailService.provisionalReservation(sqlSession, reservation);
        }

        result = new Provisional(reservation.getId(), reservation.getName(), productid, product.getName(),
                fromdate, todate, emailaddress, familyname, firstname,
                String.valueOf(NameId.round(reservation.getPrice())),
                String.valueOf(NameId.round(reservation.getQuote())),
                String.valueOf(NameId.round(reservation.getCost())),
                String.valueOf(NameId.round(reservation.getDeposit(reservation.getQuote()))),
                reservation.getCurrency(), getAlert(sqlSession, reservation), reservation.getNotes(), terms,
                message, xsl);
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Provisional(null, null, productid, null, fromdate, todate, emailaddress, familyname,
                firstname, null, null, null, null, null, null, null, null, message + " " + x.getMessage(), xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Gets the upload./*from  w  w  w  .  j a va2 s .c o  m*/
 *
 * @param reservationid the reservationid
 * @param productid the productid
 * @param fromdate the fromdate
 * @param todate the todate
 * @param emailaddress the emailaddress
 * @param familyname the familyname
 * @param firstname the firstname
 * @param price the price
 * @param currency the currency
 * @param pos the pos
 * @param xsl the xsl
 * @return the upload
 */
protected static Download getUpload(String reservationid, String productid, String fromdate, String todate,
        String emailaddress, String familyname, String firstname, String price, String currency, String pos,
        String xsl) {
    Date timestamp = new Date();
    String message = "/reservation/upload/" + reservationid + "/" + productid + "/" + fromdate + "/" + todate
            + "/" + emailaddress + "/" + familyname + "/" + firstname + "/" + price + "/" + currency + "?pos="
            + pos + "&xsl=" + xsl;
    LOG.debug(message);

    //TODO: CJM
    //if ("76e3fef6c90093eb".equalsIgnoreCase(pos)) {
    //   return new Download("0", "0", "0", "2010-01-01", "2020-12-31", "aaa@bbb.com", "familyname", "firstname", null, null, null, price, currency, message, xsl);
    //}

    SqlSession sqlSession = RazorServer.openSession();
    Download result = null;
    try {
        Party organization = Constants.getParty(sqlSession, pos);
        Party customer = organization;

        if (fromdate == null || fromdate.isEmpty() || todate == null || todate.isEmpty()) {
            throw new ServiceException(Error.date_range, fromdate + " to " + todate);
        }
        if (!Constants.parseDate(todate).after(Constants.parseDate(fromdate))) {
            throw new ServiceException(Error.date_format, fromdate + " to " + todate);
        }

        Product product = getProduct(sqlSession, pos, productid, License.DEFAULT_WAIT); //sqlSession.getMapper(ProductMapper.class).read(productid);
        if (product == null || !product.hasState(Constants.CREATED)) {
            throw new ServiceException(Error.product_id, productid);
        }
        if (product.noRank()) {
            throw new ServiceException(Error.product_not_online, productid);
        }
        if (product.notType(Product.Type.Accommodation.name())) {
            throw new ServiceException(Error.product_id, productid + " not type Accommodation");
        }
        if (!organization.hasId(product.getSupplierid())) {
            throw new ServiceException(Error.pos_party,
                    organization.getId() + " pos code <> manager " + product.getSupplierid());
        }

        Double quote = Double.valueOf(price);
        if (!product.hasCurrency(currency)) { // convert
            Double exchangerate = WebService.getRate(sqlSession, currency, product.getCurrency(), new Date());
            quote = NameId.round(quote * exchangerate);
        }

        if (emailaddress != null && !emailaddress.isEmpty() && !emailaddress.equals(Constants.BLANK)
                && Party.isEmailAddress(emailaddress) && familyname != null && !familyname.isEmpty()
                && !familyname.equals(Constants.UNALLOCATED)) {
            //Find or create customer
            customer = sqlSession.getMapper(PartyMapper.class).readbyemailaddress(emailaddress);
            if (customer == null) {
                customer = new Party();
                customer.setEmailaddress(emailaddress);
                customer.setName(familyname, firstname);
                customer.setCountry(organization.getCountry());
                customer.setCreatorid(organization.getId());
                customer.setCurrency(organization.getCurrency());
                customer.setLanguage(organization.getLanguage());
                customer.setLocationid(organization.getLocationid());
                customer.setState(Party.CREATED);
                sqlSession.getMapper(PartyMapper.class).create(customer);
                RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(),
                        organization.getId(), customer.getId());
                RelationService.create(sqlSession, Relation.ORG_PARTY_ + Party.Type.Customer.name(),
                        product.getSupplierid(), customer.getId());
            }
        }
        //LOG.debug("ReservationService getUpload 1 " + customer);

        Reservation reservation = new Reservation();
        reservation.setName(reservationid);
        reservation.setOrganizationid(product.getSupplierid());
        //         reservation.setOrganizationid(organization.getId());
        if (reservationid.contains(".")) {
            reservation = sqlSession.getMapper(ReservationMapper.class).readbyforeignid(reservationid);
        } else {
            reservation = sqlSession.getMapper(ReservationMapper.class).readbyname(reservation);
        }

        //LOG.debug("ReservationService getUpload 2 " + reservation);

        if (reservation == null && reservationid.contains(".")) { // upload new foreign reservation
            //Create reservation
            reservation = new Reservation();
            String supplierId = product.getSupplierid();
            PropertyManagerInfo proeprtyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class)
                    .readbypmid(Integer.valueOf(supplierId));
            reservation.setOrganizationid(supplierId);
            reservation.setActorid(Party.NO_ACTOR);
            reservation.setAgentid(organization.getId());
            reservation.setCustomerid(customer.getId());
            reservation.setFromdate(Constants.parseDate(fromdate));
            reservation.setTodate(Constants.parseDate(todate));
            reservation.setArrivaltime(proeprtyManagerInfo.getCheckInTime().toString());
            reservation.setDeparturetime(proeprtyManagerInfo.getCheckOutTime().toString());
            reservation.setDate(new Date());
            reservation.setDuedate(reservation.getDate());
            reservation.setDonedate(null);
            //reservation.setDeposit();
            reservation.setUnit(product.getUnit());
            reservation.setCurrency(product.getCurrency());
            reservation.setNotes("Reservation Upload by " + organization.getName());
            reservation.setPrice(NameId.round(Double.valueOf(price)));
            reservation.setPrice(quote);
            reservation.setQuote(reservation.getPrice());
            reservation.setCost(reservation.getPrice());
            reservation.setState(Reservation.State.Confirmed.name());
            reservation.setProductid(productid);

            reservation.setName(
                    SessionService.pop(sqlSession, reservation.getOrganizationid(), Serial.RESERVATION));
            sqlSession.getMapper(ReservationMapper.class).create(reservation);
            RelationService.load(sqlSession, Downloaded.RESERVATION_UPLOAD, reservation.getId(), reservationid);
            RelationService.load(sqlSession, Downloaded.RESERVATION_DOWNLOAD, reservation.getName(),
                    reservation.getOrganizationid());
            //To prevent an uploaded reservation from being downloaded again
        } else if (reservation != null) { // update reservation
            reservation.setOrganizationid(product.getSupplierid());
            reservation.setCustomerid(customer.getId());
            reservation.setFromdate(Constants.parseDate(fromdate));
            reservation.setTodate(Constants.parseDate(todate));
            reservation.setUnit(product.getUnit());
            reservation.setCurrency(product.getCurrency());
            reservation.setPrice(NameId.round(Double.valueOf(price)));
            //            reservation.setPrice(Double.valueOf(price));
            reservation.setQuote(reservation.getPrice());
            reservation.setCost(reservation.getPrice());
            reservation.setState(Reservation.State.Confirmed.name());
            reservation.setProductid(productid);
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
        } else {
            throw new ServiceException(Error.reservation_upload_id, reservationid);
        }
        //LOG.debug("getUpload 3 " + reservation);

        //TODO: CJM         reservation.setCollisions(sqlSession.getMapper(ReservationMapper.class).collisions(reservation));
        reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation));
        if (reservation.hasCollisions()) {
            throw new ServiceException(Error.product_not_available,
                    productid + " from " + fromdate + " to " + todate);
        }
        result = new Download(reservation.getName(), reservationid, productid, fromdate, todate, emailaddress,
                familyname, firstname, null, null, null, price, currency, message, xsl);
        MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, reservation);
        sqlSession.commit();
    } catch (Throwable x) {
        sqlSession.rollback();
        if (x != null && x.getMessage() != null
                && !x.getMessage().startsWith(Error.product_not_available.name())) {
            LOG.error(message + "\n" + x.getMessage());
        }
        result = new Download(null, reservationid, productid, fromdate, todate, emailaddress, familyname,
                firstname, null, null, null, price, currency, message + " " + x.getMessage(), xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Sets the provisional reservation.//from  w ww  .j  a va2 s. com
 *
 * @param reservationid the reservation ID
 * @param productid the product ID
 * @param fromdate the arrival date
 * @param todate the departure date
 * @param quote the quoted price
 * @param cost the sto rate
 * @param currency the quote currency
 * @param pos the pos code
 * @param test the test flag
 * @param xsl the style sheet
 * @return the provisional reservation
 */
protected static Provisional setProvisional(String reservationid, String productid, String fromdate,
        String todate, Double quote, Double cost, String currency, String pos, Boolean test, String xsl) {

    Date timestamp = new Date();
    String message = "/reservation/update/" + reservationid + "/" + productid + "/" + fromdate + "/" + todate
            + "/" + quote + "/" + cost + "/" + currency + "?pos=" + pos + "&test=" + test + "&xsl=" + xsl;
    LOG.debug(message);
    SqlSession sqlSession = RazorServer.openSession();
    Provisional result = null;
    try {
        Party agent = Constants.getParty(sqlSession, pos);

        if (reservationid == null || reservationid.isEmpty()) {
            throw new ServiceException(Error.reservation_id, reservationid);
        }
        Reservation reservation = sqlSession.getMapper(ReservationMapper.class).read(reservationid);
        if (reservation == null || reservationid.isEmpty()) {
            throw new ServiceException(Error.reservation_id, reservationid);
        }
        if (reservation.hasState(Reservation.State.Initial.name())
                || reservation.hasState(Reservation.State.Closed.name())
                || reservation.hasState(Reservation.State.Cancelled.name())
                || reservation.hasState(Reservation.State.Arrived.name())
                || reservation.hasState(Reservation.State.Departed.name())
                || reservation.hasState(Reservation.State.Final.name())) {
            throw new ServiceException(Error.reservation_state,
                    reservation.getName() + " " + reservation.getState());
        }

        if (productid == null || productid.isEmpty()) {
            productid = reservation.getProductid();
        }
        Product product = getProduct(sqlSession, pos, productid, License.DEFAULT_WAIT); //sqlSession.getMapper(ProductMapper.class).read(productid);

        if (product == null) {
            throw new ServiceException(Error.product_id, productid);
        }
        if (!product.hasState(Constants.CREATED)) {
            throw new ServiceException(Error.product_state, productid + " has state " + product.getState());
        }
        if (product.notType(Product.Type.Accommodation.name())) {
            throw new ServiceException(Error.product_type, product.getType());
        }
        if (product.noRank()) {
            throw new ServiceException(Error.product_not_online, productid);
        }
        reservation.setProductid(productid);

        if (fromdate != null && !fromdate.isEmpty()) {
            reservation.setFromdate(Constants.parseDate(fromdate));
        }
        if (todate != null && !todate.isEmpty()) {
            reservation.setTodate(Constants.parseDate(todate));
        }
        if (!reservation.getTodate().after(reservation.getFromdate())) {
            throw new ServiceException(Error.date_range, fromdate + " to " + todate);
        }

        if (quote != null && quote > 0.0 && reservation.hasCurrency(currency)) {
            reservation.setQuote(quote);
        }

        if (cost != null && cost > 0.0 && reservation.hasCurrency(currency)) {
            reservation.setCost(cost);
        }

        if (!test) {
            sqlSession.getMapper(ReservationMapper.class).update(reservation);

            //TODO: CJM            reservation.setCollisions(sqlSession.getMapper(ReservationMapper.class).collisions(reservation));
            reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation));
            if (reservation.hasCollisions()) {
                throw new ServiceException(Error.product_not_available,
                        productid + " from " + fromdate + " to " + todate);
            }
            MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, reservation);
            sqlSession.commit();
        }
        result = new Provisional(productid, product.getName(), Constants.formatDate(reservation.getFromdate()),
                Constants.formatDate(reservation.getTodate()),
                String.valueOf(NameId.round(reservation.getQuote())), reservation.getCurrency(),
                getAlert(sqlSession, reservation), message, xsl);
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Provisional(productid, null, fromdate, todate, String.valueOf(NameId.round(quote)),
                currency, null, message, xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}

From source file:net.cbtltd.rest.AbstractReservationExt.java

/**
 * Cancel download.// w w w. j av  a  2s. c  om
 *
 * @param reservationname the reservation number
 * @param pos the pos
 * @param test the test
 * @param xsl the xsl
 * @return the response
 */
protected static Response cancelDownload(String reservationname, String pos, Boolean test, String xsl) {

    Date timestamp = new Date();
    String message = "/reservation/cancel/" + reservationname + "?pos=" + pos + "&test=" + test + "&xsl=" + xsl;
    LOG.debug(message);

    SqlSession sqlSession = RazorServer.openSession();
    Response result = null;
    try {
        //String organizationid = Constants.decryptPos(pos);
        Party organization = Constants.getParty(sqlSession, pos);
        Reservation reservation = new Reservation();
        reservation.setName(reservationname);
        reservation.setOrganizationid(organization.getId());
        if (reservationname.contains(".")) {
            reservation = sqlSession.getMapper(ReservationMapper.class).readbyforeignid(reservationname);
        } else {
            reservation = sqlSession.getMapper(ReservationMapper.class).readbyname(reservation);
        }
        if (reservation == null) {
            reservation = sqlSession.getMapper(ReservationMapper.class).read(reservationname);
        }
        if (reservation == null || !organization.hasId(reservation.getOrganizationid())) {
            throw new ServiceException(Error.reservation_bad, reservationname);
        }

        getProduct(sqlSession, pos, reservation.getProductid(), License.DEFAULT_WAIT);

        if (!test) {
            reservation.setState(Reservation.State.Cancelled.name());
            //EmailService.canceledReservation(sqlSession, organizationid, reservation);
            reservation.setDonedate(new Date());
            sqlSession.getMapper(ReservationMapper.class).update(reservation);
            MonitorService.update(sqlSession, Data.Origin.XML_JSON, NameId.Type.Reservation, reservation);
            sqlSession.commit();
        }
        result = new Response("Canceled " + reservation.getName(), message, xsl);
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(message + "\n" + x.getMessage());
        result = new Response("Error " + x.getMessage(), message, xsl);
    } finally {
        sqlSession.close();
    }
    LOG.debug(result);
    MonitorService.monitor(message, timestamp);
    return result;
}