Commit b4a90ea3 authored by RobertZieschang's avatar RobertZieschang
Browse files

initial commit

parents
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.be1eye.cco</groupId>
<artifactId>blogpluginpart3</artifactId>
<name>blogpluginpart3</name>
<version>0.0.1-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<build>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>com.sap:scco:*</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer>
<manifestEntries>
<PluginName>${project.name}</PluginName>
<CashdeskPOSPlugin>${sap.scco.pluginClass}</CashdeskPOSPlugin>
<CashDeskVersions>${sap.scco.POSVersions}</CashDeskVersions>
<Version>${project.version}</Version>
<Specification-Title>${project.name}</Specification-Title>
<Specification-Version>${project.artifact.selectedVersion.majorVersion}.${project.artifact.selectedVersion.minorVersion}</Specification-Version>
<Specification-Vendor>${project.organization.name}</Specification-Vendor>
<Implementation-Title>${project.name}</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
<Implementation-Vendor-Id>${project.groupId}</Implementation-Vendor-Id>
<Implementation-Vendor>${project.organization.name}</Implementation-Vendor>
<Implementation-URL>${project.url}</Implementation-URL>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<sap.scco.pluginClass>com.be1eye.cco.blogpluginpart3.App</sap.scco.pluginClass>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sap.scco.POSVersions>n/a, 2.0 FP06</sap.scco.POSVersions>
</properties>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.be1eye.cco</groupId>
<artifactId>blogpluginpart3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>blogpluginpart3</name>
<url>http://maven.apache.org</url>
<properties>
<sap.scco.pluginClass>com.be1eye.cco.blogpluginpart3.App</sap.scco.pluginClass>
<sap.scco.POSVersions>n/a, 2.0 FP06</sap.scco.POSVersions>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>10.0.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>10.0.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.0.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>com.sap:scco:*</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<PluginName>${project.name}</PluginName>
<CashdeskPOSPlugin>${sap.scco.pluginClass}</CashdeskPOSPlugin>
<CashDeskVersions>${sap.scco.POSVersions}</CashDeskVersions>
<Version>${project.version}</Version>
<Specification-Title>${project.name}</Specification-Title>
<Specification-Version>${project.artifact.selectedVersion.majorVersion}.${project.artifact.selectedVersion.minorVersion}</Specification-Version>
<Specification-Vendor> ${project.organization.name}</Specification-Vendor>
<Implementation-Title>${project.name}</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
<Implementation-Vendor-Id>${project.groupId}</Implementation-Vendor-Id>
<Implementation-Vendor>${project.organization.name}</Implementation-Vendor>
<Implementation-URL>${project.url}</Implementation-URL>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.be1eye.cco.blogpluginpart3;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.util.StringUtils;
import com.be1eye.cco.blogpluginpart3.dao.LoyaltyFactorDao;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorDto;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorRequestDto;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorResponseDto;
import com.be1eye.cco.blogpluginpart3.rest.LoyaltyFactorRestInterface;
import com.sap.scco.ap.configuration.ConfigurationHelper;
import com.sap.scco.ap.plugin.BasePlugin;
import com.sap.scco.ap.plugin.annotation.PluginAt;
import com.sap.scco.ap.plugin.annotation.PluginAt.POSITION;
import com.sap.scco.ap.plugin.annotation.Schedulable;
import com.sap.scco.ap.pos.dao.CDBSession;
import com.sap.scco.ap.pos.dao.CDBSessionFactory;
import com.sap.scco.ap.pos.dao.IReceiptManager;
import com.sap.scco.ap.pos.dao.SynchStatusManager;
import com.sap.scco.ap.pos.entity.BusinessPartnerEntity;
import com.sap.scco.ap.pos.i14y.util.context.I14YContext;
import com.sap.scco.ap.pos.job.PluginJob;
import com.sap.scco.ap.pos.service.LoyaltyPosService;
import com.sap.scco.ap.pos.service.impl.LoyaltyPosServiceImpl;
import com.sap.scco.ap.pos.util.TriggerParameter;
import com.sap.scco.util.logging.Logger;
import feign.Feign;
import feign.auth.BasicAuthRequestInterceptor;
import feign.httpclient.ApacheHttpClient;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
/**
* @author RobertZieschang zieschang@be1eye.de
*
*/
public class App extends BasePlugin {
private static final Logger logger = Logger.getLogger(App.class);
private LoyaltyFactorDao loyaltyFactorDao;
private LoyaltyFactorRestInterface restInterface;
private String sysId;
@Override
public String getId() {
return "pluginpartthree";
}
@Override
public String getName() {
return "CCO Plugin Part 3";
}
@Override
public String getVersion() {
return getClass().getPackage().getImplementationVersion();
}
@Override
public void startup() {
// setting up the local user-defined-table
loyaltyFactorDao = new LoyaltyFactorDao();
loyaltyFactorDao.setupTable();
// getting the host and port of our b1i server
String b1iHost = ConfigurationHelper.INSTANCE.getB1ServiceDestination().getHost();
int b1iPort = ConfigurationHelper.INSTANCE.getB1ServiceDestination().getPort();
// getting the http basic auth credentials
String httpBasicAuthUser = ConfigurationHelper.INSTANCE.getB1ServiceDestination().getUserName();
String httpBasicAuthPassword = new String(ConfigurationHelper.INSTANCE.getB1ServiceDestination().getPassword());
// use the string builder to create host + port
StringBuilder sb = new StringBuilder();
sb.append(b1iHost);
sb.append(":");
sb.append(b1iPort);
// get the sysid
this.sysId = ConfigurationHelper.INSTANCE.getB1IntegrationSettings().getSystemId();
// setting up our REST Interface
restInterface = Feign.builder()
.client(new ApacheHttpClient())
.encoder(new JacksonEncoder())
.decoder(new JacksonDecoder())
.requestInterceptor(new BasicAuthRequestInterceptor(httpBasicAuthUser, httpBasicAuthPassword))
.target(LoyaltyFactorRestInterface.class, sb.toString());
CDBSession session = CDBSessionFactory.instance.createSession();
try {
LoyaltyPosService loyaltyPosService = new LoyaltyPosServiceImpl(session);
loyaltyPosService.registerPointCalculationLogic(new LoyaltyPointCalculation());
} catch (Exception e) {
logger.info(e.getMessage());
} finally {
session.closeDBSession();
}
super.startup();
}
@PluginAt(pluginClass = IReceiptManager.class, method ="setBusinessPartner", where = POSITION.AFTER)
public Object checkForLoyaltyFactor(Object proxy, Object[] args, Object ret, StackTraceElement caller) {
try {
BusinessPartnerEntity bp = (BusinessPartnerEntity) args[1];
LoyaltyFactorDto loyaltyFactorDto = this.loyaltyFactorDao.findOne(bp.getExternalId());
// If cardcode is empty, then it is not in the database...
if(StringUtils.isEmpty(loyaltyFactorDto.getCardCode())) {
LoyaltyFactorRequestDto request = new LoyaltyFactorRequestDto();
request.setSysId(this.sysId);
request.setCardCode(bp.getExternalId());
List<LoyaltyFactorResponseDto> response = restInterface.requestLoyaltyData(request);
if(!response.isEmpty()) {
this.loyaltyFactorDao.save(new LoyaltyFactorDto((String) response.get(0).getCardCode(), new BigDecimal(response.get(0).getULoyFac())));
}
}
} catch (Exception e) {
logger.info(e.getLocalizedMessage());
}
return ret;
}
@Schedulable("LoyaltyFactor Sync")
public void syncLoyaltyFactor(PluginJob job, TriggerParameter triggerParam, I14YContext context, Object[] params){
// We get the SyncStatusmanager from the database
CDBSession session = CDBSessionFactory.instance.createSession();
SynchStatusManager syncStatusManager = new SynchStatusManager(session);
Date lastUpdate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// We use the customerquerymax results for this. Maybe a plugin configuration would also be suitable.
Integer batchSize = ConfigurationHelper.INSTANCE.getB1IntegrationSettings().getCustomerQueryMaxResults();
// Is it a fully snyc?
if(triggerParam.isCleanSync())
{
try {
lastUpdate = dateFormat.parse("1970-01-01");
} catch (ParseException e) {
logger.severe(e.getLocalizedMessage());
}
}
else
{
lastUpdate = syncStatusManager.readLastUpdateOfObject(PluginJob.createObjectId(triggerParam.getPluginId(), triggerParam.getPluginMethodId()));
}
// Create the sync thread.
try {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new LoyaltyFactorSyncThread(this.restInterface, this.sysId, dateFormat.format(lastUpdate), batchSize));
} catch (Exception e) {
logger.info("Error while sync");
} finally {
session.closeDBSession();
}
}
}
package com.be1eye.cco.blogpluginpart3;
import java.math.BigDecimal;
import java.util.List;
import com.be1eye.cco.blogpluginpart3.dao.LoyaltyFactorDao;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorDto;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorRequestDto;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorResponseDto;
import com.be1eye.cco.blogpluginpart3.rest.LoyaltyFactorRestInterface;
public class LoyaltyFactorSyncThread implements Runnable {
private LoyaltyFactorRestInterface restClient;
private LoyaltyFactorDao loyaltyFactorDao;
private String sysId;
private String lastUpdate;
private Integer messageSize;
private String lastReturnedObjectId = "0";
public LoyaltyFactorSyncThread(LoyaltyFactorRestInterface restClient, String sysId, String lastUpdate, Integer messageSize) {
this.restClient = restClient;
this.sysId = sysId;
this.lastUpdate = lastUpdate;
this.messageSize = messageSize;
this.loyaltyFactorDao = new LoyaltyFactorDao();
}
public void run() {
boolean syncComplete = false;
do {
LoyaltyFactorRequestDto request = new LoyaltyFactorRequestDto();
request.setLastModifiedDate(this.lastUpdate);
request.setSysId(this.sysId);
request.setQueryHitsMaximumValue(this.messageSize.toString());
request.setLastReturnedObjectId(lastReturnedObjectId);
List<LoyaltyFactorResponseDto> response = this.restClient.requestLoyaltyData(request);
if(!response.isEmpty()) {
for(int i = 0; i < response.size(); i++) {
if(i == response.size() - 1) {
this.lastReturnedObjectId = response.get(i).getLastReturnedObjectId();
break;
}
this.loyaltyFactorDao.save(new LoyaltyFactorDto(response.get(i).getCardCode(), new BigDecimal(response.get(i).getULoyFac())));
}
} else {
syncComplete = true;
}
} while (!syncComplete);
}
}
package com.be1eye.cco.blogpluginpart3;
import java.math.BigDecimal;
import com.be1eye.cco.blogpluginpart3.dao.LoyaltyFactorDao;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorDto;
import com.sap.scco.ap.pos.entity.ReceiptEntity;
import com.sap.scco.ap.pos.entity.SalesItemEntity;
import com.sap.scco.ap.pos.loyalty.PointCalculationLogic;
public class LoyaltyPointCalculation implements PointCalculationLogic {
public BigDecimal calculatePointValue(ReceiptEntity receipt) {
BigDecimal overallAmount = BigDecimal.ZERO;
// get the overall amount for this receipt
for(SalesItemEntity item : receipt.getSalesItems()) {
overallAmount = overallAmount.add(item.getLoyaltyPoints());
}
// if a businesspartner is set, get the factor and multiply
if(receipt.getBusinessPartner() != null) {
LoyaltyFactorDao loyaltyFactorDao = new LoyaltyFactorDao();
// get the loyaltyFactor for this business partner
LoyaltyFactorDto loyaltyFactorDto = loyaltyFactorDao.findOne(receipt.getBusinessPartner().getExternalId());
overallAmount = overallAmount.multiply(loyaltyFactorDto.getLoyaltyFactor());
}
return overallAmount;
}
public BigDecimal calculatePointValue(SalesItemEntity salesItem) {
return SalesItemEntity.SalesItemTypeCode.MATERIAL.equals(salesItem.getTypeCode()) ? salesItem.getPaymentGrossAmount() : BigDecimal.ONE;
}
public void distributePointsToItems(ReceiptEntity arg0) {
}
public String getId() {
return "LoyaltyPointCalc";
}
}
package com.be1eye.cco.blogpluginpart3.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.be1eye.cco.blogpluginpart3.dto.LoyaltyFactorDto;
import com.sap.scco.ap.pos.dao.CDBSession;
import com.sap.scco.ap.pos.dao.CDBSessionFactory;
import com.sap.scco.util.logging.Logger;
/**
*
* @author RobertZieschang zieschang@be1eye.de
*
*/
public class LoyaltyFactorDao {
// use the logger from cco
private static final Logger logger = Logger.getLogger(LoyaltyFactorDao.class);
// name our table
private static final String TABLE_NAME = "B1E_LOYALTYFACTOR";
// create query
private static final String QUERY_CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ "CARDCODE varchar(20) not null PRIMARY KEY,"
+ "LOYALTYFACTOR decimal(18,4) not null)";
// query for adding
private static final String QUERY_INSERT_ROW = "INSERT INTO " + TABLE_NAME + " VALUES(?,?)";
// query for updating
private static final String QUERY_UPDATE_ROW = "UPDATE " + TABLE_NAME
+ " SET LOYALTYFACTOR = ?2 WHERE CARDCODE = ?1";
// query for find all
private static final String QUERY_FIND_ALL = "SELECT CARDCODE, LOYALTYFACTOR FROM " + TABLE_NAME;
// query for find one
private static final String QUERY_FIND_ONE = "SELECT CARDCODE, LOYALTYFACTOR FROM " + TABLE_NAME
+ " where CARDCODE = ?";
// query to drop one
private static final String QUERY_DROP_ONE = "DELETE FROM " + TABLE_NAME + " WHERE CARDCODE = ?";
/**
* Create the table if not existing
*/
public void setupTable() {
// lets open a session
CDBSession session = CDBSessionFactory.instance.createSession();
try {
session.beginTransaction();
EntityManager em = session.getEM();
Query q = em.createNativeQuery(QUERY_CREATE_TABLE);
q.executeUpdate();
session.commitTransaction();
logger.info("Created table " + TABLE_NAME);
} catch (Exception e) {
session.rollbackDBSession();
logger.info("Error or table " + TABLE_NAME + " already existing");
} finally {
session.closeDBSession();
}
}
/**
* Create or update an entry in our table.
*
* @param loyaltyFactor
*/
private void save(LoyaltyFactorDto loyaltyFactor, boolean isAlreadyInDB) {
CDBSession session = CDBSessionFactory.instance.createSession();
String query = isAlreadyInDB ? QUERY_UPDATE_ROW : QUERY_INSERT_ROW;
try {
session.beginTransaction();
EntityManager em = session.getEM();
Query q = em.createNativeQuery(query);
q.setParameter(1, loyaltyFactor.getCardCode());
q.setParameter(2, loyaltyFactor.getLoyaltyFactor().doubleValue());
q.executeUpdate();
session.commitTransaction();
} catch (Exception e) {
session.rollbackDBSession();
logger.info("Could not create LoyaltyFactor");
logger.info(e.getLocalizedMessage());
} finally {
session.closeDBSession();
}
}