Index: branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultService.groovy =================================================================== diff -u -r9405 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultService.groovy (.../RaceResultService.groovy) (revision 9405) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultService.groovy (.../RaceResultService.groovy) (revision 9526) @@ -2,13 +2,8 @@ import com.lemans.services.DynamicQueryExecutor import grails.transaction.Transactional - import java.time.Year -/** - * Created by vramisetti on 5/19/2016. - */ - @Transactional class RaceResultService extends RaceReportService { @@ -19,64 +14,63 @@ private static final List CLOB_TO_STRING_FIELDS = ['comment'] /** - * Find a RaceResult by id. - * - * @param criteria containing id and dealerCode - * - * @return RaceResult - */ + * Find a RaceResult by id. + * + * @param criteria containing id and dealerCode + * + * @return RaceResult + */ Map findRaceResultById(Map criteria) { DynamicQueryExecutor query = new DynamicQueryExecutor(criteria, dataSource) Map raceResult = query.executeOneFrom('vwRiderRaceResult', clauses(criteria)).results[0] raceResult ? clobToString(raceResult, CLOB_TO_STRING_FIELDS) : raceResult } /** - * Finds raceResults by dealerCode. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @param criteria containing dealerCode - * - * @return Map containing no. of totalRecords and List containing the raceResults - */ + * Finds raceResults by dealerCode. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @param criteria containing dealerCode + * + * @return Map containing no. of totalRecords and List containing the raceResults + */ Map findRaceResults(Map criteria) { criteria.sorting = criteria.sorting ?: 'raceDate+ASC' - DynamicQueryExecutor query = new DynamicQueryExecutor(criteria, dataSource) - Map data = query.executeFrom('vwRiderRaceResult', clauses(criteria)) + Map data = dqx(criteria).executeFrom('vwRiderRaceResult', clauses(criteria)) if (data.results) { data.results = clobToString(data.results, CLOB_TO_STRING_FIELDS) data } else { dealerService.findDealerByDealerCode(criteria) ? data : null } } /** - * Finds if there are races for a reportMonth. - * - * @param criteria containing dealerCode and reportDate - * - * @return boolean true or false - */ + * Finds if there are races for a reportMonth. + * + * @param criteria containing dealerCode and reportDate + * + * @return boolean true or false + */ boolean hasRaceResults(Map criteria) { DynamicQueryExecutor query = new DynamicQueryExecutor(criteria, dataSource) Map data = query.executeSelectFrom('SELECT count(*) AS totalRecords', 'FROM vwRiderRaceResult', clauses(criteria)) data.totalRecords > 0 } /** - * Finds raceResults by monthlyReport. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @param criteria containing dealerCode, riderMonthlyReportId - * - * @return Map containing no. of totalRecords and List containing the raceResults - */ + * Finds raceResults by monthlyReport. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @param criteria containing dealerCode, riderMonthlyReportId + * + * @return Map containing no. of totalRecords and List containing the raceResults + */ Map findRaceResultsByMonthlyReport(Map criteria) { Map monthlyReport = monthlyReportService.findMonthlyReportByYearMonth( - [dealerCode: criteria.dealerCode, reportYearMonth: criteria.reportYearMonth]) + [dealerCode: criteria.dealerCode, reportYearMonth: criteria.reportYearMonth]) if (monthlyReport) { findRaceResults(criteria + [reportDate: monthlyReport.raceMonth]) ?: [results: []] } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactManagerService.groovy =================================================================== diff -u -r9446 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactManagerService.groovy (.../DealerContactManagerService.groovy) (revision 9446) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactManagerService.groovy (.../DealerContactManagerService.groovy) (revision 9526) @@ -1,47 +1,46 @@ package com.lemans.dealer -import com.lemans.dealer.DealerContact import com.lemans.services.LemansManager import grails.transaction.Transactional @Transactional class DealerContactManagerService extends LemansManager { /** - * Saves an existing or newly created DealerContact. - * - * @param values Map of property values - * @param dealerCode owner - * @param id if not null updates the DealerContact, else inserts it - * @param username - * - * @return a DealerContact which may have errors or null - */ + * Saves an existing or newly created DealerContact. + * + * @param values Map of property values + * @param dealerCode owner + * @param id if not null updates the DealerContact, else inserts it + * @param username + * + * @return a DealerContact which may have errors or null + */ DealerContact saveDealerContact(Map values, String dealerCode, Integer id, String username) { DealerContact dealerContact = (id != null) ? find(dealerCode, id) : new DealerContact() if (dealerContact) { applyValuesToDomain(values, dealerContact) - dealerContact.dealerCode = dealerCode // TODO: must come after setting properties. is there a better way ??? - kk + dealerContact.dealerCode = dealerCode dealerContact.validate() saveOrDiscardDomain(dealerContact, username) } } - + /** - * Soft deletes a DealerContact. - * - * @param dealerCode of the owning Dealer - * @param id of the DealerContact - * @param username - * - * @return DealerContact which may have errors or null - */ + * Soft deletes a DealerContact. + * + * @param dealerCode of the owning Dealer + * @param id of the DealerContact + * @param username + * + * @return DealerContact which may have errors or null + */ DealerContact deleteDealerContact(String dealerCode, Integer id, String username) { DealerContact dealerContact = find(dealerCode, id) if (dealerContact) { softDelete(dealerContact, username) } dealerContact } - + private DealerContact find(String dealerCode, Integer id) { DealerContact.findByDealerCodeAndIdAndDateDeletedIsNull(dealerCode, id) } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultManagerService.groovy =================================================================== diff -u -r9501 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultManagerService.groovy (.../RaceResultManagerService.groovy) (revision 9501) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/rider/RaceResultManagerService.groovy (.../RaceResultManagerService.groovy) (revision 9526) @@ -1,16 +1,10 @@ package com.lemans.rider import com.lemans.dealer.Dealer -import com.lemans.rider.RaceResult import grails.transaction.Transactional -import org.springframework.transaction.interceptor.TransactionAspectSupport - import javax.mail.internet.MimeMessage import java.text.ParseException -/** - * Created by vramisetti on 5/19/2016. - */ @Transactional class RaceResultManagerService extends RaceReportManagerService { Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/CountryService.groovy =================================================================== diff -u -r9432 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/CountryService.groovy (.../CountryService.groovy) (revision 9432) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/CountryService.groovy (.../CountryService.groovy) (revision 9526) @@ -1,33 +1,30 @@ package com.lemans.dealer -import com.lemans.services.DynamicQueryExecutor import com.lemans.services.LemansService import grails.transaction.Transactional @Transactional class CountryService extends LemansService { - - //def dataSource - + /** - * Finds all the countries supported. - * - * @param criteria - * - * @return Map with List of countries - */ + * Finds all the countries supported. + * + * @param criteria + * + * @return Map with List of countries + */ Map findAllCountries(Map criteria) { dqx(criteria).executeFrom('dbo.country') } /** - * Finds all the countries for a specific domain. - * - * @param criteria with domain - * - * - * @return Map with List of countries - */ + * Finds all the countries for a specific domain. + * + * @param criteria with domain + * + * + * @return Map with List of countries + */ Map findAllCountriesByDomain(Map criteria) { dqx(criteria).executeFrom("dbo.fnCountryByDomain($criteria.dm)") } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportService.groovy =================================================================== diff -u -r9468 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportService.groovy (.../MonthlyReportService.groovy) (revision 9468) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportService.groovy (.../MonthlyReportService.groovy) (revision 9526) @@ -1,14 +1,8 @@ package com.lemans.rider -import com.lemans.services.DynamicQueryExecutor import grails.transaction.Transactional -import groovy.sql.Sql - import java.time.YearMonth -/** - * Created by vramisetti on 5/20/2016. - */ @Transactional class MonthlyReportService extends RaceReportService { @@ -23,47 +17,47 @@ } /** - * Find a MonthlyReport by Report's YearMonth. - * - * @param criteria containing YearMonth and dealerCode - * - * @return MonthlyReport - */ + * Find a MonthlyReport by Report's YearMonth. + * + * @param criteria containing YearMonth and dealerCode + * + * @return MonthlyReport + */ Map findMonthlyReportByYearMonth(Map criteria) { if (criteria.existsPhysically) { findMonthlyReportById(criteria) } else { criteria += [reportYearMonthValue: criteria.reportYearMonth.year] Map report = sql().rows( """ -SELECT * -FROM fnRiderMonthlyReportByYear($criteria.dealerCode, $criteria.reportYearMonthValue) x -WHERE MONTH(raceMonth) = $criteria.reportYearMonth.monthValue -""")[0] + SELECT * + FROM fnRiderMonthlyReportByYear($criteria.dealerCode, $criteria.reportYearMonthValue) x + WHERE MONTH(raceMonth) = $criteria.reportYearMonth.monthValue + """)[0] report ? clobToString(report, CLOB_TO_STRING_FIELDS) : report } } /** - * Find a MonthlyReport by id. - * - * @param criteria containing id and dealerCode - * - * @return MonthlyReport - */ + * Find a MonthlyReport by id. + * + * @param criteria containing id and dealerCode + * + * @return MonthlyReport + */ Map findMonthlyReportById(Map criteria) { Map report = dqx(criteria).executeOneFrom('vwRiderMonthlyReport', clauses(criteria)).results[0] report ? clobToString(report, CLOB_TO_STRING_FIELDS) : report } /** - * Finds monthlyReports by dealerCode. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @param criteria containing dealerCode - * - * @return Map containing no. of totalRecords and List containing the monthlyReports - */ + * Finds monthlyReports by dealerCode. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @param criteria containing dealerCode + * + * @return Map containing no. of totalRecords and List containing the monthlyReports + */ Map findMonthlyReports(Map criteria) { criteria.sorting = criteria.sorting ?: 'raceMonth+ASC' Map data = dqx(criteria).executeFrom("fnRiderMonthlyReportByYear('$criteria.dealerCode', $criteria.reportYear.year)") Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactService.groovy =================================================================== diff -u -r9446 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactService.groovy (.../DealerContactService.groovy) (revision 9446) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerContactService.groovy (.../DealerContactService.groovy) (revision 9526) @@ -1,47 +1,45 @@ package com.lemans.dealer -import com.lemans.services.DynamicQueryExecutor import com.lemans.services.LemansService import grails.transaction.Transactional @Transactional class DealerContactService extends LemansService { - + def dealerService + private final Map columnSets = [ + _contact: ['dealerContactId', 'firstName', 'lastName', 'title', 'homePhone', 'officePhone', 'cellPhone', 'dealerCode'] + ] /** - * Find a contact by id for the current user. - * - * @param criteria containing id, dm, appSecurityDealerCode, and appSecurityUserName - * - * @return contact - */ + * Find a contact by id for the current user. + * + * @param criteria containing id, dm, appSecurityDealerCode, and appSecurityUserName + * + * @return contact + */ Map findContactById(Map criteria) { dqx(criteria).executeOneFromAppSecurity('DealerContact', clauses(criteria)).results[0] } /** - * Finds contacts by dealerCode for the current user. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return Map containing no. of totalRecords and List containing the contacts - */ + * Finds contacts by dealerCode for the current user. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return Map containing no. of totalRecords and List containing the contacts + */ Map findContacts(criteria) { criteria.sorting = criteria.sorting ?: 'lastName+ASC' Map data = dqx(criteria).executeFromAppSecurity('DealerContact', clauses(criteria), columnSets) if (data.results) { data } else { dealerService.findDealerByDealerCode(criteria) ? data : null } } - private final Map columnSets = [ - _contact: ['dealerContactId', 'firstName', 'lastName', 'title', 'homePhone', 'officePhone', 'cellPhone', 'dealerCode'] - ] - private List clauses(criteria) { List clauses = [] if (criteria.dealerCode) { clauses << 'dealerCode = :dealerCode' } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileService.groovy =================================================================== diff -u -r9448 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileService.groovy (.../PayTraceCustomerProfileService.groovy) (revision 9448) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileService.groovy (.../PayTraceCustomerProfileService.groovy) (revision 9526) @@ -1,6 +1,5 @@ package com.lemans.paytrace -import com.lemans.services.DynamicQueryExecutor import com.lemans.services.LemansService import grails.converters.JSON import grails.transaction.Transactional @@ -11,7 +10,7 @@ @Transactional class PayTraceCustomerProfileService extends LemansService { - + static final String PAYTRACE_DB_MULTI_ACTION_QUERY = 'EXEC dbo.spPayTraceCustomerProfileAction ' static final String PAYTRACE_SP_ACTION_INACTIVATE = 'INACTIVATE' static final String PAYTRACE_SP_ACTION_CREATE = 'CREATE' @@ -25,40 +24,38 @@ static final String USER_PROFILE_TYPE = 'P' static final String SHARED_PROFILE_TYPE = 'S' - private static final String DOMAIN_METADATA_SQL = 'SELECT keyName, value FROM dbo.vwDomainMetadata WHERE domainId = ?' + private static final String DOMAIN_METADATA_SQL = 'SELECT keyName, value FROM dbo.vwDomainMetadata WHERE domainId = ?' - //def dataSource - def externalAPICallerService - + def eportalServiceHost - + def payTraceCustomerProfileManagerService - + /** - * Map payTrace fields to Dealer US fields. - */ + * Map payTrace fields to Dealer US fields. + */ static final Map PROFILE_CALL_BACK_FIELD_MAPPING = - [ 'ORDERID': 'customerId', - 'CUSTOMERID': 'customerId', - 'BNAME': 'customerName', - 'CARDTYPE': 'creditCardType', - 'EXPMNTH': 'expirationMonth', - 'EXPYR': 'expirationYear', - 'LAST4': 'creditCardLastFour', - 'TRANSACTIONID': 'transactionId' - ] + [ 'ORDERID': 'customerId', + 'CUSTOMERID': 'customerId', + 'BNAME': 'customerName', + 'CARDTYPE': 'creditCardType', + 'EXPMNTH': 'expirationMonth', + 'EXPYR': 'expirationYear', + 'LAST4': 'creditCardLastFour', + 'TRANSACTIONID': 'transactionId' + ] static final Map CREDIT_CARD_TYPE_MAPPING = - [ 'VISA': 'VS', - 'MASTERCARD': 'MC', - 'DISCOVER': 'DS', - 'AMERICAN EXPRESS': 'AX', - 'DINERS CLUB': 'DC', - 'DELTA': 'DE', - 'JCB': 'JC', - 'SOLO': 'SO' - ] + [ 'VISA': 'VS', + 'MASTERCARD': 'MC', + 'DISCOVER': 'DS', + 'AMERICAN EXPRESS': 'AX', + 'DINERS CLUB': 'DC', + 'DELTA': 'DE', + 'JCB': 'JC', + 'SOLO': 'SO' + ] List findSharedOrUserPaytraceProfile(Map criteria) { criteria.action = PAYTRACE_SP_ACTION_RETRIEVE @@ -69,132 +66,127 @@ criteria.action = PAYTRACE_SP_ACTION_RETRIEVE_ALL executePayTraceQuery(criteria) } + List refreshPaytraceProfileByCriteria(Map criteria) { criteria.action = PAYTRACE_SP_ACTION_REFRESH executePayTraceQuery(criteria) } private List executePayTraceQuery(criteria) { new Sql(dataSource).rows( - PAYTRACE_DB_MULTI_ACTION_QUERY + '@action = ?, @domainId=?, @dealerCode = ?, @userName = ?,' + - '@customerId = ?, @appSecurityUser = ?, @pageSize=?, @offset=?, @sortBy=?, @sortOrder=?', - [ - criteria.action, - criteria.dm.toInteger(), - criteria.dealerCode, - criteria.userName, - criteria.customerId , - criteria.auditUserName, - criteria.pageSize, - criteria.offset, - criteria.sort, - criteria.order - ]) + PAYTRACE_DB_MULTI_ACTION_QUERY + '@action = ?, @domainId=?, @dealerCode = ?, @userName = ?,' + + '@customerId = ?, @appSecurityUser = ?, @pageSize=?, @offset=?, @sortBy=?, @sortOrder=?', + [ + criteria.action, + criteria.dm.toInteger(), + criteria.dealerCode, + criteria.userName, + criteria.customerId , + criteria.auditUserName, + criteria.pageSize, + criteria.offset, + criteria.sort, + criteria.order + ]) } List verifyPayTraceProfile(Map criteria) { new Sql(dataSource).rows( - PAYTRACE_DB_MULTI_ACTION_QUERY + ' @action = ?, @domainId=?, @customerId = ?, @dealerCode = ?,' + - ' @userName = ?, @appSecurityUser = ?', - [PAYTRACE_SP_ACTION_VERIFY, criteria.dm, criteria.customerId, criteria.dealerCode, - criteria.userName, criteria.auditUserName]) + PAYTRACE_DB_MULTI_ACTION_QUERY + ' @action = ?, @domainId=?, @customerId = ?, @dealerCode = ?,' + + ' @userName = ?, @appSecurityUser = ?', + [PAYTRACE_SP_ACTION_VERIFY, criteria.dm, criteria.customerId, criteria.dealerCode, + criteria.userName, criteria.auditUserName] + ) } List createPayTraceProfile(Map criteria) { new Sql(dataSource).rows( - PAYTRACE_DB_MULTI_ACTION_QUERY + ' @action = ?, @domainId=?, @dealerCode = ?, ' + - '@userName = ?, @appSecurityUser = ?, @profileTypeCode = ?', - [PAYTRACE_SP_ACTION_CREATE, criteria.dm, criteria.dealerCode, criteria.userName, - criteria.auditUserName, getProfileTypeCode(criteria)]) + PAYTRACE_DB_MULTI_ACTION_QUERY + ' @action = ?, @domainId=?, @dealerCode = ?, ' + + '@userName = ?, @appSecurityUser = ?, @profileTypeCode = ?', + [PAYTRACE_SP_ACTION_CREATE, criteria.dm, criteria.dealerCode, criteria.userName, + criteria.auditUserName, getProfileTypeCode(criteria)]) } List updatePayTraceProfile(Map input, String loggedInUserName) { new Sql(dataSource).rows( - PAYTRACE_DB_MULTI_ACTION_QUERY + '@action = ?, @domainId=?, @customerId = ?, @customerName=? ,' + - ' @creditCardType = ?, @creditCardLastFour = ?, @expirationMonth = ?, ' + - '@expirationYear = ?, @appSecurityUser = ?, @transactionId = ?, @transactionVoidDate = ?,' + - '@callBackResponse = ?', - [ - PAYTRACE_SP_ACTION_UPDATE, - input.dm, - input.customerId, - input.customerName, - input.creditCardType, - input.creditCardLastFour, - input.expirationMonth, - input.expirationYear, - loggedInUserName, - input.transactionId, - input.transactionVoidDate, - input.callBackResponse - ]) + PAYTRACE_DB_MULTI_ACTION_QUERY + '@action = ?, @domainId=?, @customerId = ?, @customerName=? ,' + + ' @creditCardType = ?, @creditCardLastFour = ?, @expirationMonth = ?, ' + + '@expirationYear = ?, @appSecurityUser = ?, @transactionId = ?, @transactionVoidDate = ?,' + + '@callBackResponse = ?', + [ + PAYTRACE_SP_ACTION_UPDATE, + input.dm, + input.customerId, + input.customerName, + input.creditCardType, + input.creditCardLastFour, + input.expirationMonth, + input.expirationYear, + loggedInUserName, + input.transactionId, + input.transactionVoidDate, + input.callBackResponse + ]) } String getProfileTypeCode(Map criteria) { if (criteria.oneTimeProfileFlag) { return ONE_TIME_PROFILE_TYPE } else if (criteria.userName && !criteria.userName?.isEmpty()) { - return USER_PROFILE_TYPE + return USER_PROFILE_TYPE } SHARED_PROFILE_TYPE -} + } - boolean removePayTraceProfile(Map criteria) { boolean success = new Sql(dataSource).execute( - PAYTRACE_DB_MULTI_ACTION_QUERY + '@action =? , @domainId=?, @customerId = ?, ' + - '@dateInactivated = ?, @appSecurityUser = ?', - [PAYTRACE_SP_ACTION_INACTIVATE, criteria.dm, criteria.customerId, - criteria.currentDate, criteria.auditUserName]) + PAYTRACE_DB_MULTI_ACTION_QUERY + '@action =? , @domainId=?, @customerId = ?, ' + + '@dateInactivated = ?, @appSecurityUser = ?', + [PAYTRACE_SP_ACTION_INACTIVATE, criteria.dm, criteria.customerId, + criteria.currentDate, criteria.auditUserName]) success } - /** - * send paytrace callback request to mainframe - * @param payTraceProfileInput as Map - * @param action - * @param loggedInUserName - * @return - */ + * send paytrace callback request to mainframe + * @param payTraceProfileInput as Map + * @param action + * @param loggedInUserName + * @return + */ Map sendPaytraceProfileToMainframe(Map payTraceProfileInput, String action, String loggedInUserName) { if (payTraceProfileInput) { def payload = paytraceJsonInputBuilder(payTraceProfileInput, action) log.debug 'payload:' + payload - def url = "${eportalServiceHost}/PayTraceWebAPI/ep/PayTrace/payTraceDealerProfileRequest" log.debug 'mainframe url:' + url - HttpPost httpMethod = new HttpPost(url) httpMethod.setHeader('Content-Type', 'application/json') httpMethod.setEntity(new StringEntity(payload, 'UTF-8')) - String returnMessage = externalAPICallerService.callRestfulService(httpMethod) log.debug 'mainframe returnMessage:' + returnMessage def returnMessageJSON = JSON.parse(returnMessage) - boolean success = returnMessageJSON?.MessageClassName?.equalsIgnoreCase(PAYTRACE_EPORTAL_SUCCESS_RESPONSE_TEXT) - if (success) { return verifyProfileAndSetMainframeCreatedFlag(payTraceProfileInput, loggedInUserName) } } payTraceProfileInput } + /** - * sets the mainframeCreatedDate if reported to mainframe for the first time - * @param payTraceProfileInput - * @param loggedInUserName - * @return - */ + * sets the mainframeCreatedDate if reported to mainframe for the first time + * @param payTraceProfileInput + * @param loggedInUserName + * @return + */ Map verifyProfileAndSetMainframeCreatedFlag (Map payTraceProfileInput, loggedInUserName) { - Map profileMap = payTraceProfileInput as HashMap if (profileMap.mainframeCreateDate == null || !profileMap.mainframeCreated) { - payTraceCustomerProfileManagerService.savePayTraceCustomerProfile( - [mainframeCreateDate: new Date()], profileMap.customerId, loggedInUserName) - //on success full update reseting the flag as response. - payTraceProfileInput.mainframeCreated = 1 + payTraceCustomerProfileManagerService.savePayTraceCustomerProfile( + [mainframeCreateDate: new Date()], profileMap.customerId, loggedInUserName) + //on success full update reseting the flag as response. + payTraceProfileInput.mainframeCreated = 1 } payTraceProfileInput } @@ -219,11 +211,10 @@ } /** - * This method preprocess the text response send by pay trace call back call into a JSON object. - * This JSON object is compatible with PayTraceCustomerProfile table. - * examples CUSTOMERID~DUT008_001, CUSTOMERID~INSIDE_DUT008_001, CUSTOMERID~EMP_JKIRBY_001 - */ - + * This method preprocess the text response send by pay trace call back call into a JSON object. + * This JSON object is compatible with PayTraceCustomerProfile table. + * examples CUSTOMERID~DUT008_001, CUSTOMERID~INSIDE_DUT008_001, CUSTOMERID~EMP_JKIRBY_001 + */ Map processPayTraceCallbackInput(String paytraceCallbackInput) { paytraceCallbackInputToMap(paytraceCallbackInput) } @@ -235,39 +226,39 @@ def arguments = it.split('~') def columnName = PROFILE_CALL_BACK_FIELD_MAPPING.get(arguments[0]) if (columnName) { - paytraceInputMap.put(columnName, paytraceInputValue(columnName, arguments[1]?.toUpperCase())) - } - } - paytraceInputMap - } + paytraceInputMap.put(columnName, paytraceInputValue(columnName, arguments[1]?.toUpperCase())) + } + } + paytraceInputMap + } - private String paytraceInputValue(columnName, String argument) { - (columnName == 'creditCardType' && argument?.size() > 2) ? CREDIT_CARD_TYPE_MAPPING.get(argument) : argument - } + private String paytraceInputValue(columnName, String argument) { + (columnName == 'creditCardType' && argument?.size() > 2) ? CREDIT_CARD_TYPE_MAPPING.get(argument) : argument + } /** - * Finds metadata for a domain. - * - * @param domainId - * - * @return Map - */ + * Finds metadata for a domain. + * + * @param domainId + * + * @return Map + */ Map findMetadata(Integer domainId) { new Sql(dataSource).rows(DOMAIN_METADATA_SQL, [domainId]).collectEntries { [(it.keyName): it.value.characterStream.text] } } - /** - * Finds PayTrace logs by dealerCode. - * - * @param criteria containing dealerCode - * - * @return Map containing List of CorporateSamples - */ - Map payTraceLogs(Map criteria) { + /** + * Finds PayTrace logs by dealerCode. + * + * @param criteria containing dealerCode + * + * @return Map containing List of CorporateSamples + */ + Map payTraceLogs(Map criteria) { criteria.sorting = criteria.sorting ?: 'dateReserved+DESC' dqx(criteria).executeFrom("fnPaytraceCallBackResponse('${criteria.dealerCode}'," + - "${criteria.startDate ? "'$criteria.startDate'": null}, ${criteria.endDate ? "'$criteria.endDate'" : null})") + "${criteria.startDate ? "'$criteria.startDate'": null}, ${criteria.endDate ? "'$criteria.endDate'" : null})") } } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaManagerService.groovy =================================================================== diff -u -r9464 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaManagerService.groovy (.../MediaManagerService.groovy) (revision 9464) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaManagerService.groovy (.../MediaManagerService.groovy) (revision 9526) @@ -9,7 +9,6 @@ import org.apache.tika.metadata.Metadata import org.apache.tika.parser.AutoDetectParser import org.springframework.transaction.interceptor.TransactionAspectSupport - import javax.annotation.Resource import javax.mail.internet.InternetAddress import javax.mail.internet.MimeMessage @@ -34,13 +33,13 @@ static final String NO_REPLY_FROM = 'HelpDesk' /** - * Adds a media and transfers temporaryFile to actual location. - * - * @param criteria - * @param username - * - * @return the new media which may contain errors - */ + * Adds a media and transfers temporaryFile to actual location. + * + * @param criteria + * @param username + * + * @return the new media which may contain errors + */ Media addMedia(Map criteria, String username) { Map values = filterCriteria(criteria) Media media = new Media(values) @@ -60,13 +59,13 @@ private Map filterCriteria(Map criteria) { List auditProperties = [ - 'lastUpdatedBy', - 'lastUpdated', - 'createdBy', - 'dateCreated', - 'dateDeleted', - 'deletedBy', - ] + 'lastUpdatedBy', + 'lastUpdated', + 'createdBy', + 'dateCreated', + 'dateDeleted', + 'deletedBy', + ] auditProperties.each { if (criteria.containsKey(it)) { criteria.remove(it) @@ -110,7 +109,7 @@ } catch (IOException x) { rollback() media.errors.rejectValue('id', 'media.notSaved.message', - [combineFileName(values.fileName, values.extension)] as Object[], 'Media not saved') + [combineFileName(values.fileName, values.extension)] as Object[], 'Media not saved') } } @@ -125,14 +124,14 @@ } /** - * Updates values for a Media. - * - * @param criteria - * @param id - * @param username - * - * @return the media - */ + * Updates values for a Media. + * + * @param criteria + * @param id + * @param username + * + * @return the media + */ Media updateMedia(Map criteria, Integer id, String username) { Map values = filterCriteria(criteria) Media media = media(id, values.entityClass, values.entityId) @@ -146,13 +145,13 @@ } /** - * Soft deletes a media and deletes the content from the file system. - * - * @param values map containing id, entityClass and entityId - * @param username - * - * @return - */ + * Soft deletes a media and deletes the content from the file system. + * + * @param values map containing id, entityClass and entityId + * @param username + * + * @return + */ Media deleteMedia(Map values, String username) { Media media = Media.findByIdAndEntityClassAndEntityId(values.id, values.entityClass, values.entityId) if (media) { @@ -168,32 +167,36 @@ } /** - * Finds content of a media. - * - * @param media Media - * - * @return File with content - */ - File findMediaFile(Media media) { new File(mediaUploadPath(media) + "$media.id.$media.extension") } + * Finds content of a media. + * + * @param media Media + * + * @return File with content + */ + File findMediaFile(Media media) { + new File(mediaUploadPath(media) + "$media.id.$media.extension") + } /** - * Finds content of the temporary media. - * - * @param String tempId - * @param String fileName - * - * @return File with content - */ - File findTempMediaFile(String filename) { new File(filename) } + * Finds content of the temporary media. + * + * @param String tempId + * @param String fileName + * + * @return File with content + */ + File findTempMediaFile(String filename) { + new File(filename) + } /** - * Forwards media to given email. - * - * @param values containing entityClass, entityId and media idList - * @param toEmail - * - * @return a Map which might have errors - */ + * Forwards media to given email. + * + * @param values containing entityClass, entityId and media idList + * @param toEmail + * + * @return a Map which might have errors + */ Map sendMedia(Map values, String toEmail) { Map data = [errors: []] Map media = mediaService.findMedia(values) @@ -208,7 +211,7 @@ private List mediaCriteria(List media) { media.collect { - [description: it.description, finalMediaUrl: ("${assetServerHost}/${it.prefixUrl}${it.mediaUrl}${it.mediaId}.${it.extension}")] + [description: it.description, finalMediaUrl: ("${assetServerHost}/${it.prefixUrl}${it.mediaUrl}${it.mediaId}.${it.extension}")] } } @@ -224,7 +227,6 @@ Template template = engine.createTemplate(tmpl) Writable output = template.make(model) output.writeTo(writer) - MimeMessage mimeMessage = mailSender.createMimeMessage() model.to.each { mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(it)) } mimeMessage.setFrom(new InternetAddress(NO_REPLY_FROM)) @@ -237,30 +239,29 @@ this.class.classLoader.getResource("emails/${viewName}.tmpl").text } - private String tempFileName(String tempId, String extension) { temporaryDocumentPath + File.separator + tempId + '.' + extension } + private String tempFileName(String tempId, String extension) { + temporaryDocumentPath + File.separator + tempId + '.' + extension + } - /** - * Finds media. - * - * @param mediaId - * @param entityClass - * @param entityId - * - * @return Media - */ protected Media media(Integer mediaId, String entityClass, String entityId) { Media.findByIdAndEntityClassAndEntityIdAndDateDeletedIsNull(mediaId, entityClass, entityId) } - private rollback() { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() } + private rollback() { + TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() + } private MimeType mimeType(String extension, MediaType mediaType, String description) { MimeType.findByExtensionAndMediaTypeAndDescriptionAndDateDeletedIsNull(extension, mediaType, description) } - private MimeType mimeType(Integer id) { MimeType.findByIdAndDateDeletedIsNull(id) } + private MimeType mimeType(Integer id) { + MimeType.findByIdAndDateDeletedIsNull(id) + } - private MediaType mediaType(Integer mediaTypeId) { MediaType.findByIdAndDateDeletedIsNull(mediaTypeId) } + private MediaType mediaType(Integer mediaTypeId) { + MediaType.findByIdAndDateDeletedIsNull(mediaTypeId) + } private MediaCategory mediaCategory(Integer mediaCategoryId, MediaType mediaType) { MediaCategory.findByIdAndMediaTypeAndDateDeletedIsNull(mediaCategoryId, mediaType) Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerService.groovy =================================================================== diff -u -r9514 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerService.groovy (.../DealerService.groovy) (revision 9514) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerService.groovy (.../DealerService.groovy) (revision 9526) @@ -11,57 +11,76 @@ private static final List LOCAL_DATE_PROPERTIES = ['effectiveDate'] + private final String fromAppSecurityDealer = 'FROM dbo.fnAppSecurityDealer(:appSecurityDealerCode, :appSecurityUserName, :dm)\n' + + private final List baseColumnSet = ['dealerCode', 'dealerName'] + + private final Map columnSets = [ + _dealer: baseColumnSet, + _basic: baseColumnSet + ['legalDealerName', 'dbaDealerName'], + _list: baseColumnSet + ['purchaseLevelCode', 'primaryRep', 'primaryRepFullName', 'secondaryRep', + 'secondaryRepFullName', 'regionId', 'dealerStatus', 'TYSales'] + ] + + private static final String DEALER_STATUS_COUNT_SQL = + ''' + SELECT activeCount = sum(CASE WHEN dealerStatus <> 'I' THEN 1 ELSE 0 END) + ,inactiveCount = sum(CASE WHEN dealerStatus = 'I' THEN 1 ELSE 0 END) + ,totalCount = count(*) + ''' + + def dataSource_reporting - + /** - * Finds dealer purchaseHistory for specific parts. - * - * @param dealerCode - * @param parts List of parts - * - * @return totalRecords and List of results - */ + * Finds dealer purchaseHistory for specific parts. + * + * @param dealerCode + * @param parts List of parts + * + * @return totalRecords and List of results + */ Map findDealerPurchaseHistoryForParts(String dealerCode, List parts) { String xml = xmlOnRoot { - parts.each { - part(it) - } + parts.each { + part(it) } + } - List results = sql(dataSource_reporting).rows('EXEC dbo.spDealerPurchaseHistoryByXML @dealerCode = ?, @xml = ?', dealerCode, xml) - [totalRecords: results.size(), results: results] + List results = sql(dataSource_reporting).rows('EXEC dbo.spDealerPurchaseHistoryByXML @dealerCode = ?, @xml = ?', dealerCode, xml) + [totalRecords: results.size(), results: results] } - + /** - * Finds service provider by id. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Finds service provider by id. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findServiceProviderById(Map criteria) { Map data = dqx(criteria).executeOneFrom('dbo.vwServiceProvider', ['serviceProviderId = :id']) transformDatesToLocalDateStrings(data) } /** - * Finds Dealers by ServiceProvider. - * - * @param criteria containing serviceProvider - * - * @return List of dealers - */ + * Finds Dealers by ServiceProvider. + * + * @param criteria containing serviceProvider + * + * @return List of dealers + */ Map findDealersByServiceProvider(Map criteria) { dqx(criteria).executeFrom('dbo.vwDealerServiceProvider', ['serviceProviderId = :serviceProvider']) } - + /** - * Finds dealer service providers by dealer code or all service providers. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Finds dealer service providers by dealer code or all service providers. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findServiceProviders(Map criteria) { Map data List clauses = [] @@ -81,188 +100,171 @@ } transformDatesToLocalDates(data) } - + /** - * Finds Dealers by ServiceProvider. - * - * @param criteria containing serviceProvider - * - * @return List of dealers - */ + * Finds Dealers by ServiceProvider. + * + * @param criteria containing serviceProvider + * + * @return List of dealers + */ Map findDealersbyServiceProviders(Map criteria) { DynamicQueryExecutor query = new DynamicQueryExecutor(criteria, dataSource) query.executeFrom('dbo.vwDealerServiceProvider', ['serviceProviderId = :serviceProvider']) } - + /** - * Locates Online or Offline Dealers by Country or by distance from a US location - * specified by distance from a zipCode or a state/city. - * - * @param criteria - * @return List of dealers - */ + * Locates Online or Offline Dealers by Country or by distance from a US location + * specified by distance from a zipCode or a state/city. + * + * @param criteria + * @return List of dealers + */ List locateDealers(Map criteria) { sql().rows(criteria, 'EXEC dbo.spDealerLocator2012 :dm, :country, :city, :state, :zipCode, :distance, :online') } - + /** - * Finds Dealers by Service Provider - * - * @return List of Dealers - */ + * Finds Dealers by Service Provider + * + * @return List of Dealers + */ List findAllDealersByServiceProvider() { String query = 'EXEC dbo.spServiceProviderReport @reportType = ?' sql().rows(query, 'DEALERS_BY_PROVIDER') } - + /** - * Finds Expired and Expiring Service Providers. - * - * @return 2 Lists - Expired Dealers and Expiring Dealers - */ + * Finds Expired and Expiring Service Providers. + * + * @return 2 Lists - Expired Dealers and Expiring Dealers + */ List findExpiredAndExpiringServiceProviders() { String query = 'EXEC dbo.spServiceProviderReport @reportType = ?' sql().callWithAllRows(query, ['EXPIRED_PROVIDER_CONTRACTS']) { } } - + /** - * Finds DealerAddresses by dealerCode. - * - * @param criteria containing dm, appSecurity params, and dealerCode - * - * @return List of dealerAddresses - */ + * Finds DealerAddresses by dealerCode. + * + * @param criteria containing dm, appSecurity params, and dealerCode + * + * @return List of dealerAddresses + */ List findAddresses(Map criteria) { String view = criteria.addressType ? 'dbo.vwValidDealerAddress' : 'dbo.vwDealerAddress' List results = dqx(criteria).executeFrom(view, addressClauses(criteria)).results if (results) { results } else { findDealerByDealerCode(criteria) ? [] : null } } - + /** - * Find brand dealers. - * - * @param criteria containing brandId and/or dealerCode - * - * @return no. of totalRecords and List of brand dealers - */ + * Find brand dealers. + * + * @param criteria containing brandId and/or dealerCode + * + * @return no. of totalRecords and List of brand dealers + */ Map findBrandDealers(Map criteria) { dqx(criteria).executeFrom('dbo.vwDealerBrandDealerActive', brandDealerClauses(criteria)) } - + /** - * Checks for the existence of the specified dealerCode without regard to user security permissions. - * - * @param dealerCode - * - * @return true if the dealerCode is found - */ + * Checks for the existence of the specified dealerCode without regard to user security permissions. + * + * @param dealerCode + * + * @return true if the dealerCode is found + */ boolean dealerExists(String dealerCode) { new Sql(dataSource).rows('SELECT dealerCode FROM dbo.vwDealer WHERE dealerCode = ?', dealerCode) } - + /** - * Find an authorized dealer by dealerCode - * - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return dealer or null - */ + * Find an authorized dealer by dealerCode + * + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return dealer or null + */ Map findDealerByDealerCode(Map criteria) { List results = dqx(criteria).executeOneFromAppSecurity('Dealer', ['dealerCode = :dealerCode']).results results ? injectSeqList(results[0]) : null } private Map injectSeqList(Map results) { - results + [warehouseSequenceList: results.warehouseSequence?.trim()?.split(/(?<=\G..)/)] - } - + results + [warehouseSequenceList: results.warehouseSequence?.trim()?.split(/(?<=\G..)/)] + } + /** - * Find a dealer by dealerCode - * - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return no. of totalRecords and List of dealers - */ + * Find a dealer by dealerCode + * + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return no. of totalRecords and List of dealers + */ Map findDealer(Map criteria) { criteria.sorting = criteria.sorting ?: 'dealerCode' dqx(criteria).executeFromAppSecurity('Dealer', ['dealerCode = :dealerCode'], columnSets) } - + /** - * Find any dealer regardless of tenancy by dealerCode. - * - * @param dealerCode - * @return List containing the dealer - */ + * Find any dealer regardless of tenancy by dealerCode. + * + * @param dealerCode + * @return List containing the dealer + */ List findAnyDealer(String dealerCode) { sql().rows('SELECT * FROM dbo.vwDealer WHERE dealerCode = ?', dealerCode) } - + /** - * Searches for dealers like the specified q and meeting the specified criteria. - * - * Supports filtering by regionId, salesmanId, active/inactive, classification in any combination - * The classification filter must be 1 of RIDER, VENDOR, DEALER, EMPLOYEE, or OTHER. - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sort and order criteria. - * - * @param q dealerCode, dealerName, or dealerAddressZipCode (if criteria.columns != _dealer) - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return no. of totalRecords and List of dealers - */ + * Searches for dealers like the specified q and meeting the specified criteria. + * + * Supports filtering by regionId, salesmanId, active/inactive, classification in any combination + * The classification filter must be 1 of RIDER, VENDOR, DEALER, EMPLOYEE, or OTHER. + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sort and order criteria. + * + * @param q dealerCode, dealerName, or dealerAddressZipCode (if criteria.columns != _dealer) + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return no. of totalRecords and List of dealers + */ Map dealerSearch(criteria) { criteria.sorting = criteria.sorting ?: 'dealerCode' dqx(criteria).executeFromAppSecurity('Dealer', searchClauses(criteria), columnSets) } - + /** - * Get counts of all the dealers based on their dealerStatus. - * - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return Map containing value with activeCount, inactiveCount, totalCount, and regionId/salesmanId criteria - */ + * Get counts of all the dealers based on their dealerStatus. + * + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return Map containing value with activeCount, inactiveCount, totalCount, and regionId/salesmanId criteria + */ Map statusCount(criteria) { dqx(criteria).executeSelectOneFrom( DEALER_STATUS_COUNT_SQL, fromAppSecurityDealer, salesClauses(criteria)).results[0] } - + private String addDealerClause(String dealer, List clauses) { - dealer - clauses << 'dealerCode = :dealer' + dealer + clauses << 'dealerCode = :dealer' } private String addDealerClause(List dealers, List clauses) { clauses List wrappedDealers = dealers.collect { "\n\tdealerCode = '$it'" } - "WHERE (${wrappedDealers.join(' OR')}\n)" + "WHERE (${wrappedDealers.join(' OR')}\n)" } - - private final List baseColumnSet = ['dealerCode', 'dealerName'] - - private final Map columnSets = [ - _dealer: baseColumnSet, - _basic: baseColumnSet + ['legalDealerName', 'dbaDealerName'], - _list: baseColumnSet + ['purchaseLevelCode', 'primaryRep', 'primaryRepFullName', 'secondaryRep', - 'secondaryRepFullName', 'regionId', 'dealerStatus', 'TYSales'] - ] - - private static final String DEALER_STATUS_COUNT_SQL = -''' -SELECT activeCount = sum(CASE WHEN dealerStatus <> 'I' THEN 1 ELSE 0 END) - ,inactiveCount = sum(CASE WHEN dealerStatus = 'I' THEN 1 ELSE 0 END) - ,totalCount = count(*)''' - private final String fromAppSecurityDealer = 'FROM dbo.fnAppSecurityDealer(:appSecurityDealerCode, :appSecurityUserName, :dm)\n' - private List searchClauses(criteria) { List clauses = salesClauses(criteria) if (criteria.dealerStatus) { - clauses << ((criteria.dealerStatus.equalsIgnoreCase('ACTIVE')) ? ("dealerStatus <> 'I'") : ('dealerStatus = :dealerStatus')) - } + clauses << ((criteria.dealerStatus.equalsIgnoreCase('ACTIVE')) ? ("dealerStatus <> 'I'") : ('dealerStatus = :dealerStatus')) + } if (criteria.dealerCode) { clauses << 'dealerCode = :dealerCode' } - if (criteria.classification) { + if (criteria.classification) { clauses << brandClause(criteria.classification) clauses << "typeOfDealerCode NOT IN ('C', 'E')" } @@ -279,38 +281,38 @@ else if ( classification == 'EMPLOYEE') { clause = "brand = 'H'" } else { clause = "brand in ('S', 'I', 'T')" } } - + private List salesClauses(criteria) { List clauses = [] if (criteria.regionId) { clauses << 'regionId = :regionId' } if (criteria.salesmanId) { clauses << '(primaryRep = :salesmanId OR secondaryRep = :salesmanId)' } clauses } - + private List brandDealerClauses(Map criteria) { List clauses = [] if (criteria.dealerCode) { clauses << 'dealerCode = :dealerCode' } if (criteria.brandId) { clauses << 'brandId = :brandId' } clauses } - + private String qClause(criteria) { expandQ(criteria) String clause = '''( - dealerCode LIKE :beginningWithQ - OR dealerName LIKE :containingQ''' + dealerCode LIKE :beginningWithQ + OR dealerName LIKE :containingQ''' if (criteria.columns != '_dealer') { clause += '\n\tOR dealerAddressZipCode LIKE :beginningWithQ' } clause += '\n)' clause } - + private expandQ(criteria) { criteria.with { - beginningWithQ = "$q%".toString() - containingQ = "%$q%".toString() + beginningWithQ = "$q%".toString() + containingQ = "%$q%".toString() } } - + private Map transformDatesToLocalDates(Map data) { data.results = new DateTransformer().transformDatesToLocalDates(LOCAL_DATE_PROPERTIES, data.results) data Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerManagerService.groovy =================================================================== diff -u -r9474 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerManagerService.groovy (.../DealerManagerService.groovy) (revision 9474) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/DealerManagerService.groovy (.../DealerManagerService.groovy) (revision 9526) @@ -3,40 +3,28 @@ import com.lemans.services.LemansManager import grails.transaction.Transactional -import javax.servlet.ServletResponse - @Transactional class DealerManagerService extends LemansManager { /** - * Saves an existing or newly created ServiceProvider. - * - * @param values Map of property values - * @param id if not null updates the ServiceProvider, else inserts it - * @param username - * - * @return a ServiceProvider which may have errors - */ + * Saves an existing or newly created ServiceProvider. + * + * @param values Map of property values + * @param id if not null updates the ServiceProvider, else inserts it + * @param username + * + * @return a ServiceProvider which may have errors + */ ServiceProvider saveServiceProvider(Map values, Integer id, String username) { ServiceProvider serviceProvider = (id != null) ? ServiceProvider.read(id) : new ServiceProvider() - if (!serviceProvider) { throw new IllegalStateException(404, [message: "No record found for ServiceProvider with Id: $id"]) } + if (!serviceProvider) { + throw new IllegalStateException(404, [message: "No record found for ServiceProvider with Id: $id"]) + } applyValuesToDomain(values, serviceProvider) serviceProvider.validate() saveOrDiscardDomain(serviceProvider, username) } - /** - * Soft deletes a ServiceProvider. - * - * @param id - * @param username - * - * @return true if delete was successful - */ - boolean deleteServiceProvider(Integer id, String username) { - softDelete(ServiceProvider.get(id), username) - } - /** Adds a ServiceProvider to a dealer. * * @param Map of values containing dealerCode and serviceProviderId @@ -52,21 +40,37 @@ } /** - * Soft deletes a DealerService Provider. - * - * @param dealerCode - * @param serviceProviderId - * @param username - * - * @return true if delete was successful - */ + * Soft deletes a ServiceProvider. + * + * @param id + * @param username + * + * @return true if delete was successful + */ + boolean deleteServiceProvider(Integer id, String username) { + softDelete(ServiceProvider.get(id), username) + } + + /** + * Soft deletes a DealerService Provider. + * + * @param dealerCode + * @param serviceProviderId + * @param username + * + * @return true if delete was successful + */ boolean deleteDealerServiceProvider(String dealerCode, Integer serviceProviderId, String username) { DealerServiceProvider dealerServiceProvider = DealerServiceProvider.withCriteria(uniqueResult: true) { eq('serviceProviderId', serviceProviderId) eq('dealerCode', dealerCode) isNull('dateDeleted') } - if (dealerServiceProvider) { softDelete(dealerServiceProvider, username) } - else { true } + if (dealerServiceProvider) { + softDelete(dealerServiceProvider, username) + } + else { + true + } } } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileManagerService.groovy =================================================================== diff -u -r9405 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileManagerService.groovy (.../PayTraceCustomerProfileManagerService.groovy) (revision 9405) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/paytrace/PayTraceCustomerProfileManagerService.groovy (.../PayTraceCustomerProfileManagerService.groovy) (revision 9526) @@ -18,29 +18,29 @@ */ PayTraceCustomerProfile savePayTraceCustomerProfile(Map values, String customerId, String username) { PayTraceCustomerProfile paytraceCustomerProfile = validatePayTraceCustomerProfile(values, customerId) - saveOrDiscardDomain(paytraceCustomerProfile, paytraceCustomerProfile.id, username) + saveOrDiscardDomain(paytraceCustomerProfile, username) } PayTraceCustomerProfile saveProfileRestriction(boolean setPofileRestricted, String customerId, - String loggedInUsername, String loggedInDealerCode) { + String loggedInUsername, String loggedInDealerCode) { PayTraceCustomerProfile paytraceCustomerProfile = validatePayTraceCustomerProfile(['lemansRestricted': setPofileRestricted], customerId) if (paytraceCustomerProfile.dealerCode != loggedInDealerCode && !paytraceCustomerProfile.hasErrors()) { paytraceCustomerProfile.errors.rejectValue('customerId', null, [] as Object[], 'Logged in User is restricted to edit this profile.') } - saveOrDiscardDomain(paytraceCustomerProfile, paytraceCustomerProfile.id, loggedInUsername) + saveOrDiscardDomain(paytraceCustomerProfile, loggedInUsername) } PayTraceCustomerProfile validateAndDiscardProfile(Map values, String customerId) { PayTraceCustomerProfile profile = validatePayTraceCustomerProfile(values, customerId) - profile.discard() - profile + profile.discard() + profile } PayTraceCustomerProfile validatePayTraceCustomerProfile(Map values, String customerId) { PayTraceCustomerProfile paytraceCustomerProfile = PayTraceCustomerProfile.findByCustomerId(customerId) if (paytraceCustomerProfile) { - paytraceCustomerProfile.properties = filterCriteria(values) + applyValuesToDomain(values, paytraceCustomerProfile) paytraceCustomerProfile.validate() paytraceCustomerProfile } else { Index: branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalService.groovy =================================================================== diff -u -r9491 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalService.groovy (.../SalesGoalService.groovy) (revision 9491) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalService.groovy (.../SalesGoalService.groovy) (revision 9526) @@ -2,7 +2,6 @@ import com.lemans.services.LemansService import com.lemans.time.DateTransformer -import com.lemans.services.DynamicQueryExecutor import grails.transaction.Transactional @Transactional @@ -11,137 +10,137 @@ private static final List LOCAL_DATE_PROPERTIES = ['startDate', 'endDate'] /** - * Find SalesGoalCriteria By Id. - * - * @param criteria with id - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalCriteria By Id. + * + * @param criteria with id + * + * @return Map with results List and totalRecords + */ Map findSalesGoalCriteriaById(Map criteria) { dqx(criteria).executeOneFrom('dbo.vwSalesGoalCriteria', ['x.SalesGoalCriteriaId = :id']) } /** - * Find SalesGoalCriteria optionally by sales goal. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalCriteria optionally by sales goal. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findSalesGoalCriteria(Map criteria) { dqx(criteria).executeFrom('dbo.vwSalesGoalCriteria', salesGoalClauses(criteria)) } /** - * Find SalesGoalParticipant By Id. - * - * @param criteria with id - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalParticipant By Id. + * + * @param criteria with id + * + * @return Map with results List and totalRecords + */ Map findSalesGoalParticipantById(Map criteria) { dqx(criteria).executeOneFrom('dbo.vwSalesGoalParticipant', ['x.salesGoalParticipantId = :id']) } /** - * Find SalesGoalParticipants. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalParticipants. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findSalesGoalParticipants(Map criteria) { dqx(criteria).executeFrom('dbo.vwSalesGoalParticipant', salesGoalClauses(criteria)) } /** - * Find SalesGoalFrequency by id. - * - * @param criteria with id - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalFrequency by id. + * + * @param criteria with id + * + * @return Map with results List and totalRecords + */ Map findSalesGoalFrequencyById(Map criteria) { Map data = dqx(criteria).executeOneFrom('dbo.vwSalesGoalFrequency', ['x.salesGoalFrequencyId = :id']) transformDatesToLocalDateTimes(data) } /** - * Find SalesGoalFrequencies by salesGoalId. - * - * @param criteria with salesGoalId - * - * @return Map with results List and totalRecords - */ + * Find SalesGoalFrequencies by salesGoalId. + * + * @param criteria with salesGoalId + * + * @return Map with results List and totalRecords + */ Map findSalesGoalFrequencies(Map criteria) { Map data = dqx(criteria).executeFrom('dbo.vwSalesGoalFrequency', salesGoalClauses(criteria)) transformDatesToLocalDateTimes(data) } /** - * Find SalesGoal by id. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Find SalesGoal by id. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findSalesGoalById(Map criteria) { Map data = dqx(criteria).executeOneFrom('dbo.vwSalesGoal', ['x.salesGoalId = :id']) transformDatesToLocalDates(data) } /** - * Find SalesGoals by salesmanId and/or sampleTypeId. - * - * @param criteria with salesmanId and/or sampleTypeId - * - * @return Map with results List and totalRecords - */ + * Find SalesGoals by salesmanId and/or sampleTypeId. + * + * @param criteria with salesmanId and/or sampleTypeId + * + * @return Map with results List and totalRecords + */ Map findSalesGoals(Map criteria) { Map data = dqx(criteria).executeFrom('dbo.vwSalesGoal', salesGoalClauses(criteria)) transformDatesToLocalDates(data) } /** - * Find all SalesGoalOutputTypes. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Find all SalesGoalOutputTypes. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findSalesGoalOutputTypes(Map criteria) { dqx(criteria).executeFrom('dbo.vwSalesGoalOutputType') } /** - * Find SalesGoal report. - * - * @param criteria - * - * @return Map with results List and totalRecords - */ + * Find SalesGoal report. + * + * @param criteria + * + * @return Map with results List and totalRecords + */ Map findSalesGoalReport(Map criteria) { dqx(criteria).executeFrom('dbo.vwSalesGoalReport') } /** - * Find SalesGoal parts report by salesGoalId. - * - * @param criteria with salesGoal (id) - * - * @return Map with results List and totalRecords - */ + * Find SalesGoal parts report by salesGoalId. + * + * @param criteria with salesGoal (id) + * + * @return Map with results List and totalRecords + */ Map findPartReportBySalesGoal(Map criteria) { dqx(criteria).executeSelectFrom('SELECT *', "FROM dbo.fnRetrievePartBySalesGoalId($criteria.salesGoal) x") } /** - * Find SalesGoal Rep report by salesGoalId. - * - * @param criteria with salesGoal (id) - * - * @return Map with results List and totalRecords - */ + * Find SalesGoal Rep report by salesGoalId. + * + * @param criteria with salesGoal (id) + * + * @return Map with results List and totalRecords + */ Map findRepReportBySalesGoal(Map criteria) { dqx(criteria).executeSelectFrom('SELECT *', "FROM dbo.fnRetrieveRepBySalesGoalId($criteria.salesGoal) x") } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportManagerService.groovy =================================================================== diff -u -r9501 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportManagerService.groovy (.../MonthlyReportManagerService.groovy) (revision 9501) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/rider/MonthlyReportManagerService.groovy (.../MonthlyReportManagerService.groovy) (revision 9526) @@ -6,29 +6,26 @@ import java.time.YearMonth import java.time.ZoneId -/** - * Created by vramisetti on 5/20/2016. - */ @Transactional class MonthlyReportManagerService extends RaceReportManagerService { def raceResultService /** - * Saves an existing or newly created MonthlyReport. - * - * @param values Map of property values - * @param dealerCode owner - * @param reportDate(YearMonth) if not null updates the MonthlyReport, else inserts it - * @param username - * - * @return a MonthlyReport which may have errors or null - */ + * Saves an existing or newly created MonthlyReport. + * + * @param values Map of property values + * @param dealerCode owner + * @param reportDate(YearMonth) if not null updates the MonthlyReport, else inserts it + * @param username + * + * @return a MonthlyReport which may have errors or null + */ MonthlyReport addOrUpdateReport(Map values, String dealerCode, YearMonth reportDate, String username) { Dealer dealer = dealer(dealerCode) MonthlyReport monthlyReport = findReportByMonth(dealer, reportDate) ?: new MonthlyReport() if (dealer && monthlyReport) { - applyValuesToDomain(values, monthlyReport) + applyValuesToDomain(values, monthlyReport) if (!monthlyReport.id) { monthlyReport.dealer = dealer monthlyReport.raceMonth = Date.from(reportDate.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant()) @@ -42,14 +39,14 @@ } /** - * Submits an existing MonthlyReport. - * - * @param dealerCode owner - * @param reportDate(YearMonth) - * @param username - * - * @return a MonthlyReport which may have errors or null - */ + * Submits an existing MonthlyReport. + * + * @param dealerCode owner + * @param reportDate(YearMonth) + * @param username + * + * @return a MonthlyReport which may have errors or null + */ MonthlyReport submitReport(String dealerCode, YearMonth reportDate, Integer domain, String username) { MonthlyReport monthlyReport = addOrUpdateReport([submitReport: true], dealerCode, reportDate, username) if (monthlyReport && !monthlyReport.hasErrors()) { sendMonthlyReportEmail(monthlyReport, domain) } @@ -59,24 +56,24 @@ private void sendMonthlyReportEmail(MonthlyReport monthlyReport, Integer domain) { Map metaData = findMetadata(domain) Map model = [monthlyReport: monthlyReport, - races: raceResults(monthlyReport), - to: metaData.adminEmail?.split(','), - dashBoardRaceReportUrl: dashBoardRaceReportUrl(metaData.dashboardUrl, - monthlyReport.raceMonth.format('yyyyMM'), monthlyReport.dealer.id), - subject: "${monthlyReport.raceMonth.format('MMMM yyyy')} Monthly Report for Rider $monthlyReport.dealer.id"] + - questions(domain) + races: raceResults(monthlyReport), + to: metaData.adminEmail?.split(','), + dashBoardRaceReportUrl: dashBoardRaceReportUrl(metaData.dashboardUrl, + monthlyReport.raceMonth.format('yyyyMM'), monthlyReport.dealer.id), + subject: "${monthlyReport.raceMonth.format('MMMM yyyy')} Monthly Report for Rider $monthlyReport.dealer.id"] + + questions(domain) MimeMessage msg = createHtmlEmailMessage('monthlyReport', model) mailSender.send(msg) } private Map questions(Integer domain) { Map metaData = [18: [question1: 'What did you do this month to promote moose?', - question2: 'Did you display a Moose Racing banner at all events this month? Yes or No? If No, why not?', - question3: 'Product Comments', question4: 'General Comments'], - 19: [question1: 'What did you do this month to promote THOR?', - question2: 'How many times did you mention @thormxofficial in your social media?', - question3: 'Product Comments. Good or bad. Be specific - Type of gear, color, etc.', - question4: 'General Comments']] + question2: 'Did you display a Moose Racing banner at all events this month? Yes or No? If No, why not?', + question3: 'Product Comments', question4: 'General Comments'], + 19: [question1: 'What did you do this month to promote THOR?', + question2: 'How many times did you mention @thormxofficial in your social media?', + question3: 'Product Comments. Good or bad. Be specific - Type of gear, color, etc.', + question4: 'General Comments']] metaData[domain] ?: [question1: 'Question 1', question2: 'Question2', question3: 'Question3', question4: 'Question4'] } @@ -86,15 +83,15 @@ private List raceResults(MonthlyReport monthlyReport) { raceResultService.findRaceResults([reportDate: monthlyReport.raceMonth.toString(), - dealerCode: monthlyReport.dealer.id])?.results ?: [] + dealerCode: monthlyReport.dealer.id])?.results ?: [] } private MonthlyReport findReportByMonth(Dealer rider, YearMonth date) { MonthlyReport.where { - dealer == rider - month(raceMonth) == date.monthValue - year(raceMonth) == date.year - dateDeleted == null + dealer == rider + month(raceMonth) == date.monthValue + year(raceMonth) == date.year + dateDeleted == null }.find() } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalManagerService.groovy =================================================================== diff -u -r9491 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalManagerService.groovy (.../SalesGoalManagerService.groovy) (revision 9491) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/sales/goals/SalesGoalManagerService.groovy (.../SalesGoalManagerService.groovy) (revision 9526) @@ -1,9 +1,7 @@ package com.lemans.sales.goals -//import com.lemans.errors.ServiceException import com.lemans.services.LemansManager import grails.transaction.Transactional -import groovy.sql.Sql @Transactional class SalesGoalManagerService extends LemansManager { @@ -113,7 +111,6 @@ SalesGoalCriteria saveSalesGoalCriteria(Map values, Integer id, String username) { SalesGoalCriteria salesGoalCriteria = (id != null) ? findSalesGoalCriteria(id) : new SalesGoalCriteria() if (!salesGoalCriteria) { throw new IllegalStateException("No record found for SalesGoalCriteria with Id: $id") } - applyValuesToDomain(values, salesGoalCriteria) salesGoalCriteria.validate() validateSalesGoalCriteria(salesGoalCriteria, values.locale) Index: branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaService.groovy =================================================================== diff -u -r9464 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaService.groovy (.../MediaService.groovy) (revision 9464) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/media/MediaService.groovy (.../MediaService.groovy) (revision 9526) @@ -6,71 +6,70 @@ @Transactional class MediaService extends LemansService { - /** - * Find a media by id. - * - * @param criteria containing id - * - * @return media - */ + * Find a media by id. + * + * @param criteria containing id + * + * @return media + */ Map findMediaById(Map criteria) { dqx(criteria).executeOneFrom('vwMedia', clauses(criteria)).results[0] } /** - * Finds media by entityClass and entityId. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @param criteria containing entityClass and entityId - * - * @return Map containing no. of totalRecords and List containing media - */ + * Finds media by entityClass and entityId. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @param criteria containing entityClass and entityId + * + * @return Map containing no. of totalRecords and List containing media + */ Map findMedia(Map criteria) { criteria.sorting = criteria.sorting ?: 'mediaId+ASC' dqx(criteria).executeFrom('vwMedia', clauses(criteria)) } /** - * Finds MediaType's. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @return Map containing no. of totalRecords and List containing mediaType - */ + * Finds MediaType's. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @return Map containing no. of totalRecords and List containing mediaType + */ Map findMediaType(Map criteria) { criteria.sorting = criteria.sorting ?: 'mediaTypeId+ASC' dqx(criteria).executeFrom('vwMediaType') } /** - * Finds Supported Media Types's. - * - * @return Map containing results - */ + * Finds Supported Media Types's. + * + * @return Map containing results + */ Map findSupportedMediaTypes(Map criteria) { criteria.version = -1 criteria.columns = 'description,extension,mediaTypeId,mediaTypeDescription' Map data = dqx(criteria).executeFrom('vwMimeType', ['mediaTypeId IS NOT NULL', 'version != :version']) - [ - results: data.results.groupBy { it.mediaTypeDescription } - .collectEntries { k, v -> - [("$k".toString()): [description: k, mediaTypeId: v[0].mediaTypeId, mimeTypes: v*.description.unique()]] - } - ] + [ + results: data.results.groupBy { it.mediaTypeDescription } + .collectEntries { k, v -> + [("$k".toString()): [description: k, mediaTypeId: v[0].mediaTypeId, mimeTypes: v*.description.unique()]] + } + ] } /** - * Finds Media Categories. - * - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting - * - * @return Map containing no. of totalRecords and List containing mediaCategory - */ + * Finds Media Categories. + * + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting + * + * @return Map containing no. of totalRecords and List containing mediaCategory + */ Map findMediaCategory(Map criteria) { criteria.sorting = criteria.sorting ?: 'mediaCategoryId+ASC' dqx(criteria).executeFrom('vwMediaCategory', categoryClauses(criteria)) @@ -85,6 +84,7 @@ clauses } - private List categoryClauses(criteria) { criteria.mediaTypeId ? ['mediaTypeId = :mediaTypeId'] : [] } - + private List categoryClauses(criteria) { + criteria.mediaTypeId ? ['mediaTypeId = :mediaTypeId'] : [] + } } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/sales/SalesRepValidationService.groovy =================================================================== diff -u -r9405 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/sales/SalesRepValidationService.groovy (.../SalesRepValidationService.groovy) (revision 9405) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/sales/SalesRepValidationService.groovy (.../SalesRepValidationService.groovy) (revision 9526) @@ -1,88 +1,56 @@ package com.lemans.sales +import com.lemans.dealer.activities.DealerActivity import com.lemans.services.LemansService import grails.transaction.Transactional -import groovy.sql.Sql -import org.springframework.web.context.request.RequestContextHolder -/** - * Validation Service - * @author vkulkarni - * - */ @Transactional @SuppressWarnings(['CatchException']) class SalesRepValidationService extends LemansService { - - static final String DIVISION_SALESFORCE_TYPE = 'DIVISION' + +/* static final String DIVISION_SALESFORCE_TYPE = 'DIVISION' static final String REGION_SALESFORCE_TYPE = 'REGION' static final String REP_SALESFORCE_TYPE = 'REP' - static final String COMPANY_SALESFORCE_TYPE = 'COMPANY' - - //def dataSource - - List checkAuthorizedDealerCode(dealerCode) { + static final String COMPANY_SALESFORCE_TYPE = 'COMPANY'*/ + + private static final String DEALER_USERTYPE_SQL = ''' + SELECT appSecurityUserTypeName AS appSecurityUserType + FROM dbo.fnAppSecurityDealer(:appSecurityDealerCode, :appSecurityUserName, :dm) x + WHERE x.dealerCode = :dealerCode + ''' + + private static final String SALESREP_USERTYPE_SQL = ''' + SELECT appSecurityUserTypeName AS appSecurityUserType + FROM dbo.fnAppSecuritySalesman(:appSecurityDealerCode, :appSecurityUserName, :dm) x + WHERE x.salesmanId = :salesmanId + ''' + + List checkAuthorizedDealerCode(Map criteria) { List errors = [] - String loggedInDealerCode = requestHeaders.loggedInDealerCode - if (!checkAccess(dealerCode)) { - String msg = "Logged in dealer ${loggedInDealerCode} is not authorized to access/modify data for dealer ${dealerCode}" + String loggedInDealerCode = criteria.appSecurityDealerCode + if (!dealerDetails(criteria)) { + String msg = "Logged in dealer ${loggedInDealerCode} is not authorized to access/modify data for dealer ${criteria.dealerCode}" errors.add([code: msg, args: []]) } errors } - - List checkAuthorizedActivity(activityId) { + + /*List checkAuthorizedActivity(Map criteria) { List errors = [] - String loggedInDealerCode = requestHeaders.loggedInDealerCode - def dealerCode = DealerActivity.read(activityId)?.dealerCode - if (!checkAccess(dealerCode)) { + String loggedInDealerCode = criteria.loggedInDealerCode + String dealerCode = findDomainObjectById(DealerActivity, criteria.activityId)?.dealerCode + if (!dealerCode || !dealerDetails(criteria + [dealerCode: dealerCode])) { String msg = "Logged in dealer ${loggedInDealerCode} is not authorized to access/modify data for dealer ${dealerCode}" errors.add([code: msg, args: []]) } errors - } - + }*/ + boolean checkAccessForSalesPerson(salesmanId) { - Map criteria = baseCriteria() + [salesmanId: salesmanId] - sql().firstRow(SALESREP_USERTYPE_SQL, criteria) != null + sql().firstRow(SALESREP_USERTYPE_SQL, salesmanId) } - - private boolean checkAccess(dealerCode) { getAppSecurityDealerDetails(dealerCode) } - - private webParameters() { RequestContextHolder.currentRequestAttributes().params } - - private Map getAppSecurityDealerDetails(dealerCode) { - Map criteria = baseCriteria() + [dealerCode: dealerCode] + + private Map dealerDetails(criteria) { sql().firstRow(DEALER_USERTYPE_SQL, criteria) } - - private Map baseCriteria() { - String loggedInUserName = requestHeaders.loggedInUserName - String loggedInDealerCode = requestHeaders.loggedInDealerCode - Map parameters = webParameters() - [appSecurityDealerCode: loggedInDealerCode, appSecurityUserName: loggedInUserName, dm: parameters.dm] - } - - private static final String DEALER_USERTYPE_SQL = ''' -SELECT appSecurityUserTypeName AS appSecurityUserType -FROM dbo.fnAppSecurityDealer(:appSecurityDealerCode, :appSecurityUserName, :dm) x -WHERE x.dealerCode = :dealerCode -''' - - private static final String SALESREP_USERTYPE_SQL = ''' -SELECT appSecurityUserTypeName AS appSecurityUserType -FROM dbo.fnAppSecuritySalesman(:appSecurityDealerCode, :appSecurityUserName, :dm) x -WHERE x.salesmanId = :salesmanId -''' - - private Map getRequestHeaders() { - Map map = [:] - def request = RequestContextHolder.currentRequestAttributes().currentRequest.request - map.loggedInUserName = request.getHeader('loggedInUserName') - map.loggedInDealerCode = request.getHeader('loggedInDealerCode') - map.parameters = RequestContextHolder.currentRequestAttributes().params - map - } - - //private Sql sql() { new Sql(dataSource) } } Index: branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/activities/DealerActivityService.groovy =================================================================== diff -u -r9405 -r9526 --- branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/activities/DealerActivityService.groovy (.../DealerActivityService.groovy) (revision 9405) +++ branches/grails3_dealer-service/grails-app/services/com/lemans/dealer/activities/DealerActivityService.groovy (.../DealerActivityService.groovy) (revision 9526) @@ -10,111 +10,102 @@ @Transactional class DealerActivityService extends LemansService { - def dealerService + def dealerService - private static final String SALES_ACTIVITY_LOG_SQL = - 'EXEC dbo.spActivityLogReport @salesmanId = ?, @startDate = ?, @endDate = ?, @dealerStatus = ?, @reportType = ?' - + private static final String SALES_ACTIVITY_LOG_SQL = + 'EXEC dbo.spActivityLogReport @salesmanId = ?, @startDate = ?, @endDate = ?, @dealerStatus = ?, @reportType = ?' + private final Map columnSets = [_summary: baseColumnSet + ['dealerName', 'totalOrderAmount'], _list: baseColumnSet,] + + private final List baseColumnSet = ['dealerActivityId', 'activityDate', 'dealerCode', 'activityTypeName', 'createdBy',] + /** - * Gets the salesActivity log data. - * - * @param criteria containing salesmanId, startDate, endDate, reportType (typically null for getting the data as XML) - * - * @return JSON Array with report data - */ + * Gets the salesActivity log data. + * + * @param criteria containing salesmanId, startDate, endDate, reportType (typically null for getting the data as XML) + * + * @return JSON Array with report data + */ JSONObject activityLog(List criteria) { - JSONObject xmlJSONObj + JSONObject xmlJSONObj new Sql(dataSource).eachRow(SALES_ACTIVITY_LOG_SQL, criteria) { row -> if (row.getCharacterStream(1)?.ready()) { xmlJSONObj = XML.toJSONArray(IOUtils.toString(row.getCharacterStream(1))) } } xmlJSONObj } - + /** - * Find all DealerActivityTypes. - * - * @return List containing the activities - */ + * Find all DealerActivityTypes. + * + * @return List containing the activities + */ List findAllActivityTypes() { dqx([:]).executeOneFrom('dbo.vwDealerActivityType').results } - + /** - * Find an activity by id for the current user. - * - * @param criteria containing id, dm, appSecurityDealerCode, and appSecurityUserName - * - * @return no. of totalRecords and List containing the activity - */ - Map findActivityById(Map criteria) { - List clauses = ['dealerActivityId = :id', 'dealerCode = :dealerCode'] + * Find an activity by id for the current user. + * + * @param criteria containing id, dm, appSecurityDealerCode, and appSecurityUserName + * + * @return no. of totalRecords and List containing the activity + */ + Map findActivityById(Map criteria) { + List clauses = ['dealerActivityId = :id', 'dealerCode = :dealerCode'] dqx(criteria).executeOneFromAppSecurity('DealerActivity', clauses).results[0] } - + /** - * Finds activities by dealerCode or region/salesRep for the current user. - * - * Supports filtering by dealerCode, regionId, salesmanId in any combination - * Supports pagination via offset and pageSize criteria. - * Supports sorting via sorting criteria. - * Supports totalOrderAmount inclusive range filtering by lowerTotalAmount and higherTotalAmount criteria. - * Supports activityDate inclusive range filtering by startDate and endDate. - * - * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName - * - * @return no. of totalRecords and List containing the activities - */ + * Finds activities by dealerCode or region/salesRep for the current user. + * + * Supports filtering by dealerCode, regionId, salesmanId in any combination + * Supports pagination via offset and pageSize criteria. + * Supports sorting via sorting criteria. + * Supports totalOrderAmount inclusive range filtering by lowerTotalAmount and higherTotalAmount criteria. + * Supports activityDate inclusive range filtering by startDate and endDate. + * + * @param criteria containing dm, appSecurityDealerCode, and appSecurityUserName + * + * @return no. of totalRecords and List containing the activities + */ Map findActivities(Map criteria) { - criteria.sorting = criteria.sorting ?: 'activityDate+DESC' + criteria.sorting = criteria.sorting ?: 'activityDate+DESC' Map data - if (criteria.activityPerformedBySalesmanId || criteria.activityPerformedByDealerCode) { - data = dqx(criteria).executeFrom('vwDealerActivity', clauses(criteria), columnSets) - } else { - data = dqx(criteria).executeFromAppSecurity('DealerActivity', clauses(criteria), columnSets) - } - if (data.results) { data } - else { criteria.dealerCode ? (dealerService.findDealerByDealerCode(criteria) ? data : null) : data } + if (criteria.activityPerformedBySalesmanId || criteria.activityPerformedByDealerCode) { + data = dqx(criteria).executeFrom('vwDealerActivity', clauses(criteria), columnSets) + } else { + data = dqx(criteria).executeFromAppSecurity('DealerActivity', clauses(criteria), columnSets) + } + if (data.results) { data } + else { criteria.dealerCode ? (dealerService.findDealerByDealerCode(criteria) ? data : null) : data } } - - private final List baseColumnSet = ['dealerActivityId', 'activityDate', 'dealerCode', 'activityTypeName', 'createdBy',] - - private final Map columnSets = [ - _summary: baseColumnSet + ['dealerName', 'totalOrderAmount'], - _list: baseColumnSet, - ] - + private List clauses(criteria) { List clauses = [] if (criteria.activityTypeName) { clauses << 'x.activityTypeName = :activityTypeName' } if (criteria.dealerCode) { clauses << 'x.dealerCode = :dealerCode' } if (criteria.lowerSalesAmount != null) { clauses << 'x.totalOrderAmount >= :lowerSalesAmount' } if (criteria.upperSalesAmount != null) { clauses << 'x.totalOrderAmount <= :upperSalesAmount' } - addSalesClauses(criteria, clauses) - if (criteria.startDate) { clauses << 'x.activityDate >= :startDate' } if (criteria.endDate) { clauses << 'x.activityDate <= :endDate' } - - if (criteria.activityPerformedBySalesmanId) { clauses << 'x.activityPerformedBySalesmanId = :activityPerformedBySalesmanId' } - if (criteria.activityPerformedByDealerCode) { clauses << 'x.activityPerformedByDealerCode = :activityPerformedByDealerCode' } - + if (criteria.activityPerformedBySalesmanId) { clauses << 'x.activityPerformedBySalesmanId = :activityPerformedBySalesmanId' } + if (criteria.activityPerformedByDealerCode) { clauses << 'x.activityPerformedByDealerCode = :activityPerformedByDealerCode' } clauses } private addSalesClauses(Map criteria, List clauses) { if (criteria.regionId) { clauses << '''( - x.primaryRepRegionId = :regionId - OR x.secondaryRepRegionId = :regionId -)''' + x.primaryRepRegionId = :regionId + OR x.secondaryRepRegionId = :regionId + )''' } - if (criteria.salesmanId) { clauses << '''( - x.primaryRep = :salesmanId - OR x.secondaryRep = :salesmanId -)''' + x.primaryRep = :salesmanId + OR x.secondaryRep = :salesmanId + )''' } } }