I am reading data from StoredProcedureCusrsorReader. The data is for multiple accounts and having one-to-many relationships. So for each account I am getting the output as for each account I have multiple order. I don't want to process the order until I detect a change in the Account number
**AccountNo PurchaseOrder
1 AB1
1 AB2
-1 AB3
-2 CD1
-2 CD2
-2 CD3**
In the processor I want to aggregate the records with same account no using code like this
#Component
#StepScope
public class CashFlowProcessor implements ItemProcessor<BankTransaction, MonthlyCashFlow> {
private LocalDate lastDate = null;
private List<BankTransaction> monthlyGroup = new ArrayList<>();
#Override
public MonthlyCashFlow process(BankTransaction transaction) {
if (lastDate == null || isSameMonth(transaction.getDate())) {
monthlyGroup.add(transaction);
lastDate = transaction.getDate();
return null;
}
//this means that a new month has started
MonthlyCashFlow cashFlow = aggregate(); // aggregate the collected flows
lastDate = transaction.getDate(); //set the new month
monthlyGroup = new ArrayList<>(); // create a new list
monthlyGroup.add(transaction);
return cashFlow;
}
}
But the class level variable lastDate is always null for each record getting processed. Pleas suggest.
Related
I have dataset (from JSON source) with cumulative values. It looks like this:
Could I extract from this dataset delta from last hour or last day (for example, count from 0 since last midnight?)
What you are asking about falls squarely in the realm of process data as it usually comes from control systems aka process controls systems. There may be DCS (Distributed Control Systems) or SCADA out in the field that act as a focal point on receiving data. And there may be a process historian or time-series database for accessing that data, if not on an enterprise level at least not within the process controls network.
Much of the engineering associated with process data has been established for many, many decades. For my examples, I did not want to write too many custom classes so I will use some everyday .NET objects. However, I am adhering to 2 such well-regarded principles about process data:
All times will be in UTC. Usually one does not show the UtcTime until the very last moment when displaying to a local user.
Process Data acknowledges the Quality of a value. While there can be dozens of bad states associated with such Quality, I will use a simple binary approach of good or bad. Since I use double, a value is good as long as it is not double.NaN.
That said, I assume you have a class that looks similar to:
public class JsonDto
{
public string Id { get; set; }
public DateTime Time { get; set; }
public double value { get; set; }
}
Granted your class name may be different, but the main thing is this class holds an individual instance of process data. When you read a JSON file, it will produce a List<jsonDto> instance.
You will need lots of methods to transform the data to something a wee bit more useable in order to get to where the rubber finally meets the road: producing hourly differences. But that requires producing hourly values because there is no guarantee that your recorded values occur exactly on each hour.
ProcessData Class - lots of methods
public static class ProcessData
{
public enum CalculationTimeBasis { Auto = 0, EarliestTime, MostRecentTime, MidpointTime }
public static Dictionary<string, SortedList<DateTime, double>> GetTagTimedValuesMap(IEnumerable<JsonDto> jsonDto)
{
var map = new Dictionary<string, SortedList<DateTime, double>>();
var tagnames = jsonDto.Select(x => x.Id).Distinct().OrderBy(x => x);
foreach (var tagname in tagnames)
{
map.Add(tagname, new SortedList<DateTime, double>());
}
var orderedValues = jsonDto.OrderBy(x => x.Id).ThenBy(x => x.Time.ToUtcTime());
foreach (var item in orderedValues)
{
map[item.Id].Add(item.Time.ToUtcTime(), item.value);
}
return map;
}
public static DateTimeKind UnspecifiedDefaultsTo { get; set; } = DateTimeKind.Utc;
public static DateTime ToUtcTime(this DateTime value)
{
// Unlike ToUniversalTime(), this method assumes any Unspecified Kind may be Utc or Local.
if (value.Kind == DateTimeKind.Unspecified)
{
if (UnspecifiedDefaultsTo == DateTimeKind.Utc)
{
value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
}
else if (UnspecifiedDefaultsTo == DateTimeKind.Local)
{
value = DateTime.SpecifyKind(value, DateTimeKind.Local);
}
}
return value.ToUniversalTime();
}
private static DateTime TruncateTime(this DateTime value, TimeSpan interval) => new DateTime(TruncateTicks(value.Ticks, interval.Ticks)).ToUtcTime();
private static long TruncateTicks(long ticks, long interval) => (interval == 0) ? ticks : (ticks / interval) * interval;
public static SortedList<DateTime, double> GetInterpolatedValues(SortedList<DateTime, double> recordedValues, TimeSpan interval)
{
if (interval <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException($"{nameof(interval)} TimeSpan must be greater than zero");
}
var interpolatedValues = new SortedList<DateTime, double>();
var previous = recordedValues.First();
var intervalTimestamp = previous.Key.TruncateTime(interval);
foreach (var current in recordedValues)
{
if (current.Key == intervalTimestamp)
{
// It's easy when the current recorded value aligns perfectly on the desired interval.
interpolatedValues.Add(current.Key, current.Value);
intervalTimestamp += interval;
}
else if (current.Key > intervalTimestamp)
{
// We do not exactly align at the desired time, so we must interpolate
// between the "last recorded data" BEFORE the desired time (i.e. previous)
// and the "first recorded data" AFTER the desired time (i.e. current).
var interpolatedValue = GetInterpolatedValue(intervalTimestamp, previous, current);
interpolatedValues.Add(interpolatedValue.Key, interpolatedValue.Value);
intervalTimestamp += interval;
}
previous = current;
}
return interpolatedValues;
}
private static KeyValuePair<DateTime, double> GetInterpolatedValue(DateTime interpolatedTime, KeyValuePair<DateTime, double> left, KeyValuePair<DateTime, double> right)
{
if (!double.IsNaN(left.Value) && !double.IsNaN(right.Value))
{
double totalDuration = (right.Key - left.Key).TotalSeconds;
if (Math.Abs(totalDuration) > double.Epsilon)
{
double partialDuration = (interpolatedTime - left.Key).TotalSeconds;
double factor = partialDuration / totalDuration;
double calculation = left.Value + ((right.Value - left.Value) * factor);
return new KeyValuePair<DateTime, double>(interpolatedTime, calculation);
}
}
return new KeyValuePair<DateTime, double>(interpolatedTime, double.NaN);
}
public static SortedList<DateTime, double> GetDeltaValues(SortedList<DateTime, double> values, CalculationTimeBasis timeBasis = CalculationTimeBasis.Auto)
{
const CalculationTimeBasis autoDefaultsTo = CalculationTimeBasis.MostRecentTime;
var deltas = new SortedList<DateTime, double>(capacity: values.Count);
var previous = values.First();
foreach (var current in values.Skip(1))
{
var time = GetTimeForBasis(timeBasis, previous.Key, current.Key, autoDefaultsTo);
var diff = current.Value - previous.Value;
deltas.Add(time, diff);
previous = current;
}
return deltas;
}
private static DateTime GetTimeForBasis(CalculationTimeBasis timeBasis, DateTime earliestTime, DateTime mostRecentTime, CalculationTimeBasis autoDefaultsTo)
{
if (timeBasis == CalculationTimeBasis.Auto)
{
// Different (future) methods calling this may require different interpretations of Auto.
// Thus we leave it to the calling method to declare what Auto means to it.
timeBasis = autoDefaultsTo;
}
switch (timeBasis)
{
case CalculationTimeBasis.EarliestTime:
return earliestTime;
case CalculationTimeBasis.MidpointTime:
return new DateTime((earliestTime.Ticks + mostRecentTime.Ticks) / 2L).ToUtcTime();
case CalculationTimeBasis.MostRecentTime:
return mostRecentTime;
case CalculationTimeBasis.Auto:
default:
return earliestTime;
}
}
}
Usage Example
var inputValues = new List<JsonDto>();
// TODO: Magically populate inputValues
var tagDataMap = ProcessData.GetTagTimedValuesMap(inputValues);
foreach (var item in tagDataMap)
{
// Following would generate hourly differences for the one Tag Id (item.Key)
// by first generating hourly data, and then finding the delta of that.
var hourlyValues = ProcessData.GetInterpolatedValues(item.Value, TimeSpan.FromHours(1));
// Consider the difference between Hour(1) and Hour(2).
// That is, 2 input values will create 1 output value.
// Now you must decide which of the 2 input times you use for the 1 output time.
// This is what I call the CalculationTimeBasis.
// The time basis used will be Auto, which defaults to the most recent for this particular method, e.g. Hour(2)
var deltaValues = ProcessData.GetDeltaValues(hourlyValues);
// Same as above except we explicitly state we want the most recent time, e.g. also Hour(2)
var deltaValues2 = ProcessData.GetDeltaValues(hourlyValues, ProcessData.CalculationTimeBasis.MostRecentTime);
// Here the calculated differences are the same except the now
// timestamp now reflects the earliest time, e.g. Hour(1)
var deltaValues3 = ProcessData.GetDeltaValues(hourlyValues, ProcessData.CalculationTimeBasis.EarliestTime);
I am trying to do geofence monitoring/analytics using KSQLDB. I want to get a message whenever a vehicle ENTERS/LEAVES a geofence. Taking inspiration from the [https://github.com/gschmutz/various-demos/tree/master/kafka-geofencing] I have created a UDF named as GEOFENCE, below is the code for the same.
Below is my query to perform join on geofence stream and live vehicle position stream
CREATE stream join_live_pos_geofence_status_1 AS SELECT lp1.vehicleid,
lp1.lat,
lp1.lon,
s1p.geofencecoordinates,
Geofence(lp1.lat, lp1.lon, 'POLYGON(('+s1p.geofencecoordinates+'))') AS geofence_status
FROM live_position_1 LP1
LEFT JOIN stream_1_processed S1P within 72 hours
ON kmdlp1.clusterid = kmds1p.clusterid emit changes;
I am taking into account all the geofences created in last 3 days.
I have created another query to use the geofence status from previous query to calculate whether the vehicle is ENTERING/LEAVING geofence.
CREATE stream join_geofence_monitoring_1 AS SELECT *,
Geofence(jlpgs1.lat, jlpgs1.lon, 'POLYGON(('+jlpgs1.geofencecoordinates+'))', jlpgs1.geofence_status) geofence_monitoring_status
FROM join_live_pos_geofence_status_1 JLPGS1 emit changes;
The above query give me the output as 'INSIDE', 'INSIDE' for geofence_status and geofence_monitoring_status columns, respectively or the output is 'OUTSIDE', 'OUTSIDE' for geofence_status and geofence_monitoring_status columns, respectively. I know I am not taking into account the time aspect, like these 2 queries should never be executed at same time say 't0' but I am not able to think the correct way of doing this.
public class Geofence
{
private static final String OUTSIDE = "OUTSIDE";
private static final String INSIDE = "INSIDE";
private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
private static WKTReader wktReader = new WKTReader(geometryFactory);
#Udf(description = "Returns whether a coordinate lies within a polygon or not")
public static String geofence(final double latitude, final double longitude, String geometryWKT) {
boolean status = false;
String result = "";
Polygon polygon = null;
try {
polygon = (Polygon) wktReader.read(geometryWKT);
// However, an important point to note is that the longitude is the X value
// and the latitude the Y value. So we say "lat/long",
// but JTS will expect it in the order "long/lat".
Coordinate coord = new Coordinate(longitude, latitude);
Point point = geometryFactory.createPoint(coord);
status = point.within(polygon);
if(status)
{
result = INSIDE;
}
else
{
result = OUTSIDE;
}
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
#Udf(description = "Returns whether a coordinate moved in or out of a polygon")
public static String geofence(final double latitude, final double longitude, String geometryWKT, final String statusBefore) {
String status = geofence(latitude, longitude, geometryWKT);
if (statusBefore.equals("INSIDE") && status.equals("OUTSIDE")) {
//status = "LEAVING";
return "LEAVING";
} else if (statusBefore.equals("OUTSIDE") && status.equals("INSIDE")) {
//status = "ENTERING";
return "ENTERING";
}
return status;
}
}
My question is how can I calculate correctly that a vehicle is ENTERING/LEAVING a geofence? Is it even possible to do with KSQLDB?
Would it be correct to say that the join_live_pos_geofence_status_1 stream can have rows that go from INSIDE -> OUTSIDE and then from OUTSIDE -> INSIDE for some key value?
And what you're wanting to do is to output LEAVING and ENTERING events for these transitions?
You can likely do what you want using a custom UDAF. Custom UDAFs take and input and calculate an output, via some intermediate state. For example, an AVG udaf would take some numbers as input, its intermediate state would be the number of inputs and the sum of inputs, and the output would be count/sum.
In your case, the input would be the current state, e.g. either INSIDE or OUTSIDE. The UDAF would need to store the last two states in its intermediate state, and then the output state can be calculated from this. E.g.
Input Intermediate Output
INSIDE INSIDE <only single in intermediate - your choice what you output>
INSIDE INSIDE,INSIDE no-change
OUTSIDE INSIDE,OUTSIDE LEAVING
OUTSIDE OUTSIDE,OUTSIDE no-change
INSIDE OUTSIDE,INSIDE ENTERING
You'll need to decide what to output when there is only a single entry in the intermediate state, i.e. the first time a key is seen.
You can then filter the output to remove any rows that have no-change.
You may also need to set cache.max.bytes.buffering to zero to stop any results being conflated.
UPDATE: suggested code.
Not tested, but something like the following code may do what you want:
#UdafDescription(name = "my_geofence", description = "Computes the geofence status.")
public final class GoeFenceUdaf {
private static final String STATUS_1 = "STATUS_1";
private static final String STATUS_2 = "STATUS_2";
#UdafFactory(description = "Computes the geofence status.",
aggregateSchema = "STRUCT<" + STATUS_1 + " STRING, " + STATUS_2 + " STRING>")
public static Udaf<String, Struct, String> calcGeoFenceStatus() {
final Schema STRUCT_SCHEMA = SchemaBuilder.struct().optional()
.field(STATUS_1, Schema.OPTIONAL_STRING_SCHEMA)
.field(STATUS_2, Schema.OPTIONAL_STRING_SCHEMA)
.build();
return new Udaf<String, Struct, String>() {
#Override
public Struct initialize() {
return new Struct(STRUCT_SCHEMA);
}
#Override
public Struct aggregate(
final String newValue,
final Struct aggregate
) {
if (newValue == null) {
return aggregate;
}
if (aggregate.getString(STATUS_1) == null) {
// First status for this key:
return aggregate
.put(STATUS_1, newValue);
}
final String lastStatus = aggregate.getString(STATUS_2);
if (lastStatus == null) {
// Second status for this key:
return aggregate
.put(STATUS_2, newValue);
}
// Third and subsequent status for this key:
return aggregate
.put(STATUS_1, lastStatus)
.put(STATUS_2, newValue);
}
#Override
public String map(final Struct aggregate) {
final String previousStatus = aggregate.getString(STATUS_1);
final String currentStatus = aggregate.getString(STATUS_2);
if (currentStatus == null) {
// Only have single status, i.e. first status for this key
// What to do? Probably want to do:
return previousStatus.equalsIgnoreCase("OUTSIDE")
? "LEAVING"
: "ENTERING";
}
// Two statuses ...
if (currentStatus.equals(previousStatus)) {
return "NO CHANGE";
}
return previousStatus.equalsIgnoreCase("OUTSIDE")
? "ENTERING"
: "LEAVING";
}
#Override
public Struct merge(final Struct agg1, final Struct agg2) {
throw new RuntimeException("Function does not support session windows");
}
};
}
}
I am learning JPA, I found out that we have some functions which is already present in Jparepository like save,saveAll,find, findAll etc. but there is nothing like update,
I come across one scenario where I need to update the table, if the value is already present otherwise I need to insert the record in table.
I created
#Repository
public interface ProductInfoRepository
extends JpaRepository<ProductInfoTable, String>
{
Optional<ProductInfoTable> findByProductName(String productname);
}
public class ProductServiceImpl
implements ProductService
{
#Autowired
private ProductInfoRepository productRepository;
#Override
public ResponseMessage saveProductDetail(ProductInfo productInfo)
{
Optional<ProductInfoTable> productInfoinTable =
productRepository.findByProductName(productInfo.getProductName());
ProductInfoTable productInfoDetail;
Integer quantity = productInfo.getQuantity();
if (productInfoinTable.isPresent())
{
quantity += productInfoinTable.get().getQuantity();
}
productInfoDetail =
new ProductInfoTable(productInfo.getProductName(), quantity + productInfo.getQuantity(),
productInfo.getImage());
productRepository.save(productInfoDetail);
return new ResponseMessage("product saved successfully");
}
}
as you can see, I can save the record if the record is new, but when I am trying to save the record which is already present in table it is giving me error related to primarykeyviolation which is obvious. I checked somewhat, we can do the update by creating the entitymanager object or jpa query but what if I dont want to use both of them. is there any other way we can do so ?
update I also added the instance of EntityManager and trying to merge the code
#Override
public ResponseMessage saveProductDetail(ProductInfo productInfo)
{
Optional<ProductInfoTable> productInfoinTable =
productRepository.findByProductName(productInfo.getProductName());
ProductInfoTable productInfoDetail;
Integer price = productInfo.getPrice();
if (productInfoinTable.isPresent())
{
price = productInfoinTable.get().getPrice();
}
productInfoDetail =
new ProductInfoTable(productInfo.getProductName(), price, productInfo.getImage());
em.merge(productInfoDetail);
return new ResponseMessage("product saved successfully");
but no error, no execution of update statements in log, any possible reasons for that ?
}
I suspect you need code like this to solve the problem
public ResponseMessage saveProductDetail(ProductInfo productInfo)
{
Optional<ProductInfoTable> productInfoinTable =
productRepository.findByProductName(productInfo.getProductName());
final ProductInfoTable productInfoDetail;
if (productInfoinTable.isPresent()) {
// to edit
productInfoDetail = productInfoinTable.get();
Integer quantity = productInfoDetail.getQuantity() + productInfo.getQuantity();
productInfoDetail.setQuantity(quantity);
} else {
// to create new
productInfoDetail = new ProductInfoTable(productInfo.getProductName(),
productInfo.getQuantity(), productInfo.getImage());
}
productRepository.save(productInfoDetail);
return new ResponseMessage("product saved successfully");
}
I need help with understanding of the win_ext window in Esper (CEP). I'm wondering why older (first 2) events still popup on the update-method even though they have been "expired"
public class MyCepTest {
public static void main(String...args) throws Exception{
System.out.println("starting");
MyCepTest ceptest = new MyCepTest();
ceptest.execute();
System.out.println("end");
}
public void execute() throws Exception{
Configuration config = new Configuration();
config.addEventType(MyPojo.class);
EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(config);
EPAdministrator admin = epService.getEPAdministrator();
EPStatement x1 = admin.createEPL(win);
EPStatement x2 = admin.createEPL(win2);
x1.setSubscriber(this);
x2.setSubscriber(this);
EPRuntime runtime = epService.getEPRuntime();
ArrayList<MyPojo> staffToSendToCep = new ArrayList<MyPojo>();
staffToSendToCep.add(new MyPojo(1, new Date(1490615719497L)));
staffToSendToCep.add(new MyPojo(2, new Date(1490615929497L)));
for(MyPojo pojo : staffToSendToCep){
runtime.sendEvent(pojo);
}
Thread.sleep(500);
System.out.println("round 2...");//why two first Pojos are still found? Shouldn't ext_timed(pojoTime.time, 300 seconds) rule them out?
staffToSendToCep.add(new MyPojo(3, new Date(1490616949497L)));
for(MyPojo pojo : staffToSendToCep){
runtime.sendEvent(pojo);
}
}
public void update(Map<String,Object> map){
System.out.println(map);
}
public static String win = "create window fiveMinuteStuff.win:ext_timed(pojoTime.time, 300 seconds)(pojoId int, pojoTime java.util.Date)";
public static String win2 = "insert into fiveMinuteStuff select pojoId,pojoTime from MyPojo";
}
class MyPojo{
int pojoId;
Date pojoTime;
MyPojo(int pojoId, Date date){
this.pojoId = pojoId;
this.pojoTime = date;
}
public int getPojoId(){
return pojoId;
}
public Date getPojoTime(){
return pojoTime;
}
public String toString(){
return pojoId+"#"+pojoTime;
}
}
I've been puzzled with this for a while and help would be greatly appreciated
See the processing model in docs. http://espertech.com/esper/release-6.0.1/esper-reference/html/processingmodel.html
All incoming insert-stream events are delivered to listeners and subscribers. regardless of your window. A window, if one is in the query at all, defines the subsets of events to consider and therefore defines what gets aggregated, pattern-matched or is available for iteration. Try "select * from MyPojo" for reference. My advice to read up on external time, see http://espertech.com/esper/release-6.0.1/esper-reference/html/api.html#api-controlling-time
Usually when you want "external time window" you want event time to drive engine time.
I am passing all test coverage in salesforce apex in sandbox but in deploying to live getting the
error in subject, i dont know how to handle it.
my test class code is:
#isTest(SeeAllData=true)
public class myLeadTest{
public static testMethod void testMyController5() {
Account acc= new Account(name='test');
acc.Order__c='wee';
insert acc;
Campaign camp = new Campaign(Name='test');
insert camp;
Company__c cm= new Company__c();
cm.Company_Id__c=12;
cm.Name='234';
cm.Account__c=acc.id;
insert cm;
Lead l= new Lead();
l.Campaign__c=camp.Id;
l.LastName='test';
l.Company='cmpny';
l.Company_Id__c=cm.Company_Id__c;
l.Email='test#yahoo.com';
l.Status='Closed - Converted';
l.Order__c=acc.Order__c;
// l.Auto_Convert__c=true;
// l.IsConverted=false;
//l.ConvertedAccountId=acc.Id;
Lead[] l2= new Lead[]{l};
insert l2;
Opportunity op= new Opportunity ();
op.StageName='Won (Agency)';
op.Name='test';
op.CloseDate=Date.valueOf('2015-04-28');
op.AccountId=acc.id;
op.LeadSource='web';
op.StageName= 'Won (Agency)';
op.CampaignId=camp.id;
op.TrialStart__c=Date.valueOf('2012-04-28');
insert op;
Contact cnt= new Contact();
cnt.LastName='test';
cnt.AccountId=acc.id;
cnt.ASEO_Company_Id__c=12;
cnt.Email=l.Email;
cnt.Company__c=cm.id;
insert cnt;
///////////////
/* Lead l5= new Lead();
l5.Campaign__c=camp.Id;
l5.LastName='test';
l5.Company='cmpny';
l5.Company_Id__c=12;
l5.Email='test#yahoo.com';
l5.Status='Closed-Converted';
l5.isConverted=false;
//l.ConvertedAccountId=acc.Id;
insert l5; */
Contact cnt1= new Contact();
cnt1.LastName='test';
cnt1.AccountId=acc.id;
cnt1.ASEO_Company_Id__c=12;
cnt1.Email=l.Email;
insert cnt1;
Database.LeadConvert leadConvert = new Database.LeadConvert();
leadConvert.setLeadId(l2[0].Id);
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
leadConvert.setConvertedStatus(convertStatus.MasterLabel);
leadConvert.setOpportunityName(op.Name);
leadConvert.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult lcResult = Database.ConvertLead(leadConvert);
// MyLead.addCampaign(l2[0], camp.Name);
// MyLead.updateOpportunity(l2[0], lcResult);
// MyLead.updateContact( l2[0], lcResult, cm) ;
// myLead.addCampaignMembers(l2);
}
}
and class code which i call in trigger :
public class MyLead {
public static void convertLead(Lead[] leads) {
Database.LeadConvert leadConvert = new Database.LeadConvert();
for (Lead lead :leads) {
if (!(lead.IsConverted)) {
// Check if an account exists with email. Attach Contact and Account, convert Lead.
Contact[] myContacts = [SELECT Id, AccountId FROM Contact WHERE Email = :lead.Email Limit 1];
if (myContacts.size() == 1) {
System.debug('Existing Contact');
MyLead.attachExistingConvert(lead, myContacts[0]);
}
else {
System.debug('No existing contact');
if (lead.Auto_Convert__c) {
MyLead.addCampaign(lead, lead.Campaign__c);
leadConvert.setLeadId(lead.Id);
leadConvert.setConvertedStatus('Closed - Converted');
Database.LeadConvertResult lcResult = Database.ConvertLead(leadConvert);
// Populate the newly created records with extra data.
MyLead.updateOpportunity(lead, lcResult);
Company__c myCompany = [SELECT Id FROM Company__c WHERE Company_Id__c = :lead.Company_Id__c];
MyLead.updateContact(lead, lcResult, myCompany);
// Must update the Company before Account otherwise the Account lookup will fail.
MyLead.updateCompany(lead, lcResult, myCompany);
MyLead.updateAccount(lead, lcResult, myCompany);
}
}
}
}
}
// Attaches Lead to Contact and Account if matched by Email, converts Lead and creates opportunity if it doesn't exist.
public static void attachExistingConvert(Lead lead, Contact contact) {
MyLead.addCampaign(lead, lead.Campaign__c);
Database.leadConvert leadConvert = new Database.LeadConvert();
leadConvert.setLeadId(lead.Id);
leadConvert.setConvertedStatus('Closed - Converted');
leadConvert.setContactId(contact.Id);
leadConvert.setAccountId(contact.AccountId);
leadConvert.setSendNotificationEmail(True);
// Do not create an opportunity if any exist.
Opportunity[] myOpportunity = [SELECT Id FROM Opportunity WHERE AccountId = :contact.AccountId];
if (myOpportunity.size() > 0) {
leadConvert.setDoNotCreateOpportunity(True);
}
leadConvert.setLeadId(lead.Id);
Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
// If we created an opportunity, update it with extra stuff.
if (leadConvert.isDoNotCreateOpportunity() == False) {
MyLead.updateOpportunity(lead, leadConvertResult);
}
}
// Updates the newly created Opportunity with extra data
public static void updateOpportunity(Lead lead, Database.LeadConvertResult lcResult) {
Opportunity myOpportunity = [SELECT Id, StageName FROM Opportunity WHERE Id = :lcResult.opportunityId];
myOpportunity.Name = 'Online Upgrade';
myOpportunity.TrialStart__c = lead.CreatedDate.date();
//myOpportunity.Amount = lead.Monthly_Revenue__c;
myOpportunity.Amount = lead.Amount__c;
myOpportunity.Type = 'New Business';
myOpportunity.LeadSource = 'Website';
myOpportunity.Order__c = lead.Order__c;
DateTime dt = System.now();
Date d = dt.date();
myOpportunity.CloseDate = d;
myOpportunity.StageName = lead.Agency__c ? 'Won (Agency)' : 'Won (End User)';
myOpportunity.Probability = 100;
update myOpportunity;
}
// Updates the newly created Account with extra data
public static void updateAccount(Lead lead, Database.LeadConvertResult lcResult, Company__c myCompany) {
Account myAccount = [SELECT Id FROM Account WHERE Id = :lcResult.accountId];
myAccount.Type = 'Customer';
myAccount.ASEO_Company_Id__c = lead.Company_Id__c;
myAccount.Company__c = myCompany.Id; // Setting the company will cause the company account lookup to fail
myAccount.Order__c = lead.Order__c;
update myAccount;
}
// Updates the newly created Contact with extra data
public static void updateContact(Lead lead, Database.LeadConvertResult lcResult, Company__c myCompany) {
Contact myContact = [SELECT Id FROM Contact WHERE Id = :lcResult.contactId];
myContact.ASEO_Company_Id__c = lead.Company_Id__c;
myContact.Company__c = myCompany.Id;
update myContact;
}
// Updates the Company with extra data
public static void updateCompany(Lead lead, Database.LeadConvertResult lcResult, Company__c myCompany) {
myCompany.Account__c = lcResult.accountId;
update myCompany;
}
// Adds a lead to a campaign
public static void addCampaign(Lead lead, String campaign) {
Campaign[] myCampaigns = [Select Id FROM Campaign WHERE Name = :campaign LIMIT 1];
if (myCampaigns.size() == 1) {
CampaignMember campaignMember = new CampaignMember (campaignId=myCampaigns[0].Id, leadId=lead.Id);
insert campaignMember;
}
}
// Create campaign members from leads. Campaign comes from lead.Campaign__c.
public static void addCampaignMembers(Lead[] leads) {
for (Lead lead :leads) {
// Might want to query Campaigns table instead.
//Set<String> campaigns = new Set<String>();
//campaigns.add('Freemium');
Campaign[] myCampaigns = [SELECT Id FROM Campaign WHERE Name = :lead.Campaign__c LIMIT 1];
//if (campaigns.contains(lead.Campaign__c)) {
if (myCampaigns.size() == 1) {
MyLead.addCampaign(lead, lead.Campaign__c);
}
}
}
}
and my lead trigger is:
trigger LeadTrigger on Lead (after insert, after update) {
Lead[] leads = Trigger.new;
//MyLead.createOpportunity(leads);
MyLead.convertLead(leads);
Please any one can help me, i tries 25 times but in deploying to production give me error in the given subject, or any one give code coverage of this class, thank you in advance
Looks like the issue is based on a soql query that is not included in your code. You try to query a field called "Address" but this field doesn't exist. Address is still in beta...
Try to adjust your query and use the fields City, Street, Country and PostalCode.
You can learn more about sObject fields there: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_lead.htm
Just in case someone else get to this question with this problem.
As Christian said, the code is trying to access the "Address" field from Lead in a SOQL query. Starting from API version 30, the compound fields are available to use in queries (http://www.salesforce.com/us/developer/docs/api/Content/compound_fields_address.htm).
So, if you run into this issue with a query in your code, check for the API version of the class and the visualforce page. Both must be 30 or greater.