· 6 years ago · Sep 04, 2019, 07:04 PM
1// ==UserScript==
2// @name Firmamuzyczna Automat
3// @version 1.0
4// @description Automatyczna obsługa sklepu
5// @author Sebastian Miecielica
6// @include https://b2b.firmamuzyczna.pl/admin*
7// @require https://code.jquery.com/jquery-1.12.4.min.js
8// @require https://cdnjs.cloudflare.com/ajax/libs/jquery.perfect-scrollbar/1.4.0/perfect-scrollbar.min.js
9// @resource ui-CSS https://firmamuzyczna.pl/automat/style.min.css?ver=38
10// @grant GM_addStyle
11// @grant GM_getResourceText
12// ==/UserScript==
13
14// Add stylesheet
15let uiCSS = GM_getResourceText("ui-CSS");
16GM_addStyle(uiCSS);
17
18// Global variables
19let App, Notifications, Events, perfectScrollbar;
20
21// Utills
22$(document).on("click", "#shop-automatation #toggle-navbar" , function(e) {
23 e.preventDefault();
24 $('#shop-automatation').toggleClass('toggled');
25});
26
27$(document).on("click", "#shop-automatation #save-configuration" , function(e) {
28 e.preventDefault();
29
30 $('#shop-automatation select').each(function(index, select){
31 App.set($(select).attr('data-key'), $(select).val());
32 });
33
34 $('#shop-automatation input[type=text]').each(function(index, select){
35 App.set($(select).attr('data-key'), $(select).val());
36 });
37
38 App.save();
39
40 // Button styling
41 let button = $(this);
42 button.text("Zapisano poprawnie");
43 button.addClass("saved");
44
45 setTimeout(function(){
46 button.text("Zapisz");
47 button.removeClass("saved");
48 }, 1500);
49});
50
51$(document).on('click', '#shop-automatation #notifications h4' , function() {
52 $('#notifications').toggleClass('toggled');
53});
54
55$(document).on('click', '.notifications-list .notification-one' , function() {
56 Notifications.makeRead($(this).attr('data-key'));
57 Notifications.list();
58});
59
60function generateRandomKey(){
61 return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 9);
62}
63
64function goToPage(url){
65 if(window.location.href != url){
66 window.location.href = url;
67
68 return true;
69 }else{
70 return false;
71 }
72}
73
74function getCurrentDateTime(){
75 let today = new Date();
76 let date = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();
77 let time = today.getHours() + ":" + (today.getMinutes() < 10 ? '0' : '') + today.getMinutes() + ":" + today.getSeconds();
78 return date + ' ' + time;
79}
80
81// Configration/app object
82let Configuration = {
83 login: 'miecielica', // Shoper login
84 password: '4aWcmyni3p', // Shoper password
85 active: 0, // If active automatation
86 sendProforma: 0, // If active sending proforma invoice
87 sendVAT: 0, // If active sending vat invoice
88 generateShipping: 0, // If active generate shipping
89 payment18: '', // Payment ID 18
90 payment19: '', // Payment ID 19
91 payment21: '', // Payment ID 21
92 logIn: function(){ // Log in to Shoper
93 if($('.login-box').length > 0){
94 $('.login-box input[name=login]').val(this.get('login'));
95 $('.login-box input[name=password').val(this.get('password'));
96 $('.login-box button[type=submit]').click();
97 }else{
98 return true;
99 }
100 },
101 set: function(key, value){ // Setter
102 this[key] = value;
103 },
104 get: function(key){ // Getter
105 return this[key];
106 },
107 save: function(){ // Save configuration to localstorage
108 let configurationArray = new Array();
109 configurationArray.push({'name': 'active', 'value' : this.get('active')});
110 configurationArray.push({'name': 'sendProforma', 'value' : this.get('sendProforma')});
111 configurationArray.push({'name': 'sendVAT', 'value' : this.get('sendVAT')});
112 configurationArray.push({'name': 'generateShipping', 'value' : this.get('generateShipping')});
113 configurationArray.push({'name': 'payment18', 'value' : this.get('payment18')});
114 configurationArray.push({'name': 'payment19', 'value' : this.get('payment19')});
115 configurationArray.push({'name': 'payment21', 'value' : this.get('payment21')});
116
117 localStorage.setItem('b2bFirmamuzycznaConfiguration', JSON.stringify(configurationArray)); // Save config array to localstorage
118 },
119 load: function(){ // Load config from localStorage
120 let newConfiguration = JSON.parse(localStorage.getItem('b2bFirmamuzycznaConfiguration')); // Load and parse from localStorage
121
122 if(newConfiguration){
123 $(newConfiguration).each(function(key, config){
124 App.set(config['name'], config['value']);
125 });
126
127 App.save();
128 }
129 },
130 generateNavbar: function(){
131 let html = '';
132
133 // #shop-automatation start
134 html += '<div id="shop-automatation">';
135
136 // Toggle button
137 html += '<a id="toggle-navbar" href="#" title="Pokaż opcje">Pokaż opcje</a>';
138
139 // #content-wrapper start
140 html += '<div class="content-wrapper">';
141
142 // title 1
143 html += '<h4>Ustawienia automatyzacji</h4>';
144
145 // #form start
146 html += '<div id="form">';
147
148 // active
149 html += '<div class="form-group">';
150 html += '<label for="question-active">Automatyzacja sklepu</label>';
151 html += '<select class="form-control" id="question-active" data-key="active">';
152
153 if(this.get('active') == 1){
154 html += '<option value="1" selected>tak</option>';
155 html += '<option value="0">nie</option>';
156 }else{
157 html += '<option value="1">tak</option>';
158 html += '<option value="0" selected>nie</option>';
159 }
160
161 html += '</select>';
162 html += '</div>';
163
164 // sendProforma
165 html += '<div class="form-group">';
166 html += '<label for="question-sendproforma">Wysyłka faktur proforma</label>';
167 html += '<select class="form-control" id="question-sendproforma" data-key="sendProforma">';
168 if(this.get('sendProforma') == 1){
169 html += '<option value="1" selected>tak</option>';
170 html += '<option value="0">nie</option>';
171 }else{
172 html += '<option value="1">tak</option>';
173 html += '<option value="0" selected>nie</option>';
174 }
175 html += '</select>';
176 html += '</div>';
177
178 // generateShipping
179 html += '<div class="form-group">';
180 html += '<label for="question-generateshipping">Generowanie listu przewozowego</label>';
181 html += '<select class="form-control" id="question-generateshipping" data-key="generateShipping">';
182 if(this.get('generateShipping') == 1){
183 html += '<option value="1" selected>tak</option>';
184 html += '<option value="0">nie</option>';
185 }else{
186 html += '<option value="1">tak</option>';
187 html += '<option value="0" selected>nie</option>';
188 }
189 html += '</select>';
190 html += '</div>';
191
192 // sendVat
193 html += '<div class="form-group">';
194 html += '<label for="question-sendvat">Wysyłka faktur VAT</label>';
195 html += '<select class="form-control" id="question-sendvat" data-key="sendVAT">';
196 if(this.get('sendVAT') == 1){
197 html += '<option value="1" selected>tak</option>';
198 html += '<option value="0">nie</option>';
199 }else{
200 html += '<option value="1">tak</option>';
201 html += '<option value="0" selected>nie</option>';
202 }
203 html += '</select>';
204 html += '</div>';
205
206 // title 2
207 html += '<h4>Płatności odroczone</h4>';
208
209 // Przelew - TERMIN 7 DNI
210 html += '<div class="form-group">';
211 html += '<label for="payment-18-users">Przelew - TERMIN 7 DNI</label>';
212 html += '<input type="text" placeholder="Lista ID klientów z płatnością 7 dni" class="form-control" value="' + this.get('payment18') + '" id="payment-18-users" data-key="payment18">';
213 html += '</div>';
214
215 // Przelew - TERMIN 14 DNI
216 html += '<div class="form-group">';
217 html += '<label for="payment-19-users">Przelew - TERMIN 14 DNI</label>';
218 html += '<input type="text" placeholder="Lista ID klientów z płatnością 14 dni" class="form-control" value="' + this.get('payment19') + '" id="payment-19-users" data-key="payment19">';
219 html += '</div>';
220
221 // Przelew - TERMIN 30 DNI
222 html += '<div class="form-group">';
223 html += '<label for="payment-21-users">Przelew - TERMIN 30 DNI (faktoring)</label>';
224 html += '<input type="text" placeholder="Lista ID klientów z płatnością 30 dni" class="form-control" value="' + this.get('payment21') + '" id="payment-21-users" data-key="payment21">';
225 html += '</div>';
226
227 // button
228 html += '<button id="save-configuration" class="btn">Zapisz</button>';
229
230 // #form end
231 html += '</div>';
232
233 // #content-wrapper end
234 html += '</div>';
235
236 // #notifications start
237 html += '<div id="notifications">';
238
239 // title
240 html += '<h4>Powiadomienia <span class="notifications-count">0</span></h4>';
241
242 // list of notifications
243 html += '<div class="notifications-list-wrapper"><div class="notifications-list"></div></div>';
244
245 // #notifications end
246 html += '</div>';
247
248 // #shop-automatation end
249 html += '</div>';
250
251 $('body').prepend(html);
252
253 // Add perfect scrollbar
254 perfectScrollbar = new PerfectScrollbar('.notifications-list-wrapper');
255 }
256}
257
258// Notification
259// Types: 1 - successfull, 2 - error, 3 - info
260let Notification = {
261 count: 0, // Notification counter
262 add: function(type, orderId, message){ // Add new message
263 let currentNotifications = JSON.parse(localStorage.getItem('b2bFirmamuzycznaNotification')); // Load and parse from localStorage
264
265 if(currentNotifications == null){currentNotifications = new Array();}
266 currentNotifications.push({'key': generateRandomKey(), 'date': getCurrentDateTime(), 'type': type, 'orderId': orderId, message: message, unread: 1}); // Ad new message
267
268 localStorage.setItem('b2bFirmamuzycznaNotification', JSON.stringify(currentNotifications)); // Save notifications
269
270 this.setCount(parseInt(this.getCount)+1);
271 perfectScrollbar.update();
272 },
273 list: function(){ // List of messages
274 let notifications = JSON.parse(localStorage.getItem('b2bFirmamuzycznaNotification')); // Load and parse from localStorage
275
276 if(notifications && notifications.length > 0){
277 $('#notifications .notifications-list').html(''); // Clear list
278
279 let unreadCount = 0;
280 $(notifications).each(function(index, notification){ // Append to notification-list block
281 $('#notifications .notifications-list').prepend('<div class="notification-one unread-' + notification.unread + ' type-' + notification.type + '" data-key="' + notification.key + '"><p class="info"><span class="orderId">#' + notification.orderId + '</span><span class="date">' + notification.date + '</span></p><p class="notification-message">' + notification.message + '</p></div>');
282
283 // Set counter
284 if(notification.unread){
285 unreadCount++;
286 }
287 });
288
289 this.setCount(unreadCount);
290 }else{
291 $('#notifications .notifications-list').html('<p class="empty-notifications">Brak powiadomień.</p>'); // Show empty info
292 }
293
294 perfectScrollbar.update();
295 },
296 setCount: function(value){ // Set notification counter
297 if(value){
298 this.count = value;
299 }else{
300 this.count = 0;
301 }
302
303 // Update view
304 $('#notifications .notifications-count').html(value);
305 },
306 getCount: function(){ // Get number of notifications
307 return this.count;
308 },
309 makeRead: function(key){ // Set as read notification
310 let notifications = JSON.parse(localStorage.getItem('b2bFirmamuzycznaNotification')); // Load and parse from localStorage
311
312 $(notifications).each(function(index, notification){
313 if(notification.key == key){ // Find notification
314 notification.unread = 0; // Update unread value
315 }
316 });
317
318 this.setCount(parseInt(this.getCount)-1); // Set counter
319 localStorage.setItem('b2bFirmamuzycznaNotification', JSON.stringify(notifications)); // Save
320 }
321}
322// EventObject
323let EventObject = {
324 queue: [],
325 currentEvent: 0,
326 init: function(){
327 // Check if app enabled
328 if(App.get('active')){
329 this.load();
330
331 if(this.queue == null){this.queue = new Array();} // Fix with array
332
333 let that = this;
334
335 setInterval(function(){
336 if(that.currentEvent != null && that.currentEvent != 0){
337 that.runEvent(); // Run events from queue
338 }else{
339 that.queryAPI(); // Query API for new events
340 }
341 }, 30000);
342 }
343 },
344 save: function(){ // Save configuration to localstorage
345 localStorage.setItem('b2bFirmamuzycznaCurrentEvent', JSON.stringify(this.currentEvent)); // Save current event
346 localStorage.setItem('b2bFirmamuzycznaEvent', JSON.stringify(this.queue)); // Save events array to localstorage
347 },
348 load: function(){ // Load config from localStorage
349 let newCurrentEvent = JSON.parse(localStorage.getItem('b2bFirmamuzycznaCurrentEvent')); // Load and parse from localStorage
350 this.currentEvent = newCurrentEvent;
351
352 let newEvents = JSON.parse(localStorage.getItem('b2bFirmamuzycznaEvent')); // Load and parse from localStorage
353 this.queue = newEvents;
354 },
355 add: function(orderId, eventName, bundles){ // Add new event
356 if(!this.ifExist(orderId, eventName, bundles)){
357 this.queue.push({'orderId': orderId, 'event': eventName, 'bundles': bundles});
358 }
359
360 this.save(); // Save with new event
361 },
362 ifExist: function(orderId, eventName){ // Check if event exists
363 let count = 0;
364
365 $(this.queue).each(function(index, event){
366 if(event.orderId == orderId && event.event == eventName){
367 count++;
368 }
369 });
370
371 if(count == 0){
372 return 0;
373 }else{
374 return 1;
375 }
376 },
377 queryAPI: function(){ // Query API for new events
378 let that = this;
379
380 $.ajax({
381 dataType: "json",
382 url: "https://www.firmamuzyczna.pl/automat/getOrders",
383 success: function(dataArray){
384 $(dataArray).each(function(index, event){
385 that.add(event.orderId, event.event, event.bundles);
386 });
387
388 that.runEvent();
389 }
390 });
391 },
392 runEvent: function(){ // Run events every 30 seconds
393 if(this.currentEvent != null && this.currentEvent != 0){
394 let that = this;
395
396 switch(this.currentEvent.event){
397 case 'changePayment':
398 if(!goToPage('https://b2b.firmamuzyczna.pl/admin/orders/edit/id/' + that.currentEvent.orderId)){
399 // Change slect with payment
400 $('#payment').val(that.currentEvent.value).change();
401
402 setTimeout(function(){
403 // Save and quit
404 $('div[data-tab-page="1.1"] form button[name=save]').click();
405
406 // Clear currentEvent
407 that.currentEvent = 0;
408 that.save();
409 }, 1000);
410 }
411
412 break;
413 case 'sendProforma':
414 // Check if sending proforma enabled
415 if(App.get('sendProforma') == 1){
416 if(!goToPage('https://b2b.firmamuzyczna.pl/admin/orders/view/id/' + that.currentEvent.orderId)){
417 // Find payment type
418 let paymentType = $('#order-field-paid-full').find('span').eq(0).text();
419
420 // Temporary value for company account
421 let companyAccount;
422
423 // Save temp order id
424 let orderId = that.currentEvent.orderId;
425
426 // Find client id
427 let clientId;
428 $('.dialog-content a').each(function(index, anchor){
429 if($(anchor).attr('href') && $(anchor).attr('href').includes('/admin/customers/edit/id/')){
430 clientId = parseInt($(anchor).attr('href').replace('/admin/customers/edit/id/',''));
431 }
432 });
433
434 // Check payment groups
435 if($.map(App.get('payment18').split(','), Number).includes(clientId) && paymentType != 'Przelew - TERMIN 7 DNI'){
436 let eventObject = {'orderId': that.currentEvent.orderId, 'event':'changePayment','value':18};
437 that.currentEvent = eventObject;
438 that.save();
439
440 goToPage('https://b2b.firmamuzyczna.pl/admin/orders/edit/id/' + orderId);
441 }else if($.map(App.get('payment19').split(','), Number).includes(clientId) && paymentType != 'Przelew - TERMIN 14 DNI'){
442 let eventObject = {'orderId': that.currentEvent.orderId, 'event':'changePayment','value':19};
443 that.currentEvent = eventObject;
444 that.save();
445
446 goToPage('https://b2b.firmamuzyczna.pl/admin/orders/edit/id/' + orderId);
447 }else if($.map(App.get('payment21').split(','), Number).includes(clientId) && paymentType != 'Przelew - TERMIN 30 DNI (faktoring)'){
448 let eventObject = {'orderId': that.currentEvent.orderId, 'event':'changePayment','value':21};
449 that.currentEvent = eventObject;
450 that.save();
451
452 goToPage('https://b2b.firmamuzyczna.pl/admin/orders/edit/id/' + orderId);
453 }else{
454 // Set invoice time
455 switch(paymentType){
456 case 'Przelew - TERMIN 7 DNI':
457 paymentType = 7;
458 break;
459 case 'Przelew - TERMIN 14 DNI':
460 paymentType = 14;
461 break;
462 case 'Przelew - TERMIN 30 DNI (faktoring)':
463 paymentType = 30;
464 companyAccount = 122052;
465 break;
466 case 'Przelew - TERMIN 60 DNI (faktoring)':
467 paymentType = 60;
468 companyAccount = 122052;
469 break;
470 case 'Przelew - TERMIN 90 DNI (faktoring)':
471 paymentType = 90;
472 companyAccount = 122052;
473 break;
474 default:
475 paymentType = 7;
476 break;
477 }
478
479 // Open invoice link
480 $.ajax({
481 url: 'https://b2b.firmamuzyczna.pl/admin/plugin/execute/plugin/AppStore-Page/act/frame/link/1/id/' + that.currentEvent.orderId + '?insideModal=1',
482 type: 'post',
483 dataType: 'html',
484 success: function (data) {
485 let src = $(data).filter('iframe').attr("data-appstore");
486
487 if(src && src != 'undefined'){
488 // Add notification about successfull generation
489 Notifications.add(1, that.currentEvent.orderId, "Pomyślnie wygenerowano fakturę Proforma.");
490
491 // Clear currentEvent
492 that.currentEvent = 0;
493 that.save();
494
495 // Open proforma window
496 window.open(src + '&event=sendProforma&paymentType=' + paymentType + '&companyAccount=' + companyAccount);
497 }
498 }
499 });
500 }
501 }
502 }
503 break;
504 case 'generateShipping':
505 // Check if generating shipping enabled
506 if(App.get('generateShipping') == 1){
507 if(!goToPage('https://b2b.firmamuzyczna.pl/admin/orders/view/id/' + that.currentEvent.orderId)){
508 // Click the button
509 // If parcel already exist - clear this event
510 if($('.parcel-edit').length > 0){
511 $('body').append('<script>setTimeout(function(){$$(".parcel-edit").fireEvent("mousedown", this);}, 1000);</script>');
512 }else{
513 that.currentEvent = 0;
514 that.save();
515 }
516
517 // Save payment type
518 let paymentType = $('#order-field-paid-full').find('span').eq(0).text();
519
520 // Check if modal exists
521 let checkModal = setInterval(function(){
522 if($('.edition-form #cod').length > 0){
523 clearInterval(checkModal);
524
525 // Set COD
526 if(paymentType == "POBRANIE"){
527 $('.edition-form #cod').prop('checked', true).change();
528 $('.edition-form #insurance').prop('checked', true).change();
529 }
530
531 // dl x szer x wys
532 $.ajax({
533 url: 'https://www.firmamuzyczna.pl/automat/getPackageSize/index.php?id=' + that.currentEvent.orderId,
534 type: 'get',
535 dataType: 'json',
536 success: function (data) {
537 if(data.status == "success"){
538 // Load package size from API
539 $('.edition-form #apaczka_shipment_dimension_1').val(data.dimensions.length);
540 $('.edition-form #apaczka_shipment_dimension_2').val(data.dimensions.width);
541 $('.edition-form #apaczka_shipment_dimension_3').val(data.dimensions.height);
542
543 // Send with POCZTEX if big package
544 if(data.box_type == "Karton nr 3" || data.box_type == "Karton nr 4"){
545 $('#apaczka_courier_type').val('POCZTA_POLSKA_E24').change();
546 }
547
548 Notifications.add(1, that.currentEvent.orderId, "Pomyślnie wygenerowano list przewozowy.");
549
550 $('.edition-form .save-button').click();
551 }else if(data.status == "error"){
552 // Refresh page with error
553 goToPage('https://b2b.firmamuzyczna.pl/admin/orders/view/id/' + that.currentEvent.orderId)
554 }
555 }
556 });
557 }
558 }, 1000);
559 }
560 }
561 break;
562 case 'sendVAT':
563 if(!goToPage('https://b2b.firmamuzyczna.pl/admin/orders/view/id/' + that.currentEvent.orderId)){
564 // Find payment type
565 let paymentType = $('#order-field-paid-full').find('span').eq(0).text();
566
567 // Temporary value for company account
568 let companyAccount;
569
570 // Check if sending proforma enabled
571 if(App.get('sendVAT') == 1){
572 // Set invoice time
573 switch(paymentType){
574 case 'Przelew - TERMIN 7 DNI':
575 paymentType = 7;
576 break;
577 case 'Przelew - TERMIN 14 DNI':
578 paymentType = 14;
579 break;
580 case 'Przelew - TERMIN 30 DNI (faktoring)':
581 paymentType = 30;
582 companyAccount = 122052;
583 break;
584 case 'Przelew - TERMIN 60 DNI (faktoring)':
585 paymentType = 60;
586 companyAccount = 122052;
587 break;
588 case 'Przelew - TERMIN 90 DNI (faktoring)':
589 paymentType = 90;
590 companyAccount = 122052;
591 break;
592 default:
593 paymentType = 7;
594 break;
595 }
596
597 // Open invoice link
598 $.ajax({
599 url: 'https://b2b.firmamuzyczna.pl/admin/plugin/execute/plugin/AppStore-Page/act/frame/link/1/id/' + that.currentEvent.orderId + '?insideModal=1',
600 type: 'post',
601 dataType: 'html',
602 success: function (data) {
603 let src = $(data).filter('iframe').attr("data-appstore");
604
605 if(src && src != 'undefined'){
606 // Add notification about successfull generation
607 Notifications.add(1, that.currentEvent.orderId, "Pomyślnie wygenerowano fakturę VAT.");
608
609 // Temp bundles
610 let tempBundles = that.currentEvent.bundles;
611
612 // Clear currentEvent
613 that.currentEvent = 0;
614 that.save();
615
616 // Open proforma window with wifrma or not
617 if(tempBundles){
618 window.open(src + '&event=sendVAT&issue_again=1&paymentType=' + paymentType + '&companyAccount=' + companyAccount + '&bundles=' + encodeURIComponent(JSON.stringify(tempBundles)) + '&courier=' + $('.list-shipment .cell-shipment-form').text().replace(/ /g,'').replace(/(\r\n|\n|\r)/gm, "") + '&trackingNumber=' + $('.list-shipment .cell-shipping-code').text().replace(/ /g,'').replace(/(\r\n|\n|\r)/gm, ""));
619 }else{
620 window.open(src + '&event=sendVAT&issue_again=1&paymentType=' + paymentType + '&companyAccount=' + companyAccount + '&courier=' + $('.list-shipment .cell-shipment-form').text().replace(/ /g,'').replace(/(\r\n|\n|\r)/gm, "") + '&trackingNumber=' + $('.list-shipment .cell-shipping-code').text().replace(/ /g,'').replace(/(\r\n|\n|\r)/gm, ""));
621 }
622 }
623 }
624 });
625 }
626 }
627 break;
628 }
629 }else{
630 if(this.queue && this.queue.length > 0){ // If queue of events exisits
631 let event = this.queue[0]; // Taking the first element
632 this.currentEvent = event; // Setting current event
633 this.queue.splice(0, 1); // Drop element
634 this.save();
635 }
636 }
637 }
638}
639
640$(document).ready(function(){
641 App = Configuration;
642 Notifications = Notification;
643 Events = EventObject;
644
645 if(App.logIn()){
646 // Run App
647 App.load();
648 App.generateNavbar();
649
650 // Run notifications
651 Notifications.list();
652
653 // Run events
654 Events.init();
655 }
656});