Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ProductImportController{
- if(isUploading){ return; }
- isUploading = true;
- //Show/hide sections
- showResults = true;
- showImport = false;
- try{
- parseCsvInsertProductsPricebooks();
- }catch(Exception e){
- ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage() ));
- //Show/hide sections
- showResults = false;
- showImport = true;
- isUploading = false;
- if(Test.isRunningTest()){
- throw e;
- }else{
- return;
- }
- }
- //Finished
- ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Product import completed.'));
- isUploading = false;
- if(csvFileBody == null){
- throw new ProductImportException('No CSV found.');
- }
- //Convert from blob to string
- String csvString = csvFileBody.toString();
- csvFileBody = null;
- csvFileName = null;
- if(String.isBlank(csvString)){
- throw new ProductImportException('Empty CSV found.');
- }
- //Parse CSV into separate fields
- List<List<String>> allFields = parseCSV(csvString);
- if(allFields == null || allFields.isEmpty()){
- throw new ProductImportException('Empty CSV found.');
- }
- //Use first line as header
- List<String> headerFields = allFields.remove(0);
- List<HeaderWrapper> headerList = parseHeaders(headerFields);
- List<LineWrapper> lineList = new List<LineWrapper>();
- //Parse remaining lines
- if(allFields == null || allFields.isEmpty()){
- throw new ProductImportException('No rows found.');
- }else{
- for(List<String> line : allFields){
- lineList.add(new LineWrapper(line,headerList));
- }
- }
- //Get all products
- prdctList = new List<Product2>();
- for(LineWrapper line : lineList){
- prdctList.add(line.prdct);
- }
- //Insert products
- try{
- insert prdctList;
- System.debug(prdctList);
- }catch(Exception e){
- throw new ProductImportException('Could not insert products. ' + e.getMessage() ,e);
- }
- //Insert standard pricebook entries
- pbeListStandard = new List<PricebookEntry>();
- for(LineWrapper line : lineList){
- List<PricebookEntry> l = line.getStandard();
- if(l != null){
- pbeListStandard.addAll(l);
- }
- }
- try{
- if(!pbeListStandard.isEmpty()){
- System.debug('* ** *** inserting standard pbe ' + pbeListStandard);
- insert pbeListStandard;
- System.debug(pbeListStandard);
- }
- }catch(Exception e){
- throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage() ,e);
- }
- //Insert custom pricebook entries
- pbeListCustom = new List<PricebookEntry>();
- for(LineWrapper line : lineList){
- List<PricebookEntry> l = line.getCustom();
- if(l != null && !l.isEmpty()){
- pbeListCustom.addAll(l);
- }
- }
- try{
- if(!pbeListCustom.isEmpty()){
- System.debug('* ** *** inserting custom pbe ' + pbeListCustom);
- insert pbeListCustom;
- System.debug(pbeListCustom);
- }
- }catch(Exception e){
- throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage(),e);
- }
- //List of headers
- List<HeaderWrapper> headerList = new List<HeaderWrapper>();
- //Mapping setting
- Map<String,ProductImportMapping__mdt> pim = new Map<String,ProductImportMapping__mdt>();
- for(ProductImportMapping__mdt p : [SELECT MasterLabel, Field__c, isProductField__c, Pricebook__c, Isocode__c FROM ProductImportMapping__mdt]){
- pim.put(p.MasterLabel,p);
- }
- //Field types
- Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Product2.fields.getMap();
- //Pricebooks
- Map<Id,Pricebook2> pbMap = new Map<Id,Pricebook2>([SELECT Id FROM Pricebook2 WHERE IsStandard = false]);
- Id pbStandard;
- if(Test.isRunningTest()){
- pbStandard = Test.getStandardPricebookId();
- }else{
- List<Pricebook2> pbStandardList = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
- if(pbStandardList == null || pbStandardList.isEmpty()){
- throw new ProductImportException('Could not find standard pricebook.');
- }else{
- pbStandard = pbStandardList.get(0).Id;
- }
- }
- //Map header
- for(String field : headerFields){
- //Get custom setting
- ProductImportMapping__mdt setting = pim.get(field);
- HeaderWrapper header;
- if(setting != null){
- if(setting.isProductField__c){
- //check that field is valid and creatable
- if(fieldMap.containsKey(setting.Field__c.toLowerCase()) && fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().isCreateable()){
- //create header wrapper
- header = new HeaderWrapper();
- header.name = field;
- header.field = setting.Field__c;
- header.isProductField = true;
- header.isSkip = false;
- header.type = String.valueOf(fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().getType());
- }else{
- //skip header wrapper if no field
- header = new HeaderWrapper();
- header.isSkip = true;
- }
- }else{
- //check that pricebook is valid
- Id pbId;
- try{
- pbId = Id.valueOf(setting.Pricebook__c);
- }catch(Exception e){
- throw new ProductImportException('Could not convert pricebook Id.', e);
- }
- if(!pbMap.containsKey(pbId)){
- throw new ProductImportException('Id is not a custom pricebook Id');
- }
- //create header wrapper
- header = new HeaderWrapper();
- header.name = field;
- header.isProductField = false;
- header.pricebook = setting.Pricebook__c;
- header.standard = pbStandard;
- header.isocode = setting.Isocode__c;
- header.isSkip = false;
- }
- }else{
- //skip header wrapper
- header = new HeaderWrapper();
- header.isSkip = true;
- }
- //add to list
- headerList.add(header);
- }//end-for
- return headerList;
- contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
- contents = contents.replaceAll('""','DBLQT');
- List<String> lines = new List<String>();
- try {
- lines = contents.split('n');
- } catch (Exception e) {
- throw new ProductImportException('Could not split CSV.', e);
- }
- Integer num = 0;
- for(String line : lines) {
- // check for blank CSV lines (only commas)
- if (line.replaceAll(',','').trim().length() == 0) break;
- line = line.replaceAll('r','').trim();
- List<String> fields = line.split(',');
- List<String> cleanFields = new List<String>();
- String compositeField;
- Boolean makeCompositeField = false;
- for(String field : fields) {
- if (field.startsWith('"') && field.endsWith('"')) {
- cleanFields.add(field.replaceAll('DBLQT','"'));
- } else if (field.startsWith('"')) {
- makeCompositeField = true;
- compositeField = field;
- } else if (field.endsWith('"')) {
- compositeField += ',' + field;
- cleanFields.add(compositeField.replaceAll('DBLQT','"'));
- makeCompositeField = false;
- } else if (makeCompositeField) {
- compositeField += ',' + field;
- } else {
- cleanFields.add(field.replaceAll('DBLQT','"'));
- }
- }
- allFields.add(cleanFields);
- }
- return allFields;
- public LineWrapper(List<String> fields, List<HeaderWrapper> headerList){
- System.debug('* ** *** fieldsize: ' + fields.size() + '. headersize: ' + headerList.size());
- //Loop through every cell in row
- for(Integer ctr = 0; ctr < fields.size() && ctr < headerList.size(); ctr++){
- //Get value of cell and header
- String field = fields.get(ctr);
- HeaderWrapper header = headerList.get(ctr);
- System.debug('LineWrapper #' + ctr + ': "' + field + '" ' + header);
- if(header == null || header.isSkip){
- //Do nothing
- System.debug('* ** *** skip');
- }else if(header.isProductField && field == null){
- //Field name is required
- throw new ProductImportException('Could not identify field for line: ' + fields);
- }else if(header.isProductField && field != null){
- //Create product
- if(this.prdct == null){
- this.prdct = new Product2();
- }
- //Set value of field depending on type
- try{
- if(header.type == 'BOOLEAN'){
- this.prdct.put(header.field,Boolean.valueOf(field));
- }else if(header.type == 'DATETIME'){
- this.prdct.put(header.field,DateTime.valueOf(field));
- }else if(header.type == 'DOUBLE'){
- this.prdct.put(header.field,Double.valueOf(field));
- }else if(header.type == 'BOOLEAN'){
- this.prdct.put(header.field,Boolean.valueOf(field));
- }else if(header.type == 'REFERENCE'){
- this.prdct.put(header.field,Id.valueOf(field));
- }else{
- this.prdct.put(header.field,field);
- }
- }catch(Exception e){
- throw new ProductImportException('Could not populate field ' + header.field + ' with ' + field);
- }
- }else if(String.isBlank(header.isocode) || header.pricebook == null){
- //Pricebook and isocode mapping required
- throw new ProductImportException('Could not identify pricebook and currency for line: ' + fields);
- }else{
- Decimal price = Decimal.valueOf(field);
- //Create custom pricebook entry
- PricebookEntry pbe = new PricebookEntry(Pricebook2Id = header.pricebook, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode);
- //Create standard pricebook entry
- if(!pbeStandard.containsKey(header.isocode)){
- pbeStandard.put(header.isocode,new PricebookEntry(Pricebook2Id = header.standard, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode));
- //Set custom to use standard
- pbe.UseStandardPrice = true;
- }
- //Add custom pricebook entry to list
- this.pbeCustom.add(pbe);
- }//end if-else
- }//end for
- }//end constructor
- public List<PricebookEntry> getStandard(){
- for(PricebookEntry pbe : pbeStandard.values()){
- pbe.Product2Id = prdct.Id;
- }
- return pbeStandard.values();
- }
- public List<PricebookEntry> getCustom(){
- for(PricebookEntry pbe : pbeCustom){
- pbe.Product2Id = prdct.Id;
- }
- return pbeCustom;
- }
- @isTest
- Product2 prdctlist = new Product2(Name = 'Test Product004', ProductCode = 'Test Product004');
- insert prdctlist;
- Pricebook2 pbeListStandard = new Pricebook2(Name = 'Test Pricebook', Description = 'Test Pricebook',CurrencyIsoCode = 'USD',IsActive = true);
- insert pbeListStandard;
- Pricebook2 pbeListCustom = new Pricebook2(Name = 'Test Pricebook', Description = 'Test Pricebook',CurrencyIsoCode = 'USD',IsActive = true);
- insert pbeListCustom;
- //ApexPages.StandardController controller = new ApexPages.standardController(testProduct);
- ProductImportController scontroller = new ProductImportController();
- //blob csvFileBody;
- scontroller.csvFileName = 'Test Product';
- scontroller.csvFileBody = Blob.valueOf('Test AttachmentBody');
- scontroller.upload();
- //scontroller.parseCsvInsertProductsPricebooks();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement