eiru_reporting.js 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722
  1. "use strict";
  2. openerp.eiru_reporting = function (instance, local) {
  3. var QWeb = instance.web.qweb;
  4. var number= instance.web;
  5. local.ReportingWidget = instance.Widget.extend({
  6. template: 'EiruReporting',
  7. events: {
  8. 'click .report_action > button': 'clickOnReport',
  9. },
  10. reports: [
  11. {
  12. title: 'Resumen de ingresos',
  13. description: 'Permite visualizar de forma global los ingresos obtenidos por la empresa.',
  14. action: 'ReportResumenIngreso'
  15. },
  16. {
  17. title: 'Resumen de egresos',
  18. description: 'Permite visualizar de forma global los egresos realizado por la empresa.',
  19. action: 'ReportResumenEngreso'
  20. },
  21. {
  22. title: 'Utilidad de facturas detalladas',
  23. description: 'Permite visualizar la ganancia de cada ítem de las facturas detalladamente.',
  24. action: 'ReportInvoiceUtility'
  25. },
  26. {
  27. title: 'Histórico de compras',
  28. description: 'Permite visualizar un histórico de compras realizado por la empresa.',
  29. action: 'AllPurchases'
  30. },
  31. {
  32. title: 'Histórico de gastos',
  33. description: 'Permite visualizar un histórico de gastos realizado por la empresa.',
  34. action: 'ReposrtExpenses'
  35. },
  36. {
  37. title: 'Listado de productos por ubicación',
  38. description: 'Permite visualizar un listado de productos activos.',
  39. action: 'ReportStockLocation'
  40. }
  41. ],
  42. start: function () {
  43. },
  44. clickOnReport: function (e) {
  45. var templateName = this.$el.find(e.target).val();
  46. this.renderReport(templateName);
  47. },
  48. renderReport: function (templateName) {
  49. var Widget = this.getWidgetFromTemplate(templateName);
  50. var WidgetInstance = new Widget(this);
  51. var container = this.$el.find('.oe_form_sheet.oe_form_sheet_width');
  52. container.find('.report_view').hide({
  53. effect: 'fade',
  54. duration: 200,
  55. complete: function () {
  56. WidgetInstance.appendTo(container);
  57. }
  58. });
  59. },
  60. getWidgetFromTemplate: function (templateName) {
  61. var widgetName = `${templateName}Widget`;
  62. return _.pick(local, widgetName)[widgetName];
  63. },
  64. });
  65. // InvoiceUtility
  66. local.ReportInvoiceUtilityWidget = instance.Widget.extend({
  67. template: 'ReportInvoiceUtility',
  68. invoices: [],
  69. invoiceLines: [],
  70. productProduct:[],
  71. Currency:[],
  72. rowsData :[],
  73. rowOrigin:[],
  74. accountJournal:[],
  75. resCompany:[],
  76. events:{
  77. 'click #toolbar > button' : 'clickOnAction',
  78. 'change #current-journal': 'fectSearch',
  79. 'change #from' : 'fectSearch',
  80. 'change #to': 'fectSearch',
  81. 'click #volver_btn': 'volver',
  82. },
  83. init : function(parent){
  84. this._super(parent);
  85. },
  86. start: function () {
  87. var table = this.$el.find('#table');
  88. table.bootstrapTable({data : self.rowOrigin});
  89. this.fecthFecha();
  90. this.submitForm();
  91. },
  92. // volver
  93. volver: function(){
  94. this.$el.find('#volver').empty();
  95. this.$el.find('#grafico').empty();
  96. this.$el.find('.bootstrap-table').show({
  97. effect: 'drop',
  98. direction: 'down',
  99. duration: 200,
  100. });
  101. },
  102. // Cansultar
  103. submitForm: function () {
  104. var self = this;
  105. this.fetchCurency().then(function(Currency) {
  106. self.Currency = Currency;
  107. return Currency;
  108. }).then(function (Currency) {
  109. return self.fetchJournal();
  110. }).then(function (journal) {
  111. self.accountJournal =journal;
  112. self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
  113. _.each(journal, function (item) {
  114. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  115. });
  116. return self.fetchInvoiceV2();
  117. }).then(function (invoices){
  118. self.invoices = invoices;
  119. return self.fetchInvoiceLine(invoices);
  120. }).then(function (invoiceLines) {
  121. self.invoiceLines = invoiceLines;
  122. return self.fecthProduct(invoiceLines);
  123. }).then(function(productProduct){
  124. self.productProduct = productProduct;
  125. return self.fecthComanyCurrency();
  126. }).then(function(resCompany){
  127. self.resCompany = resCompany;
  128. return self.invoice_Currency();
  129. });
  130. },
  131. // company_curency
  132. fecthComanyCurrency: function(){
  133. var self = this;
  134. var defer = $.Deferred();
  135. var currency = new instance.web.Model('res.company');
  136. var field=['id', 'currency_id'];
  137. var domain=[['id','=',1]];
  138. currency.query(field).filter(domain).all().then(function(results){
  139. defer.resolve(results);
  140. });
  141. return defer;
  142. },
  143. // Fecha
  144. fecthFecha: function() {
  145. var to;
  146. var dateFormat1 = "mm/dd/yy",
  147. from = $( "#from" )
  148. .datepicker({
  149. dateFormat: "dd/mm/yy",
  150. changeMonth: true,
  151. numberOfMonths: 1,
  152. })
  153. .on( "change", function() {
  154. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  155. });
  156. to = $( "#to" ).datepicker({
  157. dateFormat: "dd/mm/yy",
  158. defaultDate: "+7d",
  159. changeMonth: true,
  160. numberOfMonths: 1,
  161. })
  162. .on( "change", function() {
  163. from.datepicker( "option", "maxDate", getDate(this));
  164. });
  165. function getDate( element ) {
  166. var fechaSel =element.value.split('/');
  167. var date;
  168. try {
  169. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  170. } catch( error ) {
  171. date = null;
  172. }
  173. return date;
  174. }
  175. },
  176. // Buscar Diario
  177. fetchJournal: function () {
  178. var self = this;
  179. var defer = $.Deferred();
  180. var Journal = new instance.web.Model('account.journal');
  181. Journal.query(['id', 'name']).filter([['type', '=', 'sale'], ['active', '=', true]]).all().then(function (results) {
  182. defer.resolve(results);
  183. });
  184. return defer;
  185. },
  186. // Buscar Cambio de Monedas USD,PYG,ARG,BRL
  187. fetchCurency: function () {
  188. var defer = $.Deferred();
  189. var currency_Rate = new instance.web.Model('res.currency.rate');
  190. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  191. var domain = [['currency_id', '=', [166 , 20, 7, 3]]];
  192. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  193. defer.resolve(results);
  194. });
  195. return defer;
  196. },
  197. // Invoice (FACTURAS)
  198. fetchInvoiceV2: function () {
  199. var filter ="[['state', '=',['open','paid']],['type', '=', 'out_invoice']";
  200. var journal_ids = _.flatten(_.map(this.accountJournal, function (item) {
  201. return item.id;
  202. }));
  203. if (journal_ids){
  204. filter=filter.concat(",['journal_id', '=',["+journal_ids+"]]");
  205. }
  206. filter=filter.concat("]");
  207. var field =['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'invoice_line','date_invoice'];
  208. var defer = $.Deferred();
  209. var Invoice = new instance.web.Model('account.invoice');
  210. Invoice.query(field).filter(filter).all().then(function (results) {
  211. defer.resolve(results);
  212. });
  213. return defer;
  214. },
  215. // Invoice line (Linea de Factura)
  216. fetchInvoiceLine: function (invoices) {
  217. var defer = $.Deferred();
  218. var linesIds = _.flatten(_.map(invoices, function (item) {
  219. return item.invoice_line;
  220. }));
  221. var InvoiceLine = new instance.web.Model('account.invoice.line');
  222. InvoiceLine.query(['id', 'quantity', 'price_unit', 'discount', 'name', 'product_id', 'origin','invoice_id']).filter([['id', 'in', linesIds]]).all().then(function (results) {
  223. defer.resolve(results)
  224. });
  225. return defer;
  226. },
  227. // Product Product
  228. fecthProduct: function(invoiceLines){
  229. var defer = $.Deferred();
  230. var porductIDS = _.flatten(_.map(invoiceLines, function (item) {
  231. return item.product_id[0];
  232. }));
  233. var ProductProdcut = new instance.web.Model('product.product');
  234. var fields = ['id', 'default_code', 'name_template', 'factory_code', 'factory_reference', 'factory_barcode', 'standard_price','type'];
  235. ProductProdcut.query(fields).filter([['id', 'in', porductIDS]]).all().then(function (results) {
  236. defer.resolve(results)
  237. });
  238. return defer;
  239. },
  240. // Obtener Monedas de la Factura
  241. getCutrrency: function (id){
  242. return _.find(this.Currency,function (curr) {
  243. return _.contains(curr.currency_id,id);
  244. });
  245. },
  246. // Actualizar cambio de las moneda de Factura
  247. invoice_Currency: function(){
  248. for (var i = 0; i < this.invoices.length; i++) {
  249. var currency_new;
  250. var item = this.invoices[i];
  251. var id = item.currency_id[0];
  252. currency_new = this.getCutrrency(id);
  253. if (!currency_new){
  254. currency_new={};
  255. currency_new.rate=1;
  256. }
  257. this.invoices[i].rate=(currency_new.rate);
  258. }
  259. return this.fectUtility();
  260. },
  261. // Obtener la Detalles de la Factura
  262. getInvoice: function (id_line){
  263. return _.find(this.invoices, function (inv) {
  264. return _.contains(inv.invoice_line, id_line);
  265. });
  266. },
  267. // Obtener las lineas de las Facturas
  268. getProduct: function(pro_id){
  269. return _.find(this.productProduct, function(prod){
  270. return _.contains(pro_id, prod.id);
  271. });
  272. },
  273. // unir los objetos
  274. fectUtility: function(){
  275. var data=[];
  276. var item;
  277. var invoice;
  278. var producto;
  279. for (var i = 0; i < this.invoiceLines.length; i++) {
  280. item = this.invoiceLines[i];
  281. invoice = this.getInvoice(item.id);
  282. producto =this.getProduct(item.product_id);
  283. if (!producto){
  284. producto={};
  285. producto.standard_price=0;
  286. }
  287. if (producto.type =="product"){
  288. data.push({
  289. number : (invoice.number),
  290. name : (item.name),
  291. quantity : accounting.formatNumber((item.quantity),0, ".", ","),
  292. price_unity : accounting.formatNumber((item.price_unit / invoice.rate),2, ".", ","),
  293. standar_price : accounting.formatNumber((producto.standard_price),2, ".", ","),
  294. price_tot : accounting.formatNumber((item.quantity * (item.price_unit / invoice.rate)),2, ".", ","),
  295. standar_tot : accounting.formatNumber((item.quantity * producto.standard_price),2, ".", ","),
  296. utility : accounting.formatNumber(((item.quantity * (item.price_unit / invoice.rate)) - (item.quantity * producto.standard_price)),2, ".", ","),
  297. journal_id :(invoice.journal_id[0]),
  298. journal_name :(invoice.journal_id[1]),
  299. date_invoice : (invoice.date_invoice),
  300. });
  301. }
  302. }
  303. this.rowsData=data;
  304. this.rowOrigin=data;
  305. this.loadTable(data)
  306. },
  307. // Buscar
  308. fectSearch: function(){
  309. var self = this;
  310. var desde =this.$el.find('#from').val();
  311. var hasta =this.$el.find('#to').val();
  312. var suc =this.$el.find('#current-journal').val();
  313. self.rowsData=self.rowOrigin;
  314. if (suc != 9999999){
  315. self.rowsData=_.filter(self.rowsData, function (inv){ return inv.journal_id == suc});
  316. }
  317. if (desde){
  318. var date= desde.split('/')
  319. self.rowsData=_.filter(self.rowsData, function (inv){
  320. return inv.date_invoice >= (date[2]+"-"+date[1]+"-"+date[0])
  321. });
  322. }
  323. if (hasta){
  324. var date= hasta.split('/')
  325. self.rowsData=_.filter(self.rowsData, function (inv){
  326. return inv.date_invoice <= (date[2]+"-"+date[1]+"-"+date[0])
  327. });
  328. }
  329. self.loadTable(self.rowsData);
  330. },
  331. // cargara la tabla
  332. loadTable:function(rowsTable){
  333. var table = this.$el.find('#table');
  334. table.bootstrapTable('load', rowsTable);
  335. },
  336. // imprimir PDF
  337. clickOnAction: function (e) {
  338. var action = this.$el.find(e.target).val();
  339. var self = this;
  340. var getColumns=[];
  341. var rows=[];
  342. var table = this.$el.find("#table");
  343. var data2 = table.bootstrapTable('getVisibleColumns');
  344. if (action === 'pdf') {
  345. var dataNEW = _.map(data2, function (val){ return val.field});
  346. _.each(this.rowsData,function (item){
  347. rows.push(_.pick(item, dataNEW));
  348. });
  349. // Obtener los nombre de la Cabezera
  350. _.each(_.map(data2,function(val){
  351. return val}), function(item){
  352. getColumns.push([{
  353. title: item.title,
  354. dataKey: item.field
  355. }]);
  356. });
  357. // Llamar al pdf
  358. this.drawPDF(_.flatten(getColumns),rows)
  359. }
  360. if (action === 'chart'){
  361. var suc =this.$el.find('#current-journal').val();
  362. if (suc == 9999999){
  363. self.fectCharFilter();
  364. }else{
  365. $("#dialog" ).dialog({
  366. autoOpen: true,
  367. resizable: false,
  368. modal: true,
  369. title: 'Atención',
  370. open: function() {
  371. $(this).html('Para Generar el Gráfico debes Seleccionar todas las Sucursales');
  372. },
  373. show: {
  374. effect: "shake",
  375. duration: 300
  376. },
  377. hide: {
  378. effect: "fade",
  379. duration: 300
  380. },
  381. buttons: {
  382. Aceptar: function() {
  383. $(this).dialog('close');
  384. }
  385. }
  386. });
  387. }
  388. }
  389. },
  390. // Generar pdfDoc
  391. drawPDF: function (getColumns,rows) {
  392. var self = this;
  393. var rowsPdf=[];
  394. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  395. var desde =(this.$el.find('#from').val());
  396. var hasta =(this.$el.find('#to').val());
  397. var totalPagesExp = "{total_pages_count_string}";
  398. var pdfDoc = new jsPDF();
  399. // rows=this.rowsData;
  400. var quantity=_.reduce(_.map(rows,function(item){
  401. var valor=0;
  402. if (item.quantity){valor = parseFloat(((item.quantity.replace(".","")).replace(",",".")))}return valor}), function(memo, num){ return memo + num; },0);
  403. var precio_unit=_.reduce(_.map(rows,function(item){
  404. var valor =0;
  405. if (item.price_unity){valor=parseFloat(((item.price_unity.replace(".","")).replace(",",".")))} return valor}), function(memo, num){ return memo + num; },0);
  406. var precio_cost=_.reduce(_.map(rows,function(item){
  407. var valor=0;
  408. if(item.standar_price){valor=parseFloat(((item.standar_price.replace(".","")).replace(",",".")))} return valor}), function(memo, num){ return memo + num;},0);
  409. var tot_unit=_.reduce(_.map(rows,function(item){
  410. var valor=0;
  411. if (item.price_tot){valor=parseFloat(((item.price_tot.replace(".","")).replace(",",".")))}return valor}), function(memo, num){ return memo + num; },0);
  412. var tol_cost=_.reduce(_.map(rows,function(item){
  413. var valor=0;
  414. if (item.standar_tot){valor=parseFloat(((item.standar_tot.replace(".","")).replace(",",".")))} return valor }), function(memo, num){ return memo + num; },0);
  415. var utility=_.reduce(_.map(rows,function(item){
  416. var valor=0;
  417. if (item.utility){valor=parseFloat(((item.utility.replace(".","")).replace(",",".")))}return valor }), function(memo, num){ return memo + num; },0);
  418. rowsPdf=rows;
  419. var company = _.map(self.resCompany, function (map) {
  420. return map.currency_id[1];
  421. });
  422. rowsPdf.push({
  423. number : " ",
  424. name : "TOTAL "+company,
  425. quantity: accounting.formatNumber(quantity,0, ".", ","),
  426. price_unity : accounting.formatNumber(precio_unit,2, ".", ","),
  427. standar_price : accounting.formatNumber(precio_cost,2, ".", ","),
  428. price_tot : accounting.formatNumber(tot_unit,2, ".", ","),
  429. standar_tot : accounting.formatNumber(tol_cost,2, ".", ","),
  430. utility : accounting.formatNumber(utility,2, ".", ",")
  431. });
  432. rowsPdf.unshift({
  433. number : " ",
  434. name : "TOTAL "+company,
  435. quantity: accounting.formatNumber(quantity,0, ".", ","),
  436. price_unity : accounting.formatNumber(precio_unit,2, ".", ","),
  437. standar_price : accounting.formatNumber(precio_cost,2, ".", ","),
  438. price_tot : accounting.formatNumber(tot_unit,2, ".", ","),
  439. standar_tot : accounting.formatNumber(tol_cost,2, ".", ","),
  440. utility : accounting.formatNumber(utility,2, ".", ",")
  441. });
  442. pdfDoc.autoTable(getColumns, rowsPdf, {
  443. styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
  444. columnStyles: {
  445. number: {fontStyle: 'bold'},
  446. name :{columnWidth: '10px'},
  447. quantity :{halign:'right' },
  448. price_unity : {halign:'right' },
  449. standar_price : {halign:'right' },
  450. price_tot : {halign:'right' },
  451. standar_tot : {halign:'right' },
  452. utility : {halign:'right'},
  453. },
  454. margin: { top: 16, horizontal: 7},
  455. addPageContent: function (data) {
  456. pdfDoc.setFontSize(12);
  457. pdfDoc.setFontStyle('bold');
  458. pdfDoc.setTextColor(40);
  459. pdfDoc.text('Utilidad de facturas detalladas por '+ sucusal, data.settings.margin.left, 10);
  460. if(desde.length > 0 || hasta.length > 0){
  461. var fecha='';
  462. if(desde){
  463. fecha=fecha.concat(' Desde '+desde);
  464. }
  465. if (hasta){
  466. fecha=fecha.concat(' Hasta '+hasta);
  467. }
  468. pdfDoc.setFontSize(10);
  469. pdfDoc.setFontStyle('bold');
  470. pdfDoc.setTextColor(40)
  471. pdfDoc.text(fecha, data.settings.margin.left,14);
  472. }
  473. // FOOTER
  474. var str = "Pagina " + data.pageCount;
  475. // Total page number plugin only available in jspdf v1.0+
  476. if (typeof pdfDoc.putTotalPages === 'function') {
  477. str = str + " de " + totalPagesExp;
  478. }
  479. pdfDoc.setFontSize(9);
  480. pdfDoc.setFontStyle('bold');
  481. pdfDoc.setTextColor(40);
  482. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  483. }
  484. });
  485. if (typeof pdfDoc.putTotalPages === 'function') {
  486. pdfDoc.putTotalPages(totalPagesExp);
  487. }
  488. pdfDoc.save('Utilidad de facturas detalladas.pdf')
  489. },
  490. // Chart Filter
  491. fectCharFilter: function(){
  492. var self = this;
  493. var dataBody=[];
  494. var dataHeader=[];
  495. var canvas="<canvas id='graf_resume'></canvas>";
  496. this.$el.find('#grafico').append(canvas);
  497. _.each(self.accountJournal, function(journal){
  498. dataHeader.push(journal.name);
  499. var utility=_.reduce(_.map(_.filter(self.rowsData, function (inv){ return inv.journal_id == journal.id}),function(item){
  500. return parseFloat(((item.utility.replace(".","")).replace(",",".")))}), function(memo, num){ return memo + num; },0);
  501. dataBody.push(accounting.toFixed((utility),2));
  502. });
  503. var selector ="<button type='button' class='oe_button oe_form_button oe_highlight' id='volver_btn' name='volver_btn'><span>Atras</span></button>";
  504. this.$el.find('#volver').append(selector);
  505. this.$el.find('.bootstrap-table').hide({
  506. effect: 'drop',
  507. direction: 'up',
  508. duration: 200,
  509. complete: function () {
  510. self.drawChart(dataHeader,dataBody);
  511. }
  512. });
  513. },
  514. // Chart
  515. drawChart: function (dataHeader,dataBody) {
  516. var barChart = new Chart(this.$el.find('#graf_resume'), {
  517. type: 'doughnut',
  518. data: {
  519. labels: dataHeader,
  520. datasets: [
  521. {
  522. labels: dataHeader,
  523. backgroundColor: [
  524. 'rgba(255, 99, 132, 0.2)',
  525. 'rgba(54, 162, 235, 0.2)',
  526. 'rgba(255, 206, 86, 0.2)',
  527. 'rgba(75, 192, 192, 0.2)',
  528. 'rgba(153, 102, 255, 0.2)',
  529. ],
  530. borderColor: [
  531. 'rgba(255,99,132,1)',
  532. 'rgba(54, 162, 235, 1)',
  533. 'rgba(255, 206, 86, 1)',
  534. 'rgba(75, 192, 192, 1)',
  535. 'rgba(153, 102, 255, 1)',
  536. ],
  537. borderWidth: 1,
  538. data: dataBody,
  539. }
  540. ]
  541. },
  542. options: {
  543. maintainAspectRatio: false,
  544. layout: {
  545. padding: 30
  546. }
  547. },
  548. });
  549. },
  550. });
  551. // ResumenEngreso
  552. local.ReportResumenEngresoWidget = instance.Widget.extend({
  553. template :'ReportResumenEngreso',
  554. accountVoucher:[],
  555. resCurrency:[],
  556. accountJournal:[],
  557. dataVoucher:[],
  558. currencyRate:[],
  559. companyCurrency:[],
  560. modules:[],
  561. events:{
  562. 'click #toolbar > button' : 'clickOnAction',
  563. 'change #current-journal': 'fectSearch',
  564. 'change #current-currency': 'fectSearch',
  565. 'change #from' : 'fectSearch',
  566. 'change #to': 'fectSearch',
  567. 'click #volver_btn': 'volver',
  568. },
  569. init:function(parent){
  570. this._super(parent);
  571. },
  572. start: function(){
  573. var self = this;
  574. var table = this.$el.find('#table');
  575. table.bootstrapTable({data : self.dataVoucher});
  576. self.fecthFecha();
  577. self.fecthInitial();
  578. },
  579. // Redirecionar
  580. // renderReport: function () {
  581. // var self = this;
  582. //
  583. // var container = this.$el.closest('.oe_form_sheet.oe_form_sheet_width');
  584. // this.$el.closest('.report_view').remove();
  585. // container.find('.report_view').show({
  586. // effect: 'fade',
  587. // duration: 200,
  588. // });
  589. // },
  590. // // Verificar el modelo
  591. // checkModel : function(model){
  592. // var self = this;
  593. // return _.filter(self.modules,function(item){return item === model});
  594. // },
  595. // // Lanzar el mensaje
  596. // showMensaje : function(modelos){
  597. // $("#dialog" ).dialog({
  598. // autoOpen: true,
  599. // resizable: false,
  600. // modal: true,
  601. // title: 'Atención',
  602. // width: 500,
  603. // open: function() {
  604. // $(this).html('Lo sentimos , pero no contás con las configuraciones adecuado para manipular este informe.\nPóngase en contacto con el administrador del sistema (referencia : '+modelos+' )');
  605. // },
  606. // show: {
  607. // effect: "fade",
  608. // duration: 200
  609. // },
  610. // hide: {
  611. // effect: "fade",
  612. // duration: 200
  613. // },
  614. // buttons: {
  615. // Aceptar: function() {
  616. // $(this).dialog('close');
  617. // }
  618. // }
  619. // });
  620. // return
  621. // },
  622. // Fecha
  623. fecthFecha: function() {
  624. var to;
  625. var dateFormat1 = "mm/dd/yy",
  626. from = $( "#from" ).datepicker({
  627. dateFormat: "dd/mm/yy",
  628. changeMonth: true,
  629. numberOfMonths: 1,
  630. })
  631. .on( "change", function() {
  632. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  633. });
  634. to = $( "#to" ).datepicker({
  635. dateFormat: "dd/mm/yy",
  636. defaultDate: "+7d",
  637. changeMonth: true,
  638. numberOfMonths: 1,
  639. })
  640. .on( "change", function() {
  641. from.datepicker( "option", "maxDate", getDate(this));
  642. });
  643. function getDate( element ) {
  644. var fechaSel =element.value.split('/');
  645. var date;
  646. try {
  647. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  648. } catch( error ) {
  649. date = null;
  650. }
  651. return date;
  652. }
  653. },
  654. // Metodo inicial
  655. fecthInitial: function(){
  656. var self = this;
  657. // self.modules = instance._modules;
  658. self.fecthJournalStore().then(function(accountJournal){
  659. self.accountJournal=accountJournal;
  660. return accountJournal;
  661. }).then(function(accountJournal){
  662. self.$el.find('#current-journal').append('<option value="9999999">Todas las SUC.</option>');
  663. _.each(accountJournal,function(item){
  664. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  665. });
  666. return self.fecthCurrency();
  667. }).then(function(resCurrency){
  668. self.$el.find('#current-currency').append('<option value="999">Todas las Monedas</option>');
  669. _.each(resCurrency,function(item){
  670. self.$el.find('#current-currency').append('<option value="'+item.id+'">'+item.name +' '+item.symbol+'</option>');
  671. });
  672. self.resCurrency =resCurrency;
  673. return self.fecthCurrencyRate();
  674. }).then(function(currencyRate){
  675. self.currencyRate =currencyRate;
  676. return self.fecthVoucher();
  677. }).then(function(accountVoucher){
  678. self.accountVoucher =accountVoucher;
  679. return self.fecthComanyCurrency();
  680. }).then(function(companyCurrency){
  681. self.companyCurrency = companyCurrency;
  682. return self.fecthDataVoucher(self.accountVoucher,self.accountJournal);
  683. });
  684. // return self.renderReport()
  685. },
  686. // Journal
  687. fecthJournalStore: function(){
  688. var self = this;
  689. var defer = $.Deferred();
  690. // var modules = self.checkModel('multi_store');
  691. // if (modules.length <= 0){
  692. // self.showMensaje('multi_store');
  693. // return defer;
  694. // }
  695. var journal = new instance.web.Model('res.store');
  696. var field=['id', 'name','out_invoice_id','journal_ids'];
  697. journal.query(field).order_by('id').all().then(function(results){
  698. defer.resolve(results);
  699. });
  700. return defer;
  701. },
  702. // company_curency
  703. fecthComanyCurrency: function(){
  704. var self = this;
  705. var defer = $.Deferred();
  706. var currency = new instance.web.Model('res.company');
  707. var field=['id', 'currency_id'];
  708. var domain=[['id','=',1]];
  709. currency.query(field).filter(domain).all().then(function(results){
  710. defer.resolve(results);
  711. });
  712. return defer;
  713. },
  714. // Moneda
  715. fecthCurrency:function(){
  716. var self = this;
  717. var defer = $.Deferred();
  718. var currency = new instance.web.Model('res.currency');
  719. var field = ['id', 'name', 'symbol'];
  720. var domain = [['active','=', true]];
  721. currency.query(field).filter(domain).order_by('id').all().then(function(results){
  722. defer.resolve(results);
  723. });
  724. return defer;
  725. },
  726. // Cambio de la moneda
  727. fecthCurrencyRate:function(){
  728. var defer = $.Deferred();
  729. var currency_Rate = new instance.web.Model('res.currency.rate');
  730. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  731. var domain = [['currency_id', '=', [166 , 20, 7, 3]]];
  732. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  733. defer.resolve(results);
  734. });
  735. return defer;
  736. },
  737. // Voucher -
  738. fecthVoucher:function(){
  739. var self= this;
  740. var defer = $.Deferred();
  741. var voucher = new instance.web.Model('account.voucher');
  742. var field = ['id', 'reference', 'number', 'partner_id', 'payment_rate_currency_id', 'currency_id', 'company_id',' state',' pre_line', 'payment_rate', 'type', 'date', 'name', 'journal_id', 'amount'];
  743. var domain =[['type', '=', 'payment']];
  744. voucher.query(field).filter(domain).order_by('id').all().then(function(results){
  745. defer.resolve(results);
  746. });
  747. return defer;
  748. },
  749. // Verificar Valor null
  750. valorNull:function(dato){
  751. var valor ="";
  752. if (dato){
  753. valor=dato;
  754. }
  755. return valor;
  756. },
  757. // Join object
  758. fecthDataVoucher:function(objVoucher,objJournal){
  759. var self=this;
  760. var item;
  761. var journal;
  762. var voucherLine;
  763. var voucherItem;//Contenido del voucher
  764. var sumaAmount; //Guardar la suma de los pagos
  765. var voucherObject=[];
  766. var voucherObjectItem=[];
  767. var cutrrencyRate; //Valor del cambio
  768. var total=0;
  769. var sumaAmountTot=0;
  770. var itemVoucher;
  771. for (var i = 0; i < objJournal.length; i++) {
  772. voucherObjectItem=[];
  773. journal=objJournal[i];
  774. //Generar la Cabezera con el nombre de la sucursal
  775. for (var f = 0; f < journal.journal_ids.length; f++) {
  776. voucherLine = journal.journal_ids[f];
  777. voucherItem = self.getVoucherjournal(objVoucher,voucherLine)
  778. if (voucherItem.length > 0){
  779. sumaAmount=_.reduce(_.map(voucherItem,function(item){return item.amount}), function(memo, num){ return memo + num; },0);
  780. itemVoucher = voucherItem.shift();
  781. cutrrencyRate=self.getCutrrencyRate(itemVoucher.currency_id[0]);
  782. if (!cutrrencyRate){
  783. cutrrencyRate={};
  784. cutrrencyRate.rate=1;
  785. }
  786. // Guardar item
  787. voucherObjectItem.push({ journal : " ",
  788. method :self.valorNull(itemVoucher.journal_id[1]),
  789. amount : accounting.formatNumber(self.valorNull(sumaAmount),2, ".", ","),
  790. currency_name : self.valorNull(itemVoucher.currency_id[0]),
  791. currency_id : self.valorNull(itemVoucher.currency_id[1]),
  792. rate : cutrrencyRate.rate,
  793. amountBase : self.valorNull(sumaAmount / cutrrencyRate.rate),
  794. journal_id: journal.id,
  795. journal_name: journal.name,
  796. graficar: false
  797. })
  798. }
  799. }
  800. if (voucherObjectItem.length > 0){
  801. var company = _.map(self.companyCurrency, function (map) {
  802. return map.currency_id[1];
  803. });
  804. sumaAmountTot=_.reduce(_.map(voucherObjectItem,function(item){return (item.amountBase)}), function(memo, num){ return memo + num; },0);
  805. total=total+sumaAmountTot;
  806. voucherObjectItem.push({journal : " ",
  807. method :"Total " + company,
  808. amount : accounting.formatNumber(self.valorNull(sumaAmountTot),2, ".", ","),
  809. currency_name : "",
  810. currency_id : "",
  811. rate : "cutrrencyRate.rate",
  812. amountBase:"",
  813. journal_id: journal.id,
  814. journal_name: journal.name,
  815. graficar: true
  816. });
  817. // Generarl la Cabezera
  818. voucherObjectItem.unshift({ journal : journal.name, method :"", amount :"", voucherLine_name :"", voucherLine_id :"",rate :"",amountBase :"",journal_id:journal.id, journal_name:journal.name, graficar:false});
  819. // Generar Objeto Principal
  820. voucherObject=voucherObject.concat(voucherObjectItem);
  821. }
  822. }
  823. if (voucherObject.length >0){
  824. voucherObject.push({journal : " Total de Egreso",
  825. method :"",
  826. amount : accounting.formatNumber(self.valorNull(total),2, ".", ","),
  827. currency_name : "",
  828. currency_id : "",
  829. rate : "",
  830. amountBase:"",
  831. journal_id: journal.id,
  832. journal_name: journal.name,
  833. graficar: false
  834. });
  835. }
  836. self.loadTable(voucherObject);
  837. },
  838. // Obtener Voucher
  839. getVoucherjournal:function(objVoucher,journal_id){
  840. return _.map(_.filter(objVoucher, function (inv){return inv.journal_id[0] === journal_id}),function(item){return item});
  841. },
  842. // Obtener Cambio
  843. getCutrrencyRate: function(currency_id){
  844. return _.filter(this.currencyRate, function(rate){return rate.currency_id[0] === currency_id}).shift();
  845. },
  846. // Generar la tabla
  847. loadTable:function(rowsTable){
  848. this.dataVoucher=rowsTable;
  849. var table = this.$el.find('#table');
  850. table.bootstrapTable('load' ,rowsTable);
  851. },
  852. // Buscar
  853. fectSearch: function(){
  854. var self = this;
  855. var desde =this.$el.find('#from').val();
  856. var hasta =this.$el.find('#to').val();
  857. var journal =this.$el.find('#current-journal').val();
  858. var currency =this.$el.find('#current-currency').val();
  859. var newJournal= self.accountJournal; //copia del Diario
  860. var newVoucher= self.accountVoucher; //copia del Vouacher
  861. if (journal != 9999999){
  862. var botonChart =this.$el.find('#chart').attr("disabled", true);
  863. newJournal=_.filter(newJournal, function (inv){ return inv.id == journal});
  864. }else {
  865. var botonChart =this.$el.find('#chart').attr("disabled", false);
  866. }
  867. if(currency != 999){
  868. newVoucher=_.filter(newVoucher, function (inv){ return inv.currency_id[0] == currency});
  869. }
  870. if (desde){
  871. var date= desde.split('/')
  872. newVoucher=_.filter(newVoucher, function (inv){return inv.date >= (date[2]+"-"+date[1]+"-"+date[0])});
  873. }
  874. if (hasta){
  875. var date= hasta.split('/')
  876. newVoucher=_.filter(newVoucher, function (inv){return inv.date <= (date[2]+"-"+date[1]+"-"+date[0])});
  877. }
  878. self.fecthDataVoucher(newVoucher,newJournal);
  879. },
  880. // volver
  881. volver: function(){
  882. this.$el.find('#volver').empty();
  883. this.$el.find('#grafico').empty();
  884. this.$el.find('.bootstrap-table').show({
  885. effect: 'drop',
  886. direction: 'down',
  887. duration: 200,
  888. });
  889. this.$el.find('#toolbar').show({
  890. effect: 'drop',
  891. direction: 'down',
  892. duration: 200,
  893. });
  894. },
  895. // Click pdf -Grafic
  896. clickOnAction: function (e) {
  897. var action = this.$el.find(e.target).val();
  898. var self = this;
  899. var getColumns=[];
  900. var rows=[];
  901. var table = this.$el.find("#table");
  902. var data2 = table.bootstrapTable('getVisibleColumns');
  903. if (action === 'pdf') {
  904. var dataNEW = _.map(data2, function (val){ return val.field});
  905. _.each(this.dataVoucher,function (item){
  906. rows.push(_.pick(item, dataNEW));
  907. });
  908. // Obtener los nombre de la Cabezera
  909. _.each(_.map(data2,function(val){return val}), function(item){
  910. getColumns.push([{title: item.title, dataKey: item.field}]);
  911. });
  912. // Llamar al pdf
  913. this.drawPDF(_.flatten(getColumns),rows)
  914. }
  915. if (action === 'chart'){
  916. var self = this;
  917. var objetChar;
  918. objetChar = _.filter(self.dataVoucher,function(item){return item.graficar === true});
  919. self.fectCharFilter(objetChar);
  920. }
  921. },
  922. // pdfDoc
  923. drawPDF:function(getColumns,rows){
  924. var self = this;
  925. var fechaActu= new Date();
  926. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  927. var desde =(this.$el.find('#from').val());
  928. var hasta =(this.$el.find('#to').val());
  929. var totalPagesExp = "{total_pages_count_string}";
  930. var pdfDoc = new window.jsPDF();
  931. pdfDoc.autoTable(getColumns, rows, {
  932. styles: { overflow: 'linebreak', fontSize:10 , columnWidth: 'wrap'},
  933. columnStyles:{ journal: {fontStyle: 'bold'},
  934. method :{columnWidth: '10px'},
  935. amount : {halign:'right'},
  936. },
  937. margin: { top: 16, horizontal: 7},
  938. addPageContent: function (data) {
  939. pdfDoc.setFontSize(12);
  940. pdfDoc.setFontStyle('bold');
  941. pdfDoc.setTextColor(40);
  942. pdfDoc.text('Resumen de Egreso de '+ sucusal, data.settings.margin.left, 10);
  943. if(desde.length > 0 || hasta.length > 0){
  944. var fecha='';
  945. if(desde){
  946. fecha=fecha.concat(' Desde '+desde);
  947. }
  948. if (hasta){
  949. fecha=fecha.concat(' Hasta '+hasta);
  950. }
  951. pdfDoc.setFontSize(10);
  952. pdfDoc.setFontStyle('bold');
  953. pdfDoc.setTextColor(40)
  954. pdfDoc.text(fecha, data.settings.margin.left,14);
  955. }
  956. // FOOTER
  957. var str = "Pagina " + data.pageCount;
  958. // Total page number plugin only available in jspdf v1.0+
  959. if (typeof pdfDoc.putTotalPages === 'function') {
  960. str = str + " de " + totalPagesExp +"\n Día de Expedición "+fechaActu.getDate()+"/"+fechaActu.getMonth()+"/"+fechaActu.getFullYear();
  961. }
  962. pdfDoc.setFontSize(9);
  963. pdfDoc.setFontStyle('bold');
  964. pdfDoc.setTextColor(40);
  965. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  966. }
  967. });
  968. if (typeof pdfDoc.putTotalPages === 'function') {
  969. pdfDoc.putTotalPages(totalPagesExp);
  970. }
  971. pdfDoc.save('Resumen de Egreso.pdf');
  972. },
  973. // Char filter
  974. fectCharFilter: function(objetChar){
  975. var self = this;
  976. var dataBody=[];
  977. var dataHeader=[];
  978. // objetChar
  979. var canvas="<canvas id='graf_resume'></canvas>";
  980. this.$el.find('#grafico').append(canvas);
  981. _.each(objetChar,function(voucher){
  982. dataHeader.push(voucher.journal_name);
  983. dataBody.push(parseFloat(((voucher.amount.replace(".","")).replace(",","."))));
  984. });
  985. var selector ="<button type='button' class='oe_button oe_form_button oe_highlight' id='volver_btn' name='volver_btn'><span>Atras</span></button>";
  986. this.$el.find('#volver').append(selector);
  987. this.$el.find('.bootstrap-table').hide({
  988. effect: 'drop',
  989. direction: 'up',
  990. duration: 200,
  991. complete: function () {
  992. self.drawChart(dataHeader,dataBody);
  993. }
  994. });
  995. this.$el.find('#toolbar').hide({
  996. effect: 'drop',
  997. direction: 'up',
  998. duration: 200,
  999. complete: function () {
  1000. self.drawChart(dataHeader,dataBody);
  1001. }
  1002. });
  1003. },
  1004. //Chart
  1005. drawChart: function (dataHeader,dataBody) {
  1006. var barChart = new Chart(this.$el.find('#graf_resume'), {
  1007. type: 'doughnut',//bar, doughnut
  1008. data: {
  1009. labels: dataHeader,
  1010. datasets: [
  1011. {
  1012. labels: dataHeader,
  1013. backgroundColor: [
  1014. 'rgba(255, 99, 132, 0.2)',
  1015. 'rgba(54, 162, 235, 0.2)',
  1016. 'rgba(255, 206, 86, 0.2)',
  1017. 'rgba(75, 192, 192, 0.2)',
  1018. 'rgba(153, 102, 255, 0.2)',
  1019. ],
  1020. borderColor: [
  1021. 'rgba(255,99,132,1)',
  1022. 'rgba(54, 162, 235, 1)',
  1023. 'rgba(255, 206, 86, 1)',
  1024. 'rgba(75, 192, 192, 1)',
  1025. 'rgba(153, 102, 255, 1)',
  1026. ],
  1027. borderWidth: 1,
  1028. data: dataBody,
  1029. }
  1030. ]
  1031. },
  1032. options: {
  1033. maintainAspectRatio: false,
  1034. layout: {
  1035. padding: 30
  1036. }
  1037. },
  1038. });
  1039. },
  1040. });
  1041. // ResumenIngreso
  1042. local.ReportResumenIngresoWidget = instance.Widget.extend({
  1043. template :'ReportResumenIngreso',
  1044. accountVoucher:[],
  1045. resCurrency:[],
  1046. accountJournal:[],
  1047. dataVoucher:[],
  1048. currencyRate:[],
  1049. resCompany:[],
  1050. modules:[],
  1051. events:{
  1052. 'click #toolbar > button' : 'clickOnAction',
  1053. 'change #current-journal': 'fectSearch',
  1054. 'change #current-currency': 'fectSearch',
  1055. 'change #from' : 'fectSearch',
  1056. 'change #to': 'fectSearch',
  1057. 'click #volver_btn': 'volver',
  1058. },
  1059. init:function(parent){
  1060. this._super(parent);
  1061. },
  1062. start: function(){
  1063. var self = this;
  1064. var table = this.$el.find('#table');
  1065. table.bootstrapTable({data : self.dataVoucher});
  1066. self.fecthFecha();
  1067. self.fecthInitial();
  1068. },
  1069. // Redirecionar
  1070. // renderReport: function () {
  1071. // var self = this;
  1072. //
  1073. // var container = this.$el.closest('.oe_form_sheet.oe_form_sheet_width');
  1074. // this.$el.closest('.report_view').remove();
  1075. // container.find('.report_view').show({
  1076. // effect: 'fade',
  1077. // duration: 200,
  1078. // });
  1079. // },
  1080. // Verificar el modelo
  1081. // checkModel : function(model){
  1082. // var self = this;
  1083. // return _.filter(self.modules,function(item){return item === model});
  1084. // },
  1085. // // Lanzar el mensaje
  1086. // showMensaje : function(modelos){
  1087. // $("#dialog" ).dialog({
  1088. // autoOpen: true,
  1089. // resizable: false,
  1090. // modal: true,
  1091. // title: 'Atención',
  1092. // width: 500,
  1093. // open: function() {
  1094. // $(this).html('Lo sentimos , pero no contás con las configuraciones adecuado para manipular este informe.\nPóngase en contacto con el administrador del sistema (referencia : '+modelos+' )');
  1095. // },
  1096. // show: {
  1097. // effect: "fade",
  1098. // duration: 200
  1099. // },
  1100. // hide: {
  1101. // effect: "fade",
  1102. // duration: 200
  1103. // },
  1104. // buttons: {
  1105. // Aceptar: function() {
  1106. // $(this).dialog('close');
  1107. // }
  1108. // }
  1109. // });
  1110. // return
  1111. // },
  1112. // Fecha
  1113. fecthFecha: function() {
  1114. var to;
  1115. var dateFormat1 = "mm/dd/yy",
  1116. from = $( "#from" ).datepicker({
  1117. dateFormat: "dd/mm/yy",
  1118. changeMonth: true,
  1119. numberOfMonths: 1,
  1120. })
  1121. .on( "change", function() {
  1122. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  1123. });
  1124. to = $( "#to" ).datepicker({
  1125. dateFormat: "dd/mm/yy",
  1126. defaultDate: "+7d",
  1127. changeMonth: true,
  1128. numberOfMonths: 1,
  1129. })
  1130. .on( "change", function() {
  1131. from.datepicker( "option", "maxDate", getDate(this));
  1132. });
  1133. function getDate( element ) {
  1134. var fechaSel =element.value.split('/');
  1135. var date;
  1136. try {
  1137. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  1138. } catch( error ) {
  1139. date = null;
  1140. }
  1141. return date;
  1142. }
  1143. },
  1144. // Metodo inicial
  1145. fecthInitial: function(){
  1146. var self = this;
  1147. // self.modules = instance._modules;
  1148. self.fecthJournalStore().then(function(accountJournal){
  1149. self.accountJournal=accountJournal;
  1150. return accountJournal;
  1151. }).then(function(accountJournal){
  1152. self.$el.find('#current-journal').append('<option value="9999999">Todas las SUC.</option>');
  1153. _.each(accountJournal,function(item){
  1154. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  1155. });
  1156. return self.fecthCurrency();
  1157. }).then(function(resCurrency){
  1158. self.$el.find('#current-currency').append('<option value="999">Todas las Monedas</option>');
  1159. _.each(resCurrency,function(item){
  1160. self.$el.find('#current-currency').append('<option value="'+item.id+'">'+item.name +' '+item.symbol+'</option>');
  1161. });
  1162. self.resCurrency =resCurrency;
  1163. return self.fecthCurrencyRate();
  1164. }).then(function(currencyRate){
  1165. self.currencyRate =currencyRate;
  1166. return self.fecthVoucher();
  1167. }).then(function(accountVoucher){
  1168. self.accountVoucher =accountVoucher;
  1169. return self.fecthComanyCurrency();
  1170. }).then(function(resCompany){
  1171. self.resCompany = resCompany;
  1172. return self.fecthDataVoucher(self.accountVoucher,self.accountJournal);
  1173. });
  1174. // return self.renderReport();
  1175. },
  1176. // company_curency
  1177. fecthComanyCurrency: function(){
  1178. var self = this;
  1179. var defer = $.Deferred();
  1180. var currency = new instance.web.Model('res.company');
  1181. var field=['id', 'currency_id'];
  1182. var domain=[['id','=',1]];
  1183. currency.query(field).filter(domain).all().then(function(results){
  1184. defer.resolve(results);
  1185. });
  1186. return defer;
  1187. },
  1188. // Journal
  1189. fecthJournalStore: function(){
  1190. var self = this;
  1191. var defer = $.Deferred();
  1192. // var modules = self.checkModel('multi_store');
  1193. //
  1194. // if (modules.length <= 0){
  1195. // self.showMensaje('multi_store');
  1196. // return defer;
  1197. // }
  1198. var journal = new instance.web.Model('res.store');
  1199. var field=['id', 'name','out_invoice_id','journal_ids'];
  1200. journal.query(field).order_by('id').all().then(function(results){
  1201. defer.resolve(results);
  1202. });
  1203. return defer;
  1204. },
  1205. // Moneda
  1206. fecthCurrency:function(){
  1207. var self = this;
  1208. var defer = $.Deferred();
  1209. var currency = new instance.web.Model('res.currency');
  1210. var field = ['id', 'name', 'symbol'];
  1211. var domain = [['active','=', true]];
  1212. currency.query(field).filter(domain).order_by('id').all().then(function(results){
  1213. defer.resolve(results);
  1214. });
  1215. return defer;
  1216. },
  1217. // Cambio de la moneda
  1218. fecthCurrencyRate:function(){
  1219. var defer = $.Deferred();
  1220. var currency_Rate = new instance.web.Model('res.currency.rate');
  1221. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  1222. var domain = [['currency_id', '=', [166 , 20, 7, 3]]];
  1223. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  1224. defer.resolve(results);
  1225. });
  1226. return defer;
  1227. },
  1228. // Voucher -
  1229. fecthVoucher:function(){
  1230. var self= this;
  1231. var defer = $.Deferred();
  1232. var voucher = new instance.web.Model('account.voucher');
  1233. var field = ['id', 'reference', 'number', 'partner_id', 'payment_rate_currency_id', 'currency_id', 'company_id',' state',' pre_line', 'payment_rate', 'type', 'date', 'name', 'journal_id', 'amount'];
  1234. var domain =[['type', '=', 'receipt']];
  1235. voucher.query(field).filter(domain).order_by('id').all().then(function(results){
  1236. defer.resolve(results);
  1237. });
  1238. return defer;
  1239. },
  1240. // Verificar Valor null
  1241. valorNull:function(dato){
  1242. var valor ="";
  1243. if (dato){
  1244. valor=dato;
  1245. }
  1246. return valor;
  1247. },
  1248. // Join object
  1249. fecthDataVoucher:function(objVoucher,objJournal){
  1250. var self=this;
  1251. var item;
  1252. var journal;
  1253. var voucherLine;
  1254. var voucherItem;//Contenido del voucher
  1255. var sumaAmount; //Guardar la suma de los pagos
  1256. var voucherObject=[];
  1257. var voucherObjectItem=[];
  1258. var cutrrencyRate; //Valor del cambio
  1259. var total=0;
  1260. var sumaAmountTot=0;
  1261. var itemVoucher;
  1262. for (var i = 0; i < objJournal.length; i++) {
  1263. voucherObjectItem=[];
  1264. journal=objJournal[i];
  1265. //Generar la Cabezera con el nombre de la sucursal
  1266. for (var f = 0; f < journal.journal_ids.length; f++) {
  1267. voucherLine = journal.journal_ids[f];
  1268. voucherItem = self.getVoucherjournal(objVoucher,voucherLine)
  1269. if (voucherItem.length > 0){
  1270. sumaAmount=_.reduce(_.map(voucherItem,function(item){return item.amount}), function(memo, num){ return memo + num; },0);
  1271. itemVoucher = voucherItem.shift();
  1272. cutrrencyRate=self.getCutrrencyRate(itemVoucher.currency_id[0]);
  1273. if (!cutrrencyRate){
  1274. cutrrencyRate={};
  1275. cutrrencyRate.rate=1;
  1276. }
  1277. // Guardar item
  1278. voucherObjectItem.push({ journal : " ",
  1279. method :self.valorNull(itemVoucher.journal_id[1]),
  1280. amount : accounting.formatNumber(self.valorNull(sumaAmount),2, ".", ","),
  1281. currency_name : self.valorNull(itemVoucher.currency_id[0]),
  1282. currency_id : self.valorNull(itemVoucher.currency_id[1]),
  1283. rate : cutrrencyRate.rate,
  1284. amountBase : self.valorNull(sumaAmount / cutrrencyRate.rate),
  1285. journal_id: journal.id,
  1286. journal_name: journal.name,
  1287. graficar: false
  1288. })
  1289. }
  1290. }
  1291. var company = _.map(self.resCompany, function (map) {
  1292. return map.currency_id[1];
  1293. });
  1294. if (voucherObjectItem.length > 0){
  1295. sumaAmountTot=_.reduce(_.map(voucherObjectItem,function(item){return (item.amountBase)}), function(memo, num){ return memo + num; },0);
  1296. total=total+sumaAmountTot;
  1297. voucherObjectItem.push({journal : " ",
  1298. method :"Total "+ company,
  1299. amount : accounting.formatNumber(self.valorNull(sumaAmountTot),2, ".", ","),
  1300. currency_name : "",
  1301. currency_id : "",
  1302. rate : "cutrrencyRate.rate",
  1303. amountBase:"",
  1304. journal_id: journal.id,
  1305. journal_name: journal.name,
  1306. graficar: true
  1307. });
  1308. // Generarl la Cabezera
  1309. voucherObjectItem.unshift({ journal : journal.name, method :"", amount :"", voucherLine_name :"", voucherLine_id :"",rate :"",amountBase :"",journal_id:journal.id, journal_name:journal.name, graficar:false});
  1310. // Generar Objeto Principal
  1311. voucherObject=voucherObject.concat(voucherObjectItem);
  1312. }
  1313. }
  1314. if (voucherObject.length > 0){
  1315. voucherObject.push({journal : " Total de Ingreso",
  1316. method :"",
  1317. amount : accounting.formatNumber(self.valorNull(total),2, ".", ","),
  1318. currency_name : "",
  1319. currency_id : "",
  1320. rate : "",
  1321. amountBase:"",
  1322. journal_id: journal.id,
  1323. journal_name: journal.name,
  1324. graficar: false
  1325. });
  1326. }
  1327. self.loadTable(voucherObject);
  1328. },
  1329. // Obtener Voucher
  1330. getVoucherjournal:function(objVoucher,journal_id){
  1331. return _.map(_.filter(objVoucher, function (inv){return inv.journal_id[0] === journal_id}),function(item){return item});
  1332. },
  1333. // Obtener Cambio
  1334. getCutrrencyRate: function(currency_id){
  1335. return _.filter(this.currencyRate, function(rate){return rate.currency_id[0] === currency_id}).shift();
  1336. },
  1337. // Generar la table
  1338. loadTable:function(rowsTable){
  1339. var self = this;
  1340. self.dataVoucher=rowsTable
  1341. var table = this.$el.find('#table');
  1342. table.bootstrapTable('load' ,rowsTable);
  1343. },
  1344. // Buscar
  1345. fectSearch: function(){
  1346. var self = this;
  1347. var desde =this.$el.find('#from').val();
  1348. var hasta =this.$el.find('#to').val();
  1349. var journal =this.$el.find('#current-journal').val();
  1350. var currency =this.$el.find('#current-currency').val();
  1351. var newJournal= self.accountJournal; //copia del Diario
  1352. var newVoucher= self.accountVoucher; //copia del Vouacher
  1353. if (journal != 9999999){
  1354. var botonChart =this.$el.find('#chart').attr("disabled", true);
  1355. newJournal=_.filter(newJournal, function (inv){ return inv.id == journal});
  1356. }else {
  1357. var botonChart =this.$el.find('#chart').attr("disabled", false);
  1358. }
  1359. if(currency != 999){
  1360. newVoucher=_.filter(newVoucher, function (inv){ return inv.currency_id[0] == currency});
  1361. }
  1362. if (desde){
  1363. var date= desde.split('/')
  1364. newVoucher=_.filter(newVoucher, function (inv){return inv.date >= (date[2]+"-"+date[1]+"-"+date[0])});
  1365. }
  1366. if (hasta){
  1367. var date= hasta.split('/')
  1368. newVoucher=_.filter(newVoucher, function (inv){return inv.date <= (date[2]+"-"+date[1]+"-"+date[0])});
  1369. }
  1370. self.fecthDataVoucher(newVoucher,newJournal);
  1371. },
  1372. // volver
  1373. volver: function(){
  1374. this.$el.find('#volver').empty();
  1375. this.$el.find('#grafico').empty();
  1376. this.$el.find('.bootstrap-table').show({
  1377. effect: 'drop',
  1378. direction: 'down',
  1379. duration: 200,
  1380. });
  1381. },
  1382. // Click pdf -Grafic
  1383. clickOnAction: function (e) {
  1384. var action = this.$el.find(e.target).val();
  1385. var self = this;
  1386. var getColumns=[];
  1387. var rows=[];
  1388. var table = this.$el.find("#table");
  1389. var data2 = table.bootstrapTable('getVisibleColumns');
  1390. if (action === 'pdf') {
  1391. var dataNEW = _.map(data2, function (val){ return val.field});
  1392. _.each(this.dataVoucher,function (item){
  1393. rows.push(_.pick(item, dataNEW));
  1394. });
  1395. // Obtener los nombre de la Cabezera
  1396. _.each(_.map(data2,function(val){return val}), function(item){
  1397. getColumns.push([{title: item.title, dataKey: item.field}]);
  1398. });
  1399. // Llamar al pdf
  1400. this.drawPDF(_.flatten(getColumns),rows)
  1401. }
  1402. if (action === 'chart'){
  1403. var self = this;
  1404. var objetChar;
  1405. objetChar = _.filter(self.dataVoucher,function(item){return item.graficar === true});
  1406. self.fectCharFilter(objetChar);
  1407. }
  1408. },
  1409. // pdfDoc
  1410. drawPDF:function(getColumns,rows){
  1411. var self = this;
  1412. var fechaActu= new Date();
  1413. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  1414. var desde =(this.$el.find('#from').val());
  1415. var hasta =(this.$el.find('#to').val());
  1416. var totalPagesExp = "{total_pages_count_string}";
  1417. var pdfDoc = new window.jsPDF();
  1418. pdfDoc.autoTable(getColumns, rows, {
  1419. styles: { overflow: 'linebreak', fontSize:10 , columnWidth: 'wrap'},
  1420. columnStyles:{ journal: {fontStyle: 'bold'},
  1421. method :{columnWidth: '10px'},
  1422. amount : {halign:'right'},
  1423. },
  1424. margin: {
  1425. top: 16,
  1426. horizontal: 7
  1427. },
  1428. addPageContent: function (data) {
  1429. pdfDoc.setFontSize(12);
  1430. pdfDoc.setFontStyle('bold');
  1431. pdfDoc.setTextColor(40);
  1432. pdfDoc.text('Resumen de Ingreso de '+ sucusal, data.settings.margin.left, 10);
  1433. if(desde.length > 0 || hasta.length > 0){
  1434. var fecha='';
  1435. if(desde){
  1436. fecha=fecha.concat(' Desde '+desde);
  1437. }
  1438. if (hasta){
  1439. fecha=fecha.concat(' Hasta '+hasta);
  1440. }
  1441. pdfDoc.setFontSize(10);
  1442. pdfDoc.setFontStyle('bold');
  1443. pdfDoc.setTextColor(40)
  1444. pdfDoc.text(fecha, data.settings.margin.left,14);
  1445. }
  1446. // FOOTER
  1447. var str = "Pagina " + data.pageCount;
  1448. // Total page number plugin only available in jspdf v1.0+
  1449. if (typeof pdfDoc.putTotalPages === 'function') {
  1450. str = str + " de " + totalPagesExp +"\n Día de Expedición "+fechaActu.getDate()+"/"+fechaActu.getMonth()+"/"+fechaActu.getFullYear();
  1451. }
  1452. pdfDoc.setFontSize(9);
  1453. pdfDoc.setFontStyle('bold');
  1454. pdfDoc.setTextColor(40);
  1455. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  1456. }
  1457. });
  1458. if (typeof pdfDoc.putTotalPages === 'function') {
  1459. pdfDoc.putTotalPages(totalPagesExp);
  1460. }
  1461. pdfDoc.save('Resumen de Ingreso.pdf');
  1462. },
  1463. // Char filter
  1464. fectCharFilter: function(objetChar){
  1465. var self = this;
  1466. var dataBody=[];
  1467. var dataHeader=[];
  1468. // objetChar
  1469. var canvas="<canvas id='graf_resume'></canvas>";
  1470. this.$el.find('#grafico').append(canvas);
  1471. _.each(objetChar,function(voucher){
  1472. dataHeader.push(voucher.journal_name);
  1473. dataBody.push(parseFloat(((voucher.amount.replace(".","")).replace(",","."))));
  1474. });
  1475. var selector ="<button type='button' class='oe_button oe_form_button oe_highlight' id='volver_btn' name='volver_btn'><span>Atras</span></button>";
  1476. this.$el.find('#volver').append(selector);
  1477. this.$el.find('.bootstrap-table').hide({
  1478. effect: 'drop',
  1479. direction: 'up',
  1480. duration: 200,
  1481. complete: function () {
  1482. self.drawChart(dataHeader,dataBody);
  1483. }
  1484. });
  1485. },
  1486. //Chart
  1487. drawChart: function (dataHeader,dataBody) {
  1488. var barChart = new Chart(this.$el.find('#graf_resume'), {
  1489. type: 'doughnut',//bar, doughnut
  1490. data: {
  1491. labels: dataHeader,
  1492. datasets: [
  1493. {
  1494. labels: dataHeader,
  1495. backgroundColor: [
  1496. 'rgba(255, 99, 132, 0.2)',
  1497. 'rgba(54, 162, 235, 0.2)',
  1498. 'rgba(255, 206, 86, 0.2)',
  1499. 'rgba(75, 192, 192, 0.2)',
  1500. 'rgba(153, 102, 255, 0.2)',
  1501. ],
  1502. borderColor: [
  1503. 'rgba(255,99,132,1)',
  1504. 'rgba(54, 162, 235, 1)',
  1505. 'rgba(255, 206, 86, 1)',
  1506. 'rgba(75, 192, 192, 1)',
  1507. 'rgba(153, 102, 255, 1)',
  1508. ],
  1509. borderWidth: 1,
  1510. data: dataBody,
  1511. }
  1512. ]
  1513. },
  1514. options: {
  1515. maintainAspectRatio: false,
  1516. layout: {
  1517. padding: 30
  1518. }
  1519. },
  1520. });
  1521. },
  1522. });
  1523. // StockLocation
  1524. local.ReportStockLocationWidget = instance.Widget.extend({
  1525. template : 'ReportStockLocation',
  1526. stockLocation : [],
  1527. stockQuant : [],
  1528. productProduct : [],
  1529. prodcut:[],
  1530. events : {
  1531. 'click #toolbar > button' : 'clickOnAction',
  1532. 'change #current-location': 'fecthSearch',
  1533. },
  1534. init : function(parent){
  1535. this._super(parent);
  1536. },
  1537. start : function(){
  1538. var self = this;
  1539. var dato=[];
  1540. var table = this.$el.find('#table');
  1541. table.bootstrapTable({data : self.prodcut});
  1542. self.fecthInitial();
  1543. },
  1544. // Consulta Inicial
  1545. fecthInitial: function(){
  1546. var self = this;
  1547. self.fecthLocation().then(function(stockLocation){
  1548. self.stockLocation=stockLocation
  1549. return stockLocation;
  1550. }).then(function(stockLocation){
  1551. self.$el.find('#current-location').append('<option value="9999999">Todas las Ubicación.</option>');
  1552. _.each(stockLocation,function(item){
  1553. self.$el.find('#current-location').append('<option value="' + item.id + '">' + item.location_id[1]+" / "+item.name + '</option>');
  1554. });
  1555. return self.fecthStockQuant();
  1556. }).then(function(stockQuant){
  1557. self.stockQuant = stockQuant;
  1558. return self.fecthProduct(stockQuant);
  1559. }).then(function(productProduct){
  1560. self.productProduct = productProduct;
  1561. return self.fecthProducto(self.stockQuant, self.stockLocation);
  1562. });
  1563. },
  1564. // Ubicacion
  1565. fecthLocation : function(){
  1566. var self = this;
  1567. var defer = $.Deferred();
  1568. var location = new instance.web.Model('stock.location');
  1569. var fields = ['id', 'name', 'company_id', 'location_id'];
  1570. var domain =[['active', '=', true],['usage', '=', 'internal']];
  1571. location.query(fields).filter(domain).order_by('id').all().then(function(results){
  1572. defer.resolve(results);
  1573. })
  1574. return defer;
  1575. },
  1576. // quant
  1577. fecthStockQuant : function(){
  1578. var self = this;
  1579. var defer = $.Deferred();
  1580. var location = _.map(self.stockLocation,function(item){
  1581. return item.id;
  1582. });
  1583. var company_id =(_.map(self.stockLocation, function(item){
  1584. return item.company_id[0];
  1585. })).shift();
  1586. var quant = new instance.web.Model('stock.quant');
  1587. var fields = ['id', 'product_id', 'qty', 'cost','location_id'];
  1588. var domain =[['company_id', '=', company_id],['location_id', '=',location]];
  1589. quant.query(fields).filter(domain).all().then(function(results){
  1590. defer.resolve(results);
  1591. })
  1592. return defer;
  1593. },
  1594. // ProductProduct
  1595. fecthProduct: function(quant){
  1596. var defer = $.Deferred();
  1597. var porductIDS = _.flatten(_.map(quant, function (item) {
  1598. return item.product_id[0];
  1599. }));
  1600. var ProductProdcut = new instance.web.Model('product.product');
  1601. var fields = ['id','name','name_template', 'standard_price','type','attribute_value_ids'];
  1602. ProductProdcut.query(fields).filter([['id', 'in', porductIDS]]).all().then(function (results) {
  1603. defer.resolve(results)
  1604. });
  1605. return defer;
  1606. },
  1607. // Union de Modulos
  1608. fecthProducto : function(stockQuant,stockLocation){
  1609. var self = this;
  1610. var stock=[];
  1611. var itemLocation;
  1612. var itemProduct;
  1613. var itemQuant;
  1614. var productProduct;
  1615. var cat = 0;
  1616. var quant;
  1617. for (var i = 0; i < stockLocation.length; i++) {
  1618. itemLocation = stockLocation[i];
  1619. productProduct = self.getProdcutoProduct(self.productProduct,stockQuant, itemLocation.id);
  1620. for (var f = 0; f < productProduct.length; f++) {
  1621. itemProduct = productProduct[f];
  1622. itemQuant = self.getQuantProduct(itemLocation.id, itemProduct.id, stockQuant);
  1623. if (itemQuant.length >0){
  1624. cat = _.reduce(_.map(itemQuant,function(item){
  1625. return item.qty;
  1626. }),function(mamo, num){
  1627. return mamo + num;
  1628. },0);
  1629. quant=itemQuant.shift();
  1630. stock.push({prodcut : quant.product_id[1],
  1631. qty : cat,
  1632. location :(itemLocation.location_id[1]+" / "+itemLocation.name)});
  1633. }
  1634. }
  1635. }
  1636. self.loadTable(stock);
  1637. },
  1638. // Obtener Producto Por quant y locations
  1639. getProdcutoProduct: function(productProduct, stockQuant, location_id){
  1640. var self = this;
  1641. var product_ids= _.flatten(_.map(_.filter(stockQuant, function(item){
  1642. return item.location_id[0] === location_id;
  1643. }),function(map){
  1644. return map.product_id[0];
  1645. }));
  1646. return _.filter(productProduct,function(prod){return _.contains(product_ids, prod.id)});
  1647. },
  1648. // Obtener Qaunt por productos
  1649. getQuantProduct: function(location_id, product_id, quantObjs){
  1650. var self = this;
  1651. var quantProdcut = quantObjs;
  1652. if (location_id){
  1653. quantProdcut = _.filter(quantProdcut, function(item){
  1654. return item.location_id[0] === location_id;
  1655. });
  1656. }
  1657. if (product_id){
  1658. quantProdcut = _.filter(quantProdcut, function(item){
  1659. return item.product_id[0] === product_id;
  1660. });
  1661. }
  1662. return quantProdcut;
  1663. },
  1664. // Buscar
  1665. fecthSearch: function(){
  1666. var self = this;
  1667. var location =this.$el.find('#current-location').val();
  1668. var locationObjs = self.stockLocation;
  1669. var quantObjs = self.stockQuant;
  1670. if (location != 9999999){
  1671. locationObjs=_.filter(locationObjs, function (inv){
  1672. return inv.id == location;
  1673. });
  1674. quantObjs=_.filter(quantObjs, function (inv){
  1675. return inv.location_id[0] == location;
  1676. });
  1677. }
  1678. self.fecthProducto(quantObjs,locationObjs)
  1679. },
  1680. // Generar la table
  1681. loadTable:function(rowsTable){
  1682. var self = this;
  1683. this.prodcut=rowsTable;
  1684. var table = this.$el.find('#table');
  1685. table.bootstrapTable('load' ,rowsTable);
  1686. },
  1687. // Click pdf -Grafic
  1688. clickOnAction: function (e) {
  1689. var self = this;
  1690. var action = self.$el.find(e.target).val();
  1691. var getColumns=[];
  1692. var rows=[];
  1693. var table = self.$el.find("#table");
  1694. var data2 = table.bootstrapTable('getVisibleColumns');
  1695. if (action === 'pdf') {
  1696. var dataNEW = _.map(data2, function (val){
  1697. return val.field;
  1698. });
  1699. _.each(self.prodcut,function (item){
  1700. rows.push(_.pick(item, dataNEW));
  1701. });
  1702. // Obtener los nombre de la Cabezera
  1703. _.each(_.map(data2,function(val){return val}), function(item){
  1704. getColumns.push([{
  1705. title: item.title,
  1706. dataKey: item.field
  1707. }]);
  1708. });
  1709. self.drawPDF(_.flatten(getColumns),rows)
  1710. }
  1711. },
  1712. // pdfDoc
  1713. drawPDF:function(getColumns,rows){
  1714. var self = this;
  1715. var fechaActu= new Date();
  1716. var location = this.sucDescrip = this.$el.find('#current-location option:selected').text();
  1717. var totalPagesExp = "{total_pages_count_string}";
  1718. var pdfDoc = new jsPDF();
  1719. pdfDoc.autoTable(getColumns, rows, {
  1720. styles: { overflow: 'linebreak', fontSize:8 , columnWidth: 'wrap'},
  1721. columnStyles:{
  1722. prodcut :{columnWidth: '8px'},
  1723. location :{columnWidth: '8px'},
  1724. qty : {halign:'center'},
  1725. },
  1726. margin: { top: 16, horizontal: 7},
  1727. addPageContent: function (data) {
  1728. pdfDoc.setFontSize(12);
  1729. pdfDoc.setFontStyle('bold');
  1730. pdfDoc.setTextColor(40);
  1731. pdfDoc.text('Listado de Stock Por '+ location, data.settings.margin.left, 10);
  1732. // FOOTER
  1733. var str = "Pagina " + data.pageCount;
  1734. if (typeof pdfDoc.putTotalPages === 'function') {
  1735. str = str + " de " + totalPagesExp +"\n Día de Expedición "+fechaActu.getDate()+"/"+fechaActu.getMonth()+"/"+fechaActu.getFullYear();
  1736. }
  1737. pdfDoc.setFontSize(9);
  1738. pdfDoc.setFontStyle('bold');
  1739. pdfDoc.setTextColor(40);
  1740. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  1741. }
  1742. });
  1743. if (typeof pdfDoc.putTotalPages === 'function') {
  1744. pdfDoc.putTotalPages(totalPagesExp);
  1745. }
  1746. pdfDoc.save('Listado_de_Stock_Por_Ubicaion.pdf');
  1747. }
  1748. });
  1749. // AllPurchases Listado de Compras
  1750. local.AllPurchasesWidget = instance.Widget.extend({
  1751. template: 'AllPurchases',
  1752. invoice: [],
  1753. Currency:[],
  1754. resCurrency :[],
  1755. resCompany:[],
  1756. accountJournal:[],
  1757. supplier:[],
  1758. newInvoice:[],
  1759. rowsData :[],
  1760. // event
  1761. events:{
  1762. 'click #toolbar > button' : 'clickOnAction',
  1763. 'change #current-journal' : 'factSearch',
  1764. 'change #current-currency' : 'factSearch',
  1765. 'change #from' : 'factSearch',
  1766. 'change #to' : 'factSearch',
  1767. 'click #volver_btn' : 'volver',
  1768. },
  1769. // Initil
  1770. init : function(parent){
  1771. this._super(parent);
  1772. },
  1773. // start
  1774. start: function () {
  1775. var self = this;
  1776. var table = this.$el.find('#table');
  1777. table.bootstrapTable({data : self.rowsData});
  1778. this.fecthFecha();
  1779. this.submitForm();
  1780. },
  1781. // volver
  1782. volver: function(){
  1783. this.$el.find('#volver').empty();
  1784. this.$el.find('.bootstrap-table').show({
  1785. effect: 'drop',
  1786. direction: 'down',
  1787. duration: 200,
  1788. });
  1789. },
  1790. // Consultar
  1791. submitForm: function () {
  1792. var self = this;
  1793. self.fetchResCurency().then(function(resCurrency) {
  1794. return resCurrency;
  1795. }).then(function (resCurrency) {
  1796. self.resCurrency = resCurrency;
  1797. self.$el.find('#current-currency').append('<option value="9999999">Todas las monedas</option>');
  1798. _.each(resCurrency, function (item) {
  1799. self.$el.find('#current-currency').append('<option value="' + item.id + '">' + item.name + '</option>');
  1800. });
  1801. return self.fetchCurency(resCurrency);
  1802. }).then(function(Currency){
  1803. self.Currency = Currency;
  1804. return self.fetchJournal();
  1805. }).then(function (journal) {
  1806. self.accountJournal =journal;
  1807. self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
  1808. _.each(journal, function (item) {
  1809. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  1810. });
  1811. return self.fetchInvoiceP2();
  1812. }).then(function (invoice){
  1813. self.invoice = invoice;
  1814. return self.fetchSupplier(invoice);
  1815. }).then(function(supplier){
  1816. self.supplier=supplier;
  1817. return self.fecthComanyCurrency();
  1818. }).then(function(resCompany){
  1819. self.resCompany = resCompany;
  1820. self.inicializarBuscadorsup();
  1821. return self.fect_generar(self.invoice);
  1822. });
  1823. },
  1824. // Fecha
  1825. fecthFecha: function() {
  1826. var to;
  1827. var dateFormat1 = "mm/dd/yy",
  1828. from = $( "#from" )
  1829. .datepicker({
  1830. dateFormat: "dd/mm/yy",
  1831. changeMonth: true,
  1832. numberOfMonths: 1,
  1833. })
  1834. .on( "change", function() {
  1835. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  1836. });
  1837. to = $( "#to" ).datepicker({
  1838. dateFormat: "dd/mm/yy",
  1839. defaultDate: "+7d",
  1840. changeMonth: true,
  1841. numberOfMonths: 1,
  1842. })
  1843. .on( "change", function() {
  1844. from.datepicker( "option", "maxDate", getDate(this));
  1845. });
  1846. function getDate( element ) {
  1847. var fechaSel =element.value.split('/');
  1848. var date;
  1849. try {
  1850. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  1851. } catch( error ) {
  1852. date = null;
  1853. }
  1854. return date;
  1855. }
  1856. },
  1857. // Buscar Diario
  1858. fetchJournal: function () {
  1859. var self = this;
  1860. var defer = $.Deferred();
  1861. var Journal = new instance.web.Model('account.journal');
  1862. Journal.query(['id', 'name']).filter([['type', '=', 'purchase']]).all().then(function(results){
  1863. defer.resolve(results);
  1864. });
  1865. return defer;
  1866. },
  1867. // Buscar Cambio de Monedas USD,PYG,ARG,BRL
  1868. fetchCurency: function (currency) {
  1869. var defer = $.Deferred();
  1870. var currency_id = _.flatten(_.map(currency,function(map){
  1871. return map.id;
  1872. }))
  1873. var currency_Rate = new instance.web.Model('res.currency.rate');
  1874. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  1875. var domain = [['currency_id', '=', currency_id]];
  1876. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  1877. defer.resolve(results);
  1878. });
  1879. return defer;
  1880. },
  1881. // Moneda
  1882. fetchResCurency: function () {
  1883. var defer = $.Deferred();
  1884. var currency = new instance.web.Model('res.currency');
  1885. var fields = ['id', 'name'];
  1886. var domain = [['active', '=', true]];
  1887. currency.query(fields).filter(domain).all().then(function (results) {
  1888. defer.resolve(results);
  1889. });
  1890. return defer;
  1891. },
  1892. // Invoice (FACTURAS)
  1893. fetchInvoiceP2: function () {
  1894. var journal_ids = _.flatten(_.map(this.accountJournal, function (item) {
  1895. return item.id;
  1896. }));
  1897. var filter =[['state', '=',['open','paid']],['type', '=', 'in_invoice'],['origin', '!=', false],['journal_id', '=',journal_ids]];
  1898. var field =['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'supplier_invoice_number','date_invoice','partner_id','amount_total','user_id'];
  1899. var defer = $.Deferred();
  1900. var Invoice = new instance.web.Model('account.invoice');
  1901. Invoice.query(field).filter(filter).all().then(function (results) {
  1902. defer.resolve(results);
  1903. });
  1904. return defer;
  1905. },
  1906. // company_curency
  1907. fecthComanyCurrency: function(){
  1908. var self = this;
  1909. var defer = $.Deferred();
  1910. var currency = new instance.web.Model('res.company');
  1911. var field=['id', 'currency_id'];
  1912. var domain=[['id','=',1]];
  1913. currency.query(field).filter(domain).all().then(function(results){
  1914. defer.resolve(results);
  1915. });
  1916. return defer;
  1917. },
  1918. // Partner (Proveeedor)
  1919. fetchSupplier: function() {
  1920. var self = this;
  1921. var defer = $.Deferred();
  1922. var supplier = new instance.web.Model('res.partner');
  1923. supplier.query(['id', 'name', 'ruc', 'active', 'supplier']).filter([['active', '=', true], ['supplier', '=', true]]).all().then(function (results) {
  1924. defer.resolve(results);
  1925. });
  1926. return defer;
  1927. },
  1928. // Obtener el Cambio de la Moneda
  1929. getCurrency: function (id){
  1930. return _.find(this.Currency,function (curr) {
  1931. return _.contains(curr.currency_id,id);
  1932. });
  1933. },
  1934. // Verificar si los Valores no son nulos
  1935. valorNull:function(dato){
  1936. var valor ="";
  1937. if (dato){
  1938. valor=dato;
  1939. }
  1940. return valor;
  1941. },
  1942. // Buscador
  1943. inicializarBuscadorsup: function () {
  1944. var self = this;
  1945. var results = self.supplier;
  1946. results = _.map(results, function (item) {
  1947. return {
  1948. label: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc),
  1949. value: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc)
  1950. }
  1951. });
  1952. self.$('#customer').autocomplete({
  1953. source: results,
  1954. minLength:0,
  1955. search: function(event, ui) {
  1956. if (!(self.$('#customer').val())){
  1957. self.factSearch();
  1958. }
  1959. },
  1960. select: function(event, ui) {
  1961. self.factSearch();
  1962. }
  1963. });
  1964. },
  1965. // unir los objetos
  1966. fect_generar: function(invoices){
  1967. var self = this;
  1968. var data = [];
  1969. _.each(invoices, function(invoice){
  1970. data.push({
  1971. number: invoice.number,
  1972. supplier_invoice_number: self.valorNull(invoice.supplier_invoice_number),
  1973. partner: invoice.partner_id[1],
  1974. date: moment(invoice.date_invoice).format("DD/MM/YYYY"),
  1975. date_invoice: invoice.date_invoice,
  1976. user: invoice.user_id[1],
  1977. currency: invoice.currency_id[1],
  1978. amount_total: accounting.formatNumber(invoice.amount_total,2,".",","),
  1979. amount: invoice.amount_total,
  1980. journal_id : invoice.journal_id[0],
  1981. currency_id : invoice.currency_id[0],
  1982. partner_id : invoice.partner_id[0]
  1983. });
  1984. });
  1985. self.newInvoice = data;
  1986. this.loadTable(data);
  1987. },
  1988. // Buscar
  1989. factSearch: function(){
  1990. var self = this;
  1991. var desde =this.$el.find('#from').val();
  1992. var hasta =this.$el.find('#to').val();
  1993. var suc =this.$el.find('#current-journal').val();
  1994. var currency =this.$el.find('#current-currency').val();
  1995. var prov= this.$el.find('#customer').val().split('-');
  1996. var newInvoice = self.newInvoice;
  1997. // Buscar por Sucursales
  1998. if (suc != 9999999){
  1999. newInvoice=_.filter(newInvoice, function (inv){
  2000. return inv.journal_id == suc;
  2001. });
  2002. }
  2003. // Buscar por fecha Desde
  2004. if (desde.length > 0){
  2005. var date= desde.split('/');
  2006. newInvoice = _.filter(newInvoice, function (inv){
  2007. return inv.date_invoice >= (date[2]+"-"+date[1]+"-"+date[0]);
  2008. });
  2009. }
  2010. // Buscar por Fechas Hasta
  2011. if (hasta.length > 0){
  2012. var date= hasta.split('/');
  2013. newInvoice = _.filter(newInvoice, function (inv){
  2014. return inv.date_invoice <= (date[2]+"-"+date[1]+"-"+date[0]);
  2015. });
  2016. }
  2017. // Busacar por moneda
  2018. if(currency != 9999999){
  2019. newInvoice = _.filter(newInvoice,function(inv){
  2020. return inv.currency_id == currency;
  2021. });
  2022. }
  2023. // Busacara por proveedor
  2024. if (prov != ""){
  2025. newInvoice = _.filter(newInvoice, function(inv){
  2026. return inv.partner_id == prov[0];
  2027. });
  2028. }
  2029. self.loadTable(newInvoice)
  2030. },
  2031. // cargara la tabla
  2032. loadTable:function(rowsTable){
  2033. var self = this;
  2034. self.rowsData = rowsTable;
  2035. var table = this.$el.find('#table');
  2036. table.bootstrapTable('load',rowsTable);
  2037. },
  2038. // Obtener Invoice por Monedad
  2039. getInvoice : function(currency_id){
  2040. var self = this;
  2041. return _.filter(self.rowsData, function(item){
  2042. return item.currency_id === currency_id;
  2043. });
  2044. },
  2045. // Crear Objete PDF
  2046. getObjetPdf: function(rowsTable){
  2047. var self = this;
  2048. var rowsPdf=[];
  2049. var rows=[];
  2050. var itemCurrecy;
  2051. var itenRow;
  2052. var item;
  2053. var curreRate;
  2054. var amount_total=0;
  2055. var amount=0;
  2056. var company = _.map(self.resCompany,function(map){return map.currency_id[1]});
  2057. for (var i = 0; i < self.resCurrency.length; i++) {
  2058. itemCurrecy = self.resCurrency[i];
  2059. itenRow = self.getInvoice(itemCurrecy.id);
  2060. rowsPdf=[];
  2061. if (itenRow.length > 0){
  2062. rowsPdf.push({number: itemCurrecy.name, supplier_invoice_number: "", partner: "", date: "", date_invoice: "", user: "", currency: "", amount_total: "", journal_id : "", currency_id : "", partner_id : ""});
  2063. _.each(itenRow, function(item){
  2064. rowsPdf.push({
  2065. number: item.number,
  2066. supplier_invoice_number: self.valorNull(item.supplier_invoice_number),
  2067. partner: item.partner,
  2068. date: moment(item.date_invoice).format("DD/MM/YYYY"),
  2069. date_invoice: item.date_invoice,
  2070. user: item.user,
  2071. currency: item.currency,
  2072. amount_total: accounting.formatNumber((item.amount),2,".",","),
  2073. amount: item.amount,
  2074. journal_id : item.journal_id,
  2075. currency_id : item.currency_id,
  2076. partner_id : item.partner_id
  2077. });
  2078. });
  2079. curreRate = self.getCurrency(itemCurrecy.id);
  2080. if (!curreRate){
  2081. curreRate={};
  2082. curreRate.rate=1;
  2083. }
  2084. amount_total= _.reduce(_.map(itenRow,function(map){
  2085. return(map.amount);
  2086. }),function(memo, num){
  2087. return memo + num;
  2088. },0);
  2089. amount = amount+(amount_total/curreRate.rate);
  2090. rowsPdf.push({
  2091. number: "Sub - Total "+itemCurrecy.name,
  2092. supplier_invoice_number: "",
  2093. partner: "",
  2094. date: "",
  2095. date_invoice: "",
  2096. user: "",
  2097. currency: "",
  2098. amount_total: accounting.formatNumber((amount_total),2,".",","),
  2099. journal_id : "",
  2100. currency_id : "",
  2101. partner_id : ""
  2102. });
  2103. }
  2104. if (rowsPdf.length >0){
  2105. rows = rows.concat(rowsPdf);
  2106. }
  2107. }
  2108. if (rows.length > 0){
  2109. rows.push({
  2110. number: "Total en "+company,
  2111. supplier_invoice_number: "",
  2112. partner: "",
  2113. date: "",
  2114. date_invoice: "",
  2115. user: "",
  2116. currency: "",
  2117. amount_total: accounting.formatNumber((amount),2,".",","),
  2118. journal_id : "",
  2119. currency_id : "",
  2120. partner_id : ""
  2121. });
  2122. }
  2123. return rows;
  2124. },
  2125. // imprimir PDF
  2126. clickOnAction: function (e) {
  2127. var self = this;
  2128. var rowsNew;
  2129. var action = self.$el.find(e.target).val();
  2130. var table = self.$el.find("#table");
  2131. var data2 = table.bootstrapTable('getVisibleColumns');
  2132. var getColumns=[];
  2133. var rows=[];
  2134. rowsNew = self.getObjetPdf();
  2135. if (action === 'pdf') {
  2136. var dataNEW = _.map(data2, function (val){
  2137. return val.field;
  2138. });
  2139. _.each(rowsNew,function (item){
  2140. rows.push(_.pick(item, dataNEW));
  2141. });
  2142. // Obtener los nombre de la Cabezera
  2143. _.each(_.map(data2,function(val){
  2144. return val;
  2145. }), function(item){
  2146. getColumns.push([{
  2147. title: item.title,
  2148. dataKey: item.field
  2149. }]);
  2150. });
  2151. this.drawPDF(_.flatten(getColumns),rows);
  2152. }
  2153. },
  2154. // Generar pdfDoc
  2155. drawPDF: function (getColumns,rows) {
  2156. var self = this;
  2157. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  2158. var desde =(this.$el.find('#from').val());
  2159. var hasta =(this.$el.find('#to').val());
  2160. var totalPagesExp = "{total_pages_count_string}";
  2161. var pdfDoc = new jsPDF();
  2162. pdfDoc.autoTable(getColumns, rows, {
  2163. styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
  2164. columnStyles: {
  2165. number : {columnWidth: '8px'},
  2166. supplier_invoice_number : {columnWidth: '8px'},
  2167. partner : {columnWidth: '8px'},
  2168. date : {columnWidth: '8px'},
  2169. user : {columnWidth: '8px'},
  2170. currency : {columnWidth: '8px'},
  2171. amount_total: {halign:'right',columnWidth: '8px'},
  2172. },
  2173. margin: { top: 16, horizontal: 7},
  2174. addPageContent: function (data) {
  2175. pdfDoc.setFontSize(12);
  2176. pdfDoc.setFontStyle('bold');
  2177. pdfDoc.setTextColor(40);
  2178. pdfDoc.text('Listado de Compras '+ sucusal, data.settings.margin.left, 10);
  2179. if(desde.length > 0 || hasta.length > 0){
  2180. var fecha='';
  2181. if(desde){
  2182. fecha=fecha.concat(' Desde '+desde);
  2183. }
  2184. if (hasta){
  2185. fecha=fecha.concat(' Hasta '+hasta);
  2186. }
  2187. pdfDoc.setFontSize(10);
  2188. pdfDoc.setFontStyle('bold');
  2189. pdfDoc.setTextColor(40)
  2190. pdfDoc.text(fecha, data.settings.margin.left,14);
  2191. }
  2192. // FOOTER
  2193. var str = "Pagina " + data.pageCount;
  2194. // Total page number plugin only available in jspdf v1.0+
  2195. if (typeof pdfDoc.putTotalPages === 'function') {
  2196. str = str + " de " + totalPagesExp;
  2197. }
  2198. pdfDoc.setFontSize(9);
  2199. pdfDoc.setFontStyle('bold');
  2200. pdfDoc.setTextColor(40);
  2201. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  2202. }
  2203. });
  2204. if (typeof pdfDoc.putTotalPages === 'function') {
  2205. pdfDoc.putTotalPages(totalPagesExp);
  2206. }
  2207. pdfDoc.save('Listado de Compras.pdf')
  2208. },
  2209. });
  2210. // ReposrtExpenses Listado de Gastos
  2211. local.ReposrtExpensesWidget = instance.Widget.extend({
  2212. template: 'ReposrtExpenses',
  2213. invoice: [],
  2214. Currency:[],
  2215. resCurrency :[],
  2216. resCompany:[],
  2217. accountJournal:[],
  2218. supplier:[],
  2219. newInvoice:[],
  2220. rowsData :[],
  2221. // event
  2222. events:{
  2223. 'click #toolbar > button' : 'clickOnAction',
  2224. 'change #current-journal' : 'factSearch',
  2225. 'change #current-currency' : 'factSearch',
  2226. 'change #from' : 'factSearch',
  2227. 'change #to' : 'factSearch',
  2228. 'click #volver_btn' : 'volver',
  2229. },
  2230. // Initil
  2231. init : function(parent){
  2232. this._super(parent);
  2233. },
  2234. // start
  2235. start: function () {
  2236. var self = this;
  2237. var table = this.$el.find('#table');
  2238. table.bootstrapTable({data : self.rowsData});
  2239. this.fecthFecha();
  2240. this.submitForm();
  2241. },
  2242. // volver
  2243. volver: function(){
  2244. this.$el.find('#volver').empty();
  2245. this.$el.find('.bootstrap-table').show({
  2246. effect: 'drop',
  2247. direction: 'down',
  2248. duration: 200,
  2249. });
  2250. },
  2251. // Consultar
  2252. submitForm: function () {
  2253. var self = this;
  2254. self.fetchResCurency().then(function(resCurrency) {
  2255. return resCurrency;
  2256. }).then(function (resCurrency) {
  2257. self.resCurrency = resCurrency;
  2258. self.$el.find('#current-currency').append('<option value="9999999">Todas las monedas</option>');
  2259. _.each(resCurrency, function (item) {
  2260. self.$el.find('#current-currency').append('<option value="' + item.id + '">' + item.name + '</option>');
  2261. });
  2262. return self.fetchCurency(resCurrency);
  2263. }).then(function(Currency){
  2264. self.Currency = Currency;
  2265. return self.fetchJournal();
  2266. }).then(function (journal) {
  2267. self.accountJournal =journal;
  2268. self.$el.find('#current-journal').append('<option value="9999999">TODAS LAS SUC.</option>');
  2269. _.each(journal, function (item) {
  2270. self.$el.find('#current-journal').append('<option value="' + item.id + '">' + item.name + '</option>');
  2271. });
  2272. return self.fetchInvoiceP2();
  2273. }).then(function (invoice){
  2274. self.invoice = invoice;
  2275. return self.fetchSupplier(invoice);
  2276. }).then(function(supplier){
  2277. self.supplier=supplier;
  2278. return self.fecthComanyCurrency();
  2279. }).then(function(resCompany){
  2280. self.resCompany = resCompany;
  2281. self.inicializarBuscadorsup();
  2282. return self.fect_generar(self.invoice);
  2283. });
  2284. },
  2285. // Fecha
  2286. fecthFecha: function() {
  2287. var to;
  2288. var dateFormat1 = "mm/dd/yy",
  2289. from = $( "#from" )
  2290. .datepicker({
  2291. dateFormat: "dd/mm/yy",
  2292. changeMonth: true,
  2293. numberOfMonths: 1,
  2294. })
  2295. .on( "change", function() {
  2296. to.datepicker( "option", "minDate", getDate(this), "dd/mm/yyyy");
  2297. });
  2298. to = $( "#to" ).datepicker({
  2299. dateFormat: "dd/mm/yy",
  2300. defaultDate: "+7d",
  2301. changeMonth: true,
  2302. numberOfMonths: 1,
  2303. })
  2304. .on( "change", function() {
  2305. from.datepicker( "option", "maxDate", getDate(this));
  2306. });
  2307. function getDate( element ) {
  2308. var fechaSel =element.value.split('/');
  2309. var date;
  2310. try {
  2311. date = $.datepicker.parseDate( dateFormat1, (fechaSel[1]+"/"+fechaSel[0]+"/"+fechaSel[2]));
  2312. } catch( error ) {
  2313. date = null;
  2314. }
  2315. return date;
  2316. }
  2317. },
  2318. // Buscar Diario
  2319. fetchJournal: function () {
  2320. var self = this;
  2321. var defer = $.Deferred();
  2322. var Journal = new instance.web.Model('account.journal');
  2323. Journal.query(['id', 'name']).filter([['type', '=', 'purchase']]).all().then(function(results){
  2324. defer.resolve(results);
  2325. });
  2326. return defer;
  2327. },
  2328. // Buscar Cambio de Monedas USD,PYG,ARG,BRL
  2329. fetchCurency: function (currency) {
  2330. var defer = $.Deferred();
  2331. var currency_id = _.flatten(_.map(currency,function(map){
  2332. return map.id;
  2333. }))
  2334. var currency_Rate = new instance.web.Model('res.currency.rate');
  2335. var fields = ['id', 'name', 'currency_id', 'rate', 'create_date'];
  2336. var domain = [['currency_id', '=', currency_id]];
  2337. currency_Rate.query(fields).filter(domain).all().then(function (results) {
  2338. defer.resolve(results);
  2339. });
  2340. return defer;
  2341. },
  2342. // Moneda
  2343. fetchResCurency: function () {
  2344. var defer = $.Deferred();
  2345. var currency = new instance.web.Model('res.currency');
  2346. var fields = ['id', 'name'];
  2347. var domain = [['active', '=', true]];
  2348. currency.query(fields).filter(domain).all().then(function (results) {
  2349. defer.resolve(results);
  2350. });
  2351. return defer;
  2352. },
  2353. // Invoice (FACTURAS)
  2354. fetchInvoiceP2: function () {
  2355. var journal_ids = _.flatten(_.map(this.accountJournal, function (item) {
  2356. return item.id;
  2357. }));
  2358. var filter =[['state', '=',['open','paid']],['type', '=', 'in_invoice'],['origin', '=', false],['journal_id', '=',journal_ids]];
  2359. var field =['id', 'type', 'number', 'origin', 'state', 'journal_id', 'currency_id', 'supplier_invoice_number','date_invoice','partner_id','amount_total','user_id'];
  2360. var defer = $.Deferred();
  2361. var Invoice = new instance.web.Model('account.invoice');
  2362. Invoice.query(field).filter(filter).all().then(function (results) {
  2363. defer.resolve(results);
  2364. });
  2365. return defer;
  2366. },
  2367. // company_curency
  2368. fecthComanyCurrency: function(){
  2369. var self = this;
  2370. var defer = $.Deferred();
  2371. var currency = new instance.web.Model('res.company');
  2372. var field=['id', 'currency_id'];
  2373. var domain=[['id','=',1]];
  2374. currency.query(field).filter(domain).all().then(function(results){
  2375. defer.resolve(results);
  2376. });
  2377. return defer;
  2378. },
  2379. // Partner (Proveeedor)
  2380. fetchSupplier: function() {
  2381. var self = this;
  2382. var defer = $.Deferred();
  2383. var supplier = new instance.web.Model('res.partner');
  2384. supplier.query(['id', 'name', 'ruc', 'active', 'supplier']).filter([['active', '=', true], ['supplier', '=', true]]).all().then(function (results) {
  2385. defer.resolve(results);
  2386. });
  2387. return defer;
  2388. },
  2389. // Obtener el Cambio de la Moneda
  2390. getCurrency: function (id){
  2391. return _.find(this.Currency,function (curr) {
  2392. return _.contains(curr.currency_id,id);
  2393. });
  2394. },
  2395. // Verificar si los Valores no son nulos
  2396. valorNull:function(dato){
  2397. var valor ="";
  2398. if (dato){
  2399. valor=dato;
  2400. }
  2401. return valor;
  2402. },
  2403. // Buscador
  2404. inicializarBuscadorsup: function () {
  2405. var self = this;
  2406. var results = self.supplier;
  2407. results = _.map(results, function (item) {
  2408. return {
  2409. label: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc),
  2410. value: item.id + '-'+ item.name + ' ' + self.valorNull(item.ruc)
  2411. }
  2412. });
  2413. self.$('#customer').autocomplete({
  2414. source: results,
  2415. minLength:0,
  2416. search: function(event, ui) {
  2417. if (!(self.$('#customer').val())){
  2418. self.factSearch();
  2419. }
  2420. },
  2421. select: function(event, ui) {
  2422. self.factSearch();
  2423. }
  2424. });
  2425. },
  2426. // unir los objetos
  2427. fect_generar: function(invoices){
  2428. var self = this;
  2429. var data = [];
  2430. _.each(invoices, function(invoice){
  2431. data.push({
  2432. number: invoice.number,
  2433. supplier_invoice_number: self.valorNull(invoice.supplier_invoice_number),
  2434. partner: invoice.partner_id[1],
  2435. date: moment(invoice.date_invoice).format("DD/MM/YYYY"),
  2436. date_invoice: invoice.date_invoice,
  2437. user: invoice.user_id[1],
  2438. currency: invoice.currency_id[1],
  2439. amount_total: accounting.formatNumber(invoice.amount_total,2,".",","),
  2440. amount: invoice.amount_total,
  2441. journal_id : invoice.journal_id[0],
  2442. currency_id : invoice.currency_id[0],
  2443. partner_id : invoice.partner_id[0]
  2444. });
  2445. });
  2446. self.newInvoice = data;
  2447. this.loadTable(data);
  2448. },
  2449. // Buscar
  2450. factSearch: function(){
  2451. var self = this;
  2452. var desde =this.$el.find('#from').val();
  2453. var hasta =this.$el.find('#to').val();
  2454. var suc =this.$el.find('#current-journal').val();
  2455. var currency =this.$el.find('#current-currency').val();
  2456. var prov= this.$el.find('#customer').val().split('-');
  2457. var newInvoice = self.newInvoice;
  2458. // Buscar por Sucursales
  2459. if (suc != 9999999){
  2460. newInvoice=_.filter(newInvoice, function (inv){
  2461. return inv.journal_id == suc;
  2462. });
  2463. }
  2464. // Buscar por fecha Desde
  2465. if (desde.length > 0){
  2466. var date= desde.split('/');
  2467. newInvoice = _.filter(newInvoice, function (inv){
  2468. return inv.date_invoice >= (date[2]+"-"+date[1]+"-"+date[0]);
  2469. });
  2470. }
  2471. // Buscar por Fechas Hasta
  2472. if (hasta.length > 0){
  2473. var date= hasta.split('/');
  2474. newInvoice = _.filter(newInvoice, function (inv){
  2475. return inv.date_invoice <= (date[2]+"-"+date[1]+"-"+date[0]);
  2476. });
  2477. }
  2478. // Busacar por moneda
  2479. if(currency != 9999999){
  2480. newInvoice = _.filter(newInvoice,function(inv){
  2481. return inv.currency_id == currency;
  2482. });
  2483. }
  2484. // Busacara por proveedor
  2485. if (prov != ""){
  2486. newInvoice = _.filter(newInvoice, function(inv){
  2487. return inv.partner_id == prov[0];
  2488. });
  2489. }
  2490. self.loadTable(newInvoice)
  2491. },
  2492. // cargara la tabla
  2493. loadTable:function(rowsTable){
  2494. var self = this;
  2495. self.rowsData = rowsTable;
  2496. var table = this.$el.find('#table');
  2497. table.bootstrapTable('load',rowsTable);
  2498. },
  2499. // Obtener Invoice por Monedad
  2500. getInvoice : function(currency_id){
  2501. var self = this;
  2502. return _.filter(self.rowsData, function(item){
  2503. return item.currency_id === currency_id;
  2504. });
  2505. },
  2506. // Crear Objete PDF
  2507. getObjetPdf: function(rowsTable){
  2508. var self = this;
  2509. var rowsPdf=[];
  2510. var rows=[];
  2511. var itemCurrecy;
  2512. var itenRow;
  2513. var item;
  2514. var curreRate;
  2515. var amount_total=0;
  2516. var amount=0;
  2517. var company = _.map(self.resCompany,function(map){return map.currency_id[1]});
  2518. for (var i = 0; i < self.resCurrency.length; i++) {
  2519. itemCurrecy = self.resCurrency[i];
  2520. itenRow = self.getInvoice(itemCurrecy.id);
  2521. rowsPdf=[];
  2522. if (itenRow.length > 0){
  2523. rowsPdf.push({number: itemCurrecy.name, supplier_invoice_number: "", partner: "", date: "", date_invoice: "", user: "", currency: "", amount_total: "", journal_id : "", currency_id : "", partner_id : ""});
  2524. _.each(itenRow, function(item){
  2525. rowsPdf.push({
  2526. number: item.number,
  2527. supplier_invoice_number: self.valorNull(item.supplier_invoice_number),
  2528. partner: item.partner,
  2529. date: moment(item.date_invoice).format("DD/MM/YYYY"),
  2530. date_invoice: item.date_invoice,
  2531. user: item.user,
  2532. currency: item.currency,
  2533. amount_total: accounting.formatNumber((item.amount),2,".",","),
  2534. amount: item.amount,
  2535. journal_id : item.journal_id,
  2536. currency_id : item.currency_id,
  2537. partner_id : item.partner_id
  2538. });
  2539. });
  2540. curreRate = self.getCurrency(itemCurrecy.id);
  2541. if (!curreRate){
  2542. curreRate={};
  2543. curreRate.rate=1;
  2544. }
  2545. amount_total= _.reduce(_.map(itenRow,function(map){
  2546. return(map.amount);
  2547. }),function(memo, num){
  2548. return memo + num;
  2549. },0);
  2550. amount = amount+(amount_total/curreRate.rate);
  2551. rowsPdf.push({
  2552. number: "Sub - Total "+itemCurrecy.name,
  2553. supplier_invoice_number: "",
  2554. partner: "",
  2555. date: "",
  2556. date_invoice: "",
  2557. user: "",
  2558. currency: "",
  2559. amount_total: accounting.formatNumber((amount_total),2,".",","),
  2560. journal_id : "",
  2561. currency_id : "",
  2562. partner_id : ""
  2563. });
  2564. }
  2565. if (rowsPdf.length >0){
  2566. rows = rows.concat(rowsPdf);
  2567. }
  2568. }
  2569. if (rows.length > 0){
  2570. rows.push({
  2571. number: "Total en "+company,
  2572. supplier_invoice_number: "",
  2573. partner: "",
  2574. date: "",
  2575. date_invoice: "",
  2576. user: "",
  2577. currency: "",
  2578. amount_total: accounting.formatNumber((amount),2,".",","),
  2579. journal_id : "",
  2580. currency_id : "",
  2581. partner_id : ""
  2582. });
  2583. }
  2584. return rows;
  2585. },
  2586. // imprimir PDF
  2587. clickOnAction: function (e) {
  2588. var self = this;
  2589. var rowsNew;
  2590. var action = self.$el.find(e.target).val();
  2591. var table = self.$el.find("#table");
  2592. var data2 = table.bootstrapTable('getVisibleColumns');
  2593. var getColumns=[];
  2594. var rows=[];
  2595. rowsNew = self.getObjetPdf();
  2596. if (action === 'pdf') {
  2597. var dataNEW = _.map(data2, function (val){
  2598. return val.field;
  2599. });
  2600. _.each(rowsNew,function (item){
  2601. rows.push(_.pick(item, dataNEW));
  2602. });
  2603. // Obtener los nombre de la Cabezera
  2604. _.each(_.map(data2,function(val){
  2605. return val;
  2606. }), function(item){
  2607. getColumns.push([{
  2608. title: item.title,
  2609. dataKey: item.field
  2610. }]);
  2611. });
  2612. this.drawPDF(_.flatten(getColumns),rows);
  2613. }
  2614. },
  2615. // Generar pdfDoc
  2616. drawPDF: function (getColumns,rows) {
  2617. var self = this;
  2618. var sucusal = this.sucDescrip = this.$el.find('#current-journal option:selected').text();
  2619. var desde =(this.$el.find('#from').val());
  2620. var hasta =(this.$el.find('#to').val());
  2621. var totalPagesExp = "{total_pages_count_string}";
  2622. var pdfDoc = new jsPDF();
  2623. pdfDoc.autoTable(getColumns, rows, {
  2624. styles: { overflow: 'linebreak', fontSize: 8, columnWidth: 'wrap'},
  2625. columnStyles: {
  2626. number : {columnWidth: '8px'},
  2627. supplier_invoice_number : {columnWidth: '8px'},
  2628. partner : {columnWidth: '8px'},
  2629. date : {columnWidth: '8px'},
  2630. user : {columnWidth: '8px'},
  2631. currency : {columnWidth: '8px'},
  2632. amount_total: {halign:'right',columnWidth: '8px'},
  2633. },
  2634. margin: { top: 16, horizontal: 7},
  2635. addPageContent: function (data) {
  2636. pdfDoc.setFontSize(12);
  2637. pdfDoc.setFontStyle('bold');
  2638. pdfDoc.setTextColor(40);
  2639. pdfDoc.text('Listado de Compras '+ sucusal, data.settings.margin.left, 10);
  2640. if(desde.length > 0 || hasta.length > 0){
  2641. var fecha='';
  2642. if(desde){
  2643. fecha=fecha.concat(' Desde '+desde);
  2644. }
  2645. if (hasta){
  2646. fecha=fecha.concat(' Hasta '+hasta);
  2647. }
  2648. pdfDoc.setFontSize(10);
  2649. pdfDoc.setFontStyle('bold');
  2650. pdfDoc.setTextColor(40)
  2651. pdfDoc.text(fecha, data.settings.margin.left,14);
  2652. }
  2653. // FOOTER
  2654. var str = "Pagina " + data.pageCount;
  2655. // Total page number plugin only available in jspdf v1.0+
  2656. if (typeof pdfDoc.putTotalPages === 'function') {
  2657. str = str + " de " + totalPagesExp;
  2658. }
  2659. pdfDoc.setFontSize(9);
  2660. pdfDoc.setFontStyle('bold');
  2661. pdfDoc.setTextColor(40);
  2662. pdfDoc.text(str, data.settings.margin.left, pdfDoc.internal.pageSize.height - 5);
  2663. }
  2664. });
  2665. if (typeof pdfDoc.putTotalPages === 'function') {
  2666. pdfDoc.putTotalPages(totalPagesExp);
  2667. }
  2668. pdfDoc.save('Listado de Gastos.pdf')
  2669. },
  2670. });
  2671. // Proximo Report
  2672. instance.web.client_actions.add('eiru_reporting.action_report', 'instance.eiru_reporting.ReportingWidget');
  2673. }