Advertisement
Guest User

Untitled

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