Search in sources :

Example 11 with Answer

use of life.genny.qwanda.Answer in project rulesservice by genny-project.

the class QRules method processAddressAnswers.

public List<Answer> processAddressAnswers(QDataAnswerMessage m) {
    // Put this in to stop bad User null error.... TODO
    if (getUser() == null) {
        return new ArrayList<Answer>();
    }
    try {
        List<Answer> resultAnswers = new ArrayList<Answer>();
        Answer[] newAnswers = new Answer[50];
        Answer[] answers = m.getItems();
        List<Answer> newAnswerList = new ArrayList<Answer>();
        for (Answer answer : answers) {
            String targetCode = answer.getTargetCode();
            answer.setSourceCode(answer.getTargetCode());
            String attributeCode = answer.getAttributeCode();
            String value = answer.getValue();
            println("value ::" + value + "attribute code ::" + attributeCode);
            /* if this answer is actually an address another rule will be triggered */
            if (attributeCode.contains("ADDRESS_JSON")) {
                JsonObject addressDataJson = new JsonObject(value);
                println("The Address Json is  :: " + addressDataJson);
                Map<String, String> availableKeys = new HashMap<String, String>();
                availableKeys.put("full_address", "FULL");
                availableKeys.put("street_address", "ADDRESS1");
                availableKeys.put("suburb", "SUBURB");
                availableKeys.put("state", "STATE");
                availableKeys.put("postal_code", "POSTCODE");
                availableKeys.put("country", "COUNTRY");
                int i = 0;
                for (Map.Entry<String, String> entry : availableKeys.entrySet()) {
                    String key = entry.getKey();
                    String valueEntry = entry.getValue();
                    if (addressDataJson.containsKey(key)) {
                        String newAttributeCode = attributeCode.replace("JSON", valueEntry);
                        answer.setAttributeCode(newAttributeCode);
                        answer.setValue(addressDataJson.getString(key));
                        String jsonAnswer = RulesUtils.toJson(answer);
                        Answer answerObj = RulesUtils.fromJson(jsonAnswer, Answer.class);
                        newAnswerList.add(answerObj);
                    }
                }
                /* Store latitude */
                String newAttCode = attributeCode.replace("JSON", "LATITUDE");
                answer.setAttributeCode(newAttCode);
                Double latitude = addressDataJson.getDouble("latitude");
                println(" The latitude value after conversion is  :: " + latitude);
                if (latitude != null) {
                    answer.setValue(Double.toString(latitude));
                    String jsonAnswer = RulesUtils.toJson(answer);
                    Answer answerObj = RulesUtils.fromJson(jsonAnswer, Answer.class);
                    println("The answer object for latitude attribute is  :: " + answerObj.toString());
                    newAnswerList.add(answerObj);
                // println("The answer object for latitude attribute added to Answer array ");
                }
                /* Store longitude */
                newAttCode = attributeCode.replace("JSON", "LONGITUDE");
                answer.setAttributeCode(newAttCode);
                Double longitude = addressDataJson.getDouble("longitude");
                println(" The longitude value after conversion is  :: " + longitude);
                if (longitude != null) {
                    answer.setValue(Double.toString(longitude));
                    String jsonAnswer = RulesUtils.toJson(answer);
                    Answer answerObj = RulesUtils.fromJson(jsonAnswer, Answer.class);
                    newAnswerList.add(answerObj);
                    i++;
                }
                // ArrayList<Answer> list = new ArrayList<Answer>();
                // for (Answer s : newAnswers) {
                // if (s != null)
                // list.add(s);
                // }
                println("---------------------------");
                // println(list);
                // newAnswers = list.toArray(new Answer[list.size()]);
                // println(newAnswers);
                /* set new answers */
                // m.setItems(newAnswers);
                // String json = RulesUtils.toJson(m);
                // println("updated answer json string ::" + json);
                /* send new answers to api */
                /*
					 * QwandaUtils.apiPostEntity(qwandaServiceUrl + "/qwanda/answers/bulk2", json,
					 * getToken());
					 */
                // for (Answer an : newAnswers) {
                // publishData(an);
                resultAnswers.addAll(newAnswerList);
            // }
            }
        }
        return resultAnswers;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ArrayList<Answer>();
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BadDataException(life.genny.qwanda.exception.BadDataException) ParseException(org.json.simple.parser.ParseException) Answer(life.genny.qwanda.Answer) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 12 with Answer

use of life.genny.qwanda.Answer in project rulesservice by genny-project.

the class QRules method saveJob.

public void saveJob(BaseEntity job) {
    String jobCode = job.getCode();
    /*
		 * We create a new attribute "PRI_TOTAL_DISTANCE" for this BEG. TODO: should be
		 * triggered in another rule
		 */
    Double pickupLatitude = job.getValue("PRI_PICKUP_ADDRESS_LATITUDE", 0.0);
    Double pickupLongitude = job.getValue("PRI_PICKUP_ADDRESS_LONGITUDE", 0.0);
    Double deliveryLatitude = job.getValue("PRI_DROPOFF_ADDRESS_LATITUDE", 0.0);
    Double deliveryLongitude = job.getValue("PRI_DROPOFF_ADDRESS_LONGITUDE", 0.0);
    /* Add author to the load */
    List<Answer> answers = new ArrayList<Answer>();
    answers.add(new Answer(getUser().getCode(), jobCode, "PRI_POSITION_LATITUDE", pickupLatitude + ""));
    answers.add(new Answer(getUser().getCode(), jobCode, "PRI_POSITION_LONGITUDE", pickupLongitude + ""));
    Double totalDistance = GPSUtils.getDistance(pickupLatitude, pickupLongitude, deliveryLatitude, deliveryLongitude);
    if (totalDistance > 0) {
        Answer totalDistanceAnswer = new Answer(jobCode, jobCode, "PRI_TOTAL_DISTANCE_M", totalDistance + "");
        answers.add(totalDistanceAnswer);
    }
    /* Adding Offer Count to 0 */
    Answer offerCountAns = new Answer(getUser().getCode(), jobCode, "PRI_OFFER_COUNT", "0");
    /* Publish Answer */
    answers.add(offerCountAns);
    /* set Status of the job */
    answers.add(new Answer(getUser().getCode(), jobCode, "STA_STATUS", Status.NEEDS_NO_ACTION.value()));
    // Setting color to green for new jobs for both driver and owner
    /*
		 * answers.add(new Answer(getUser().getCode(), jobCode, "STA_" +
		 * getUser().getCode(), Status.NEEDS_NO_ACTION.value()));
		 */
    BaseEntity updatedJob = this.getBaseEntityByCode(job.getCode());
    Long jobId = updatedJob.getId();
    answers.add(new Answer(getUser().getCode(), jobCode, "PRI_JOB_ID", jobId + ""));
    saveAnswers(answers);
    /* Determine the recipient code */
    String[] recipientCodes = VertxUtils.getSubscribers(realm(), "GRP_NEW_ITEMS");
    println("Recipients for Job/Load " + Arrays.toString(recipientCodes));
    /*
		 * Send newly created job with its attributes to all drivers so that it exists
		 * before link change
		 */
    BaseEntity newJobDetails = getBaseEntityByCode(jobCode);
    println("The newly submitted Job details     ::     " + newJobDetails.toString());
    publishData(newJobDetails, recipientCodes);
    /* publishing to Owner */
    publishBE(newJobDetails);
    /* Moving the BEG */
    Link link = new Link("GRP_DRAFTS", jobCode, "LNK_CORE");
    try {
        String output = QwandaUtils.apiPostEntity(getQwandaServiceUrl() + "/qwanda/baseentitys/move/GRP_NEW_ITEMS", JsonUtils.toJson(link), getToken());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /* Get the sourceCode(Company code) for this User */
    BaseEntity company = getParent(getUser().getCode(), "LNK_STAFF");
    /* link newly created Job to GRP_LOADS */
    BaseEntity load = getChildren(jobCode, "LNK_BEG", "LOAD");
    String loadCode = load.getCode();
    Link newLoadLinkToLoadList = QwandaUtils.createLink("GRP_LOADS", loadCode, "LNK_LOAD", company.getCode(), (double) 1, getToken());
    println("The load has been added to the GRP_LOADS ");
    /* SEND LOAD BE */
    /* Try sending different types of links to the frontend to get it to display */
    publishBaseEntityByCode(loadCode, jobCode, "LNK_BEG", recipientCodes);
    /* publishing to Owner */
    publishBE(getBaseEntityByCode(loadCode));
    QEventLinkChangeMessage msgLnkBegLoad = new QEventLinkChangeMessage(new Link(jobCode, load.getCode(), "LNK_BEG"), null, getToken());
    publishData(msgLnkBegLoad, recipientCodes);
    publishBaseEntityByCode(jobCode, "GRP_NEW_ITEMS", "LNK_CORE", recipientCodes);
    /* publishing to Owner */
    publishBE(getBaseEntityByCode(jobCode));
    if (!newJobDetails.getValue("PRI_JOB_IS_SUBMITTED", false)) {
        /* Sending Messages */
        println("new job");
        HashMap<String, String> contextMap = new HashMap<String, String>();
        contextMap.put("JOB", jobCode);
        contextMap.put("OWNER", getUser().getCode());
        println("The String Array is ::" + Arrays.toString(recipientCodes));
        /* Sending toast message to owner frontend */
        sendMessage("", recipientCodes, contextMap, "MSG_CH40_NEW_JOB_POSTED", "TOAST");
        /* Sending message to BEG OWNER */
        sendMessage("", recipientCodes, contextMap, "MSG_CH40_NEW_JOB_POSTED", "EMAIL");
    }
}
Also used : QEventLinkChangeMessage(life.genny.qwanda.message.QEventLinkChangeMessage) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BaseEntity(life.genny.qwanda.entity.BaseEntity) IOException(java.io.IOException) Answer(life.genny.qwanda.Answer) Link(life.genny.qwanda.Link)

Example 13 with Answer

use of life.genny.qwanda.Answer in project rulesservice by genny-project.

the class QRules method acceptJob.

public void acceptJob(QEventBtnClickMessage m) {
    /* Get beg.getCode(), username, userCode, userFullName */
    // Get Baseentity once so we don't need to keep
    BaseEntity beg = getBaseEntityByCode(m.getItemCode());
    // fetching...
    println("beg.getCode()  ::   " + beg.getCode());
    String userCode = getUser().getCode();
    println("usercode   ::   " + getUser().getCode());
    String userName = getAsString("preferred_username");
    println("username   ::   " + userName);
    String userFullName = getFullName(getUser());
    println("user fullName   ::   " + userFullName);
    String linkCode = "LNK_BEG";
    String linkOffer = "OFFER";
    String linkQuoter = "QUOTER";
    String linkOwner = "OWNER";
    String linkCreator = "CREATOR";
    Optional<String> optOwnerCode = beg.getValue("PRI_AUTHOR");
    String ownerCode = null;
    if (optOwnerCode.isPresent()) {
        ownerCode = optOwnerCode.get();
    } else {
        ownerCode = QwandaUtils.getSourceOrTargetForGroupLink("GRP_NEW_ITEMS", linkCode, beg.getCode(), linkOwner, false, getToken());
    }
    /* get BEG PRICEs */
    println("BEG Prices   ::   ");
    Money begPrice = beg.getLoopValue("PRI_PRICE", Money.of(0.00, "AUD"));
    Money ownerPriceExcGST = beg.getLoopValue("PRI_OWNER_PRICE_EXC_GST", Money.of(0.00, "AUD"));
    Money ownerPriceIncGST = beg.getLoopValue("PRI_OWNER_PRICE_INC_GST", Money.of(0.00, "AUD"));
    Money driverPriceExcGST = beg.getLoopValue("PRI_DRIVER_PRICE_EXC_GST", Money.of(0.00, "AUD"));
    Money driverPriceIncGST = beg.getLoopValue("PRI_DRIVER_PRICE_INC_GST", Money.of(0.00, "AUD"));
    Money feePriceExcGST = beg.getLoopValue("PRI_FEE_EXC_GST", Money.of(0.00, "AUD"));
    Money feePriceIncGST = beg.getLoopValue("PRI_FEE_INC_GST", Money.of(0.00, "AUD"));
    /* Create Offer BE */
    BaseEntity offer = createBaseEntityByCode(getUser().getCode(), "OFR", "Offer");
    println("OFFER CODE   ::   " + offer.getCode());
    RulesUtils.ruleLogger("OFFER Base Entity", offer);
    /* Send beg to driver and owner should see it as part of beg link */
    VertxUtils.subscribe(realm(), offer, getUser().getCode());
    VertxUtils.subscribe(realm(), offer, ownerCode);
    /* Save attributes for OFFER as answer */
    List<Answer> answerList = new ArrayList<Answer>();
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_PRICE", JsonUtils.toJson(begPrice)));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_OWNER_PRICE_EXC_GST", JsonUtils.toJson(ownerPriceExcGST)));
    /*
		 * answerList .add(new Answer(getUser(), offer, "PRI_OFFER_OWNER_PRICE_INC_GST",
		 * JsonUtils.toJson(ownerPriceIncGST)));
		 */
    Answer owIncGST = new Answer(getUser(), offer, "PRI_OFFER_OWNER_PRICE_INC_GST", JsonUtils.toJson(ownerPriceIncGST));
    owIncGST.setChangeEvent(false);
    answerList.add(owIncGST);
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_DRIVER_PRICE_EXC_GST", JsonUtils.toJson(driverPriceExcGST)));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_DRIVER_PRICE_INC_GST", JsonUtils.toJson(driverPriceIncGST)));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_FEE_EXC_GST", JsonUtils.toJson(feePriceExcGST)));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_FEE_INC_GST", JsonUtils.toJson(feePriceIncGST)));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_CODE", offer.getCode()));
    answerList.add(new Answer(getUser(), offer, "PRI_QUOTER_CODE", getUser().getCode()));
    answerList.add(new Answer(getUser(), offer, "PRI_QUOTER_USERNAME", userName));
    answerList.add(new Answer(getUser(), offer, "PRI_QUOTER_FULLNAME", userFullName));
    answerList.add(new Answer(getUser(), offer, "PRI_BEG_CODE", beg.getCode()));
    answerList.add(new Answer(getUser(), offer, "PRI_NEXT_ACTION", linkOwner));
    answerList.add(new Answer(getUser(), offer, "PRI_OFFER_DATE", getCurrentLocalDateTime()));
    saveAnswers(answerList);
    /* Update the number of offers for BEG */
    Integer offerCount = beg.getLoopValue("PRI_OFFER_COUNT", 0);
    offerCount = offerCount + 1;
    println("Offer Count is   ::   " + offerCount);
    saveAnswer(new Answer(beg.getCode(), beg.getCode(), "PRI_OFFER_COUNT", offerCount.toString()));
    /* Determine the recipient code */
    String[] recipients = VertxUtils.getSubscribers(realm(), beg.getCode());
    println("BEG subscribers   ::   " + Arrays.toString(recipients));
    /* link BEG and OFFER BE || OFFER */
    createLink(beg.getCode(), offer.getCode(), linkCode, linkOffer, 1.0);
    /* link BEG and QUOTER BE || QUOTER */
    createLink(beg.getCode(), getUser().getCode(), linkCode, linkQuoter, 1.0);
    /* link OFFER and QUOTER BE || CREATOR */
    createLink(offer.getCode(), getUser().getCode(), "LNK_OFR", linkCreator, 1.0);
    /* set Status of the job */
    /* get Owner of the job */
    BaseEntity owner = getChildren(beg.getCode(), "LNK_BEG", "OWNER");
    // updateBaseEntityAttribute(getUser().getCode(), beg.getCode(), "STA_STATUS",
    // "#FFA500");
    updateBaseEntityAttribute(getUser().getCode(), beg.getCode(), "STA_" + getUser().getCode(), Status.NEEDS_ACTION.value());
    updateBaseEntityAttribute(getUser().getCode(), beg.getCode(), "STA_" + owner.getCode(), Status.NEEDS_ACTION.value());
    /* SEND (OFFER, QUOTER, BEG) BaseEntitys to recipients */
    String[] offerRecipients = VertxUtils.getSubscribers(realm(), offer.getCode());
    println("OFFER subscribers   ::   " + Arrays.toString(offerRecipients));
    publishBaseEntityByCode(offer.getCode(), beg.getCode(), "LNK_BEG", offerRecipients);
    publishBaseEntityByCode(getUser().getCode(), beg.getCode(), "LNK_BEG", offerRecipients);
    publishBaseEntityByCode(beg.getCode(), "GRP_NEW_ITEMS", "LNK_CORE", offerRecipients);
    /* Messages */
    /* OWNER config */
    HashMap<String, String> contextMap = new HashMap<String, String>();
    contextMap.put("QUOTER", getUser().getCode());
    contextMap.put("JOB", beg.getCode());
    contextMap.put("OFFER", offer.getCode());
    RulesUtils.println("owner code ::" + ownerCode);
    String[] recipientArr = { ownerCode };
    /* Sending toast message to owner frontend */
    sendMessage("", recipientArr, contextMap, "MSG_CH40_ACCEPT_QUOTE_OWNER", "TOAST");
    /* QUOTER config */
    HashMap<String, String> contextMapForDriver = new HashMap<String, String>();
    contextMapForDriver.put("JOB", beg.getCode());
    contextMapForDriver.put("OWNER", ownerCode);
    contextMapForDriver.put("OFFER", offer.getCode());
    contextMapForDriver.put("QUOTER", getUser().getCode());
    String[] recipientArrForDriver = { getUser().getCode() };
    /* Sending toast message to driver frontend */
    sendMessage("", recipientArrForDriver, contextMapForDriver, "MSG_CH40_ACCEPT_QUOTE_DRIVER", "TOAST");
}
Also used : AttributeInteger(life.genny.qwanda.attribute.AttributeInteger) AttributeMoney(life.genny.qwanda.attribute.AttributeMoney) Money(org.javamoney.moneta.Money) Answer(life.genny.qwanda.Answer) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) BaseEntity(life.genny.qwanda.entity.BaseEntity) ArrayList(java.util.ArrayList)

Example 14 with Answer

use of life.genny.qwanda.Answer in project rulesservice by genny-project.

the class QRules method saveAnswers.

/**
 * @param answers
 */
public void saveAnswers(List<Answer> answers, final boolean changeEvent) {
    if (!changeEvent) {
        for (Answer answer : answers) {
            answer.setChangeEvent(false);
        }
    }
    Answer[] items = new Answer[answers.size()];
    items = answers.toArray(items);
    QDataAnswerMessage msg = new QDataAnswerMessage(items);
    updateCachedBaseEntity(answers);
    String jsonAnswer = RulesUtils.toJson(msg);
    jsonAnswer.replace("\\\"", "\"");
    try {
        QwandaUtils.apiPostEntity(getQwandaServiceUrl() + "/qwanda/answers/bulk2", jsonAnswer, token);
    } catch (IOException e) {
        log.error("Socket error trying to post answer");
    }
}
Also used : Answer(life.genny.qwanda.Answer) QDataAnswerMessage(life.genny.qwanda.message.QDataAnswerMessage) IOException(java.io.IOException)

Example 15 with Answer

use of life.genny.qwanda.Answer in project rulesservice by genny-project.

the class QRules method updateGPS.

public void updateGPS(QDataGPSMessage m) {
    GPS driverPosition = m.getItems()[0];
    Double driverLatitude = driverPosition.getLatitude();
    Double driverLongitude = driverPosition.getLongitude();
    if (driverLatitude != null && driverLongitude != null) {
        try {
            List<BaseEntity> jobsInTransit = getBaseEntitysByAttributeAndValue("STT_IN_TRANSIT", getUser().getCode());
            if (!jobsInTransit.isEmpty()) {
                println("###### GPS: for user " + getUser().getCode() + ":" + m);
                println(jobsInTransit.toString());
            }
            for (BaseEntity be : jobsInTransit) {
                Double deliveryLatitude = be.getValue("PRI_DROPOFF_ADDRESS_LATITUDE", 0.0);
                Double deliveryLongitude = be.getValue("PRI_DROPOFF_ADDRESS_LONGITUDE", 0.0);
                Double totalDistance = be.getValue("PRI_TOTAL_DISTANCE_M", 0.0);
                /* Call Google Maps API to know how far the driver is */
                Double distance = GPSUtils.getDistance(driverLatitude, driverLongitude, deliveryLatitude, deliveryLongitude);
                Double percentage = 100.0 * (totalDistance - distance) / (totalDistance);
                percentage = percentage < 0 ? 0 : percentage;
                /* update position of the beg */
                List<Answer> answers = new ArrayList<Answer>();
                answers.add(new Answer(be.getCode(), be.getCode(), "PRI_PROGRESS", percentage.toString()));
                answers.add(new Answer(be.getCode(), be.getCode(), "PRI_POSITION_LATITUDE", driverLatitude + ""));
                answers.add(new Answer(be.getCode(), be.getCode(), "PRI_POSITION_LONGITUDE", driverLongitude + ""));
                saveAnswers(answers);
            }
        } catch (NumberFormatException e) {
            println("GPS Error " + m);
        }
    }
}
Also used : Answer(life.genny.qwanda.Answer) BaseEntity(life.genny.qwanda.entity.BaseEntity) ArrayList(java.util.ArrayList) GPS(life.genny.qwanda.GPS)

Aggregations

Answer (life.genny.qwanda.Answer)16 BaseEntity (life.genny.qwanda.entity.BaseEntity)8 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)5 LinkedHashMap (java.util.LinkedHashMap)5 IOException (java.io.IOException)4 JsonObject (io.vertx.core.json.JsonObject)2 AttributeMoney (life.genny.qwanda.attribute.AttributeMoney)2 EntityAttribute (life.genny.qwanda.attribute.EntityAttribute)2 BadDataException (life.genny.qwanda.exception.BadDataException)2 QDataAnswerMessage (life.genny.qwanda.message.QDataAnswerMessage)2 Money (org.javamoney.moneta.Money)2 JsonArray (io.vertx.core.json.JsonArray)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 ExecutionException (java.util.concurrent.ExecutionException)1 GPS (life.genny.qwanda.GPS)1 Link (life.genny.qwanda.Link)1 AttributeBoolean (life.genny.qwanda.attribute.AttributeBoolean)1