Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.17 KB | None | 0 0
  1. public class ProductImportController{
  2.  
  3. if(isUploading){ return; }
  4. isUploading = true;
  5.  
  6. //Show/hide sections
  7. showResults = true;
  8. showImport = false;
  9.  
  10. try{
  11. parseCsvInsertProductsPricebooks();
  12. }catch(Exception e){
  13. ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage() ));
  14.  
  15. //Show/hide sections
  16. showResults = false;
  17. showImport = true;
  18. isUploading = false;
  19.  
  20. if(Test.isRunningTest()){
  21. throw e;
  22. }else{
  23. return;
  24. }
  25. }
  26.  
  27. //Finished
  28. ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Product import completed.'));
  29. isUploading = false;
  30.  
  31. if(csvFileBody == null){
  32. throw new ProductImportException('No CSV found.');
  33. }
  34.  
  35. //Convert from blob to string
  36. String csvString = csvFileBody.toString();
  37. csvFileBody = null;
  38. csvFileName = null;
  39.  
  40. if(String.isBlank(csvString)){
  41. throw new ProductImportException('Empty CSV found.');
  42. }
  43.  
  44. //Parse CSV into separate fields
  45. List<List<String>> allFields = parseCSV(csvString);
  46.  
  47. if(allFields == null || allFields.isEmpty()){
  48. throw new ProductImportException('Empty CSV found.');
  49. }
  50.  
  51. //Use first line as header
  52. List<String> headerFields = allFields.remove(0);
  53. List<HeaderWrapper> headerList = parseHeaders(headerFields);
  54. List<LineWrapper> lineList = new List<LineWrapper>();
  55.  
  56. //Parse remaining lines
  57. if(allFields == null || allFields.isEmpty()){
  58. throw new ProductImportException('No rows found.');
  59. }else{
  60. for(List<String> line : allFields){
  61. lineList.add(new LineWrapper(line,headerList));
  62. }
  63. }
  64.  
  65. //Get all products
  66. prdctList = new List<Product2>();
  67. for(LineWrapper line : lineList){
  68. prdctList.add(line.prdct);
  69. }
  70.  
  71. //Insert products
  72. try{
  73. insert prdctList;
  74. System.debug(prdctList);
  75. }catch(Exception e){
  76. throw new ProductImportException('Could not insert products. ' + e.getMessage() ,e);
  77. }
  78.  
  79.  
  80. //Insert standard pricebook entries
  81. pbeListStandard = new List<PricebookEntry>();
  82. for(LineWrapper line : lineList){
  83. List<PricebookEntry> l = line.getStandard();
  84. if(l != null){
  85. pbeListStandard.addAll(l);
  86. }
  87. }
  88. try{
  89. if(!pbeListStandard.isEmpty()){
  90. System.debug('* ** *** inserting standard pbe ' + pbeListStandard);
  91. insert pbeListStandard;
  92. System.debug(pbeListStandard);
  93. }
  94. }catch(Exception e){
  95. throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage() ,e);
  96. }
  97.  
  98. //Insert custom pricebook entries
  99. pbeListCustom = new List<PricebookEntry>();
  100. for(LineWrapper line : lineList){
  101. List<PricebookEntry> l = line.getCustom();
  102. if(l != null && !l.isEmpty()){
  103. pbeListCustom.addAll(l);
  104. }
  105. }
  106. try{
  107. if(!pbeListCustom.isEmpty()){
  108. System.debug('* ** *** inserting custom pbe ' + pbeListCustom);
  109. insert pbeListCustom;
  110. System.debug(pbeListCustom);
  111. }
  112. }catch(Exception e){
  113. throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage(),e);
  114. }
  115.  
  116. //List of headers
  117. List<HeaderWrapper> headerList = new List<HeaderWrapper>();
  118.  
  119. //Mapping setting
  120. Map<String,ProductImportMapping__mdt> pim = new Map<String,ProductImportMapping__mdt>();
  121. for(ProductImportMapping__mdt p : [SELECT MasterLabel, Field__c, isProductField__c, Pricebook__c, Isocode__c FROM ProductImportMapping__mdt]){
  122. pim.put(p.MasterLabel,p);
  123. }
  124.  
  125. //Field types
  126. Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Product2.fields.getMap();
  127.  
  128. //Pricebooks
  129. Map<Id,Pricebook2> pbMap = new Map<Id,Pricebook2>([SELECT Id FROM Pricebook2 WHERE IsStandard = false]);
  130.  
  131. Id pbStandard;
  132. if(Test.isRunningTest()){
  133. pbStandard = Test.getStandardPricebookId();
  134. }else{
  135. List<Pricebook2> pbStandardList = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
  136. if(pbStandardList == null || pbStandardList.isEmpty()){
  137. throw new ProductImportException('Could not find standard pricebook.');
  138. }else{
  139. pbStandard = pbStandardList.get(0).Id;
  140. }
  141. }
  142.  
  143. //Map header
  144. for(String field : headerFields){
  145.  
  146. //Get custom setting
  147. ProductImportMapping__mdt setting = pim.get(field);
  148. HeaderWrapper header;
  149.  
  150. if(setting != null){
  151. if(setting.isProductField__c){
  152.  
  153. //check that field is valid and creatable
  154. if(fieldMap.containsKey(setting.Field__c.toLowerCase()) && fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().isCreateable()){
  155.  
  156. //create header wrapper
  157. header = new HeaderWrapper();
  158. header.name = field;
  159. header.field = setting.Field__c;
  160. header.isProductField = true;
  161. header.isSkip = false;
  162. header.type = String.valueOf(fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().getType());
  163.  
  164. }else{
  165.  
  166. //skip header wrapper if no field
  167. header = new HeaderWrapper();
  168. header.isSkip = true;
  169.  
  170. }
  171.  
  172. }else{
  173.  
  174. //check that pricebook is valid
  175. Id pbId;
  176. try{
  177. pbId = Id.valueOf(setting.Pricebook__c);
  178. }catch(Exception e){
  179. throw new ProductImportException('Could not convert pricebook Id.', e);
  180. }
  181. if(!pbMap.containsKey(pbId)){
  182. throw new ProductImportException('Id is not a custom pricebook Id');
  183. }
  184.  
  185.  
  186. //create header wrapper
  187. header = new HeaderWrapper();
  188. header.name = field;
  189. header.isProductField = false;
  190. header.pricebook = setting.Pricebook__c;
  191. header.standard = pbStandard;
  192. header.isocode = setting.Isocode__c;
  193. header.isSkip = false;
  194.  
  195. }
  196. }else{
  197. //skip header wrapper
  198. header = new HeaderWrapper();
  199. header.isSkip = true;
  200. }
  201.  
  202. //add to list
  203. headerList.add(header);
  204.  
  205. }//end-for
  206.  
  207. return headerList;
  208.  
  209. contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
  210. contents = contents.replaceAll('""','DBLQT');
  211. List<String> lines = new List<String>();
  212. try {
  213. lines = contents.split('n');
  214. } catch (Exception e) {
  215. throw new ProductImportException('Could not split CSV.', e);
  216. }
  217.  
  218. Integer num = 0;
  219. for(String line : lines) {
  220. // check for blank CSV lines (only commas)
  221. if (line.replaceAll(',','').trim().length() == 0) break;
  222.  
  223.  
  224. line = line.replaceAll('r','').trim();
  225.  
  226. List<String> fields = line.split(',');
  227. List<String> cleanFields = new List<String>();
  228. String compositeField;
  229. Boolean makeCompositeField = false;
  230. for(String field : fields) {
  231. if (field.startsWith('"') && field.endsWith('"')) {
  232. cleanFields.add(field.replaceAll('DBLQT','"'));
  233. } else if (field.startsWith('"')) {
  234. makeCompositeField = true;
  235. compositeField = field;
  236. } else if (field.endsWith('"')) {
  237. compositeField += ',' + field;
  238. cleanFields.add(compositeField.replaceAll('DBLQT','"'));
  239. makeCompositeField = false;
  240. } else if (makeCompositeField) {
  241. compositeField += ',' + field;
  242. } else {
  243. cleanFields.add(field.replaceAll('DBLQT','"'));
  244. }
  245. }
  246.  
  247. allFields.add(cleanFields);
  248. }
  249.  
  250. return allFields;
  251.  
  252. public LineWrapper(List<String> fields, List<HeaderWrapper> headerList){
  253.  
  254. System.debug('* ** *** fieldsize: ' + fields.size() + '. headersize: ' + headerList.size());
  255.  
  256. //Loop through every cell in row
  257. for(Integer ctr = 0; ctr < fields.size() && ctr < headerList.size(); ctr++){
  258.  
  259. //Get value of cell and header
  260. String field = fields.get(ctr);
  261. HeaderWrapper header = headerList.get(ctr);
  262.  
  263. System.debug('LineWrapper #' + ctr + ': "' + field + '" ' + header);
  264.  
  265. if(header == null || header.isSkip){
  266. //Do nothing
  267. System.debug('* ** *** skip');
  268. }else if(header.isProductField && field == null){
  269.  
  270. //Field name is required
  271. throw new ProductImportException('Could not identify field for line: ' + fields);
  272.  
  273. }else if(header.isProductField && field != null){
  274.  
  275. //Create product
  276. if(this.prdct == null){
  277. this.prdct = new Product2();
  278. }
  279.  
  280. //Set value of field depending on type
  281. try{
  282. if(header.type == 'BOOLEAN'){
  283. this.prdct.put(header.field,Boolean.valueOf(field));
  284. }else if(header.type == 'DATETIME'){
  285. this.prdct.put(header.field,DateTime.valueOf(field));
  286. }else if(header.type == 'DOUBLE'){
  287. this.prdct.put(header.field,Double.valueOf(field));
  288. }else if(header.type == 'BOOLEAN'){
  289. this.prdct.put(header.field,Boolean.valueOf(field));
  290. }else if(header.type == 'REFERENCE'){
  291. this.prdct.put(header.field,Id.valueOf(field));
  292. }else{
  293. this.prdct.put(header.field,field);
  294. }
  295. }catch(Exception e){
  296. throw new ProductImportException('Could not populate field ' + header.field + ' with ' + field);
  297. }
  298.  
  299. }else if(String.isBlank(header.isocode) || header.pricebook == null){
  300.  
  301. //Pricebook and isocode mapping required
  302. throw new ProductImportException('Could not identify pricebook and currency for line: ' + fields);
  303.  
  304. }else{
  305. Decimal price = Decimal.valueOf(field);
  306.  
  307. //Create custom pricebook entry
  308. PricebookEntry pbe = new PricebookEntry(Pricebook2Id = header.pricebook, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode);
  309.  
  310.  
  311. //Create standard pricebook entry
  312. if(!pbeStandard.containsKey(header.isocode)){
  313. pbeStandard.put(header.isocode,new PricebookEntry(Pricebook2Id = header.standard, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode));
  314.  
  315. //Set custom to use standard
  316. pbe.UseStandardPrice = true;
  317. }
  318.  
  319. //Add custom pricebook entry to list
  320. this.pbeCustom.add(pbe);
  321.  
  322. }//end if-else
  323.  
  324. }//end for
  325.  
  326. }//end constructor
  327.  
  328. public List<PricebookEntry> getStandard(){
  329. for(PricebookEntry pbe : pbeStandard.values()){
  330. pbe.Product2Id = prdct.Id;
  331. }
  332. return pbeStandard.values();
  333. }
  334.  
  335. public List<PricebookEntry> getCustom(){
  336. for(PricebookEntry pbe : pbeCustom){
  337. pbe.Product2Id = prdct.Id;
  338. }
  339.  
  340. return pbeCustom;
  341. }
  342.  
  343. @isTest
  344.  
  345. Product2 prdctlist = new Product2(Name = 'Test Product004', ProductCode = 'Test Product004');
  346. insert prdctlist;
  347.  
  348. Pricebook2 pbeListStandard = new Pricebook2(Name = 'Test Pricebook', Description = 'Test Pricebook',CurrencyIsoCode = 'USD',IsActive = true);
  349. insert pbeListStandard;
  350. Pricebook2 pbeListCustom = new Pricebook2(Name = 'Test Pricebook', Description = 'Test Pricebook',CurrencyIsoCode = 'USD',IsActive = true);
  351. insert pbeListCustom;
  352.  
  353.  
  354. //ApexPages.StandardController controller = new ApexPages.standardController(testProduct);
  355. ProductImportController scontroller = new ProductImportController();
  356.  
  357.  
  358. //blob csvFileBody;
  359. scontroller.csvFileName = 'Test Product';
  360. scontroller.csvFileBody = Blob.valueOf('Test AttachmentBody');
  361. scontroller.upload();
  362.  
  363.  
  364. //scontroller.parseCsvInsertProductsPricebooks();
  365.  
  366.  
  367.  
  368. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement