From 76d6e2d4b7ce71bf3b090b0042125e4986b92c0e Mon Sep 17 00:00:00 2001
From: carlosjr <carlosjr@verdnatura.es>
Date: Fri, 5 Feb 2021 15:26:49 +0100
Subject: [PATCH 01/10] worker added to supplier basic data and summary

---
 .../10281-valentineDay/00-supplierWorker.sql  |  2 +
 db/changes/10281-valentineDay/delete.keep     |  0
 db/dump/fixtures.sql                          |  8 +--
 .../back/methods/supplier/getSummary.js       | 15 +++++-
 modules/supplier/back/models/supplier.json    | 54 +++++++++++--------
 modules/supplier/front/basic-data/index.html  | 11 ++++
 .../supplier/front/basic-data/locale/es.yml   |  3 +-
 modules/supplier/front/summary/index.html     |  7 +++
 modules/supplier/front/summary/locale/es.yml  |  3 +-
 9 files changed, 73 insertions(+), 30 deletions(-)
 create mode 100644 db/changes/10281-valentineDay/00-supplierWorker.sql
 delete mode 100644 db/changes/10281-valentineDay/delete.keep

diff --git a/db/changes/10281-valentineDay/00-supplierWorker.sql b/db/changes/10281-valentineDay/00-supplierWorker.sql
new file mode 100644
index 0000000000..c35a86a230
--- /dev/null
+++ b/db/changes/10281-valentineDay/00-supplierWorker.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `vn`.`supplier` ADD COLUMN `workerFk` INT(11) NULL DEFAULT NULL COMMENT 'Responsible for approving invoices' AFTER `isTrucker`;
+ALTER TABLE `vn`.`supplier` ADD CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/db/changes/10281-valentineDay/delete.keep b/db/changes/10281-valentineDay/delete.keep
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql
index 8742c161f1..7c1ee93f00 100644
--- a/db/dump/fixtures.sql
+++ b/db/dump/fixtures.sql
@@ -1233,11 +1233,11 @@ INSERT INTO `vn`.`annualAverageInvoiced`(`clientFk`, `invoiced`)
         (104, 500),
         (105, 5000);
 
-INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`,`isFarmer`,`commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`)
+INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`,`isFarmer`,`commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`)
     VALUES
-        (1,   'Plants SL',             'Plants nick',   4100000001, 1, '06089160W', 0, 0, CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4,  1, 1),
-        (2,   'Farmer King',           'The farmer',    4000020002, 1, '87945234L', 1, 0, CURDATE(), 1, 'supplier address 2', 'SILLA',      2, 43022, 1, 2, 10, 93, 2, 8),
-        (442, 'Verdnatura Levante SL', 'Verdnatura',    5115000442, 1, '06815934E', 0, 0, CURDATE(), 1, 'supplier address 3', 'SILLA',      1, 43022, 1, 2, 15, 6,  9, 3);
+        (1,   'Plants SL',             'Plants nick',   4100000001, 1, '06089160W', 0, 0, CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4,  1, 1, 18),
+        (2,   'Farmer King',           'The farmer',    4000020002, 1, '87945234L', 1, 0, CURDATE(), 1, 'supplier address 2', 'SILLA',      2, 43022, 1, 2, 10, 93, 2, 8, 18),
+        (442, 'Verdnatura Levante SL', 'Verdnatura',    5115000442, 1, '06815934E', 0, 0, CURDATE(), 1, 'supplier address 3', 'SILLA',      1, 43022, 1, 2, 15, 6,  9, 3, 18);
 
 INSERT INTO `vn`.`supplierContact`(`id`, `supplierFk`, `phone`, `mobile`, `email`, `observation`, `name`)
     VALUES
diff --git a/modules/supplier/back/methods/supplier/getSummary.js b/modules/supplier/back/methods/supplier/getSummary.js
index e6509eaa24..1148c16cb2 100644
--- a/modules/supplier/back/methods/supplier/getSummary.js
+++ b/modules/supplier/back/methods/supplier/getSummary.js
@@ -42,6 +42,7 @@ module.exports = Self => {
                 'sageTaxTypeFk',
                 'sageTransactionTypeFk',
                 'sageWithholdingFk',
+                'workerFk'
             ],
             include: [
                 {
@@ -85,7 +86,19 @@ module.exports = Self => {
                     scope: {
                         fields: ['id', 'withholding']
                     }
-                }
+                },
+                {
+                    relation: 'worker',
+                    scope: {
+                        fields: ['userFk'],
+                        include: {
+                            relation: 'user',
+                            scope: {
+                                fields: ['nickname']
+                            }
+                        }
+                    }
+                },
             ]
         };
         let supplier = await Self.app.models.Supplier.findOne(filter);
diff --git a/modules/supplier/back/models/supplier.json b/modules/supplier/back/models/supplier.json
index eb3c5989e6..4ec568c8be 100644
--- a/modules/supplier/back/models/supplier.json
+++ b/modules/supplier/back/models/supplier.json
@@ -11,75 +11,78 @@
     },
     "properties": {
         "id": {
-            "type": "Number",
+            "type": "number",
             "id": true,
             "description": "Identifier"
         },
         "name": {
-            "type": "String"
+            "type": "string"
         },
         "account": {
-            "type": "String"
+            "type": "string"
         },
         "countryFk": {
-            "type": "Number"
+            "type": "number"
         },
         "nif": {
-            "type": "String"
+            "type": "string"
         },
         "isFarmer": {
-            "type": "Boolean"
+            "type": "boolean"
         },
         "phone": {
-            "type": "Number"
+            "type": "number"
         },
         "retAccount": {
-            "type": "Number"
+            "type": "number"
         },
         "commission": {
-            "type": "Boolean"
+            "type": "boolean"
         },
         "created": {
-            "type": "Date"
+            "type": "date"
         },
         "postcodeFk": {
-            "type": "Number"
+            "type": "number"
         },
         "isActive": {
-            "type": "Boolean"
+            "type": "boolean"
         },
         "isOfficial": {
-            "type": "Boolean"
+            "type": "boolean"
         },
         "isSerious": {
-            "type": "Boolean"
+            "type": "boolean"
         },
         "note": {
-            "type": "String"
+            "type": "string"
         },
         "street": {
-            "type": "String"
+            "type": "string"
         },
         "city": {
-            "type": "String"
+            "type": "string"
         },
         "provinceFk": {
-            "type": "Number"
+            "type": "number"
         },
         "postCode": {
-            "type": "String"
+            "type": "string"
         },
         "payMethodFk": {
-            "type": "Number"
+            "type": "number"
         },
         "payDemFk": {
-            "type": "Number"
+            "type": "number"
         },
         "payDay": {
-            "type": "Number"
+            "type": "number"
         },
         "nickname": {
-            "type": "String"
+            "type": "string"
+        },
+        "workerFk": {
+            "type": "number"
         },
         "sageTaxTypeFk": {
 			"type": "number",
@@ -126,6 +129,11 @@
             "model": "Client",
             "foreignKey": "nif",
             "primaryKey": "fi"
+        },
+        "worker": {
+            "type": "belongsTo",
+            "model": "Worker",
+            "foreignKey": "workerFk"
         },
 		"sageTaxType": {
 			"type": "belongsTo",
diff --git a/modules/supplier/front/basic-data/index.html b/modules/supplier/front/basic-data/index.html
index 72accfb5f3..8d5376f1f8 100644
--- a/modules/supplier/front/basic-data/index.html
+++ b/modules/supplier/front/basic-data/index.html
@@ -15,6 +15,17 @@
                 rule
                 vn-focus>
             </vn-textfield>
+            <vn-autocomplete
+                vn-one
+                ng-model="$ctrl.supplier.workerFk"
+                url="Clients/activeWorkersWithRole"
+                search-function="{firstName: $search}"
+                show-field="nickname"
+                value-field="id"
+                where="{role: 'employee'}"
+                label="Sales person"
+                info="Responsible for approving invoices">
+            </vn-autocomplete>
         </vn-horizontal>
         <vn-horizontal>
             <vn-check
diff --git a/modules/supplier/front/basic-data/locale/es.yml b/modules/supplier/front/basic-data/locale/es.yml
index a24df93837..56811d35bf 100644
--- a/modules/supplier/front/basic-data/locale/es.yml
+++ b/modules/supplier/front/basic-data/locale/es.yml
@@ -1,3 +1,4 @@
 Notes: Notas
 Active: Activo
-Verified: Verificado
\ No newline at end of file
+Verified: Verificado
+Responsible for approving invoices: Responsable de aprobar las facturas
\ No newline at end of file
diff --git a/modules/supplier/front/summary/index.html b/modules/supplier/front/summary/index.html
index b089f25e93..51ebde6951 100644
--- a/modules/supplier/front/summary/index.html
+++ b/modules/supplier/front/summary/index.html
@@ -31,6 +31,13 @@
                     label="Alias" 
                     value="{{::$ctrl.summary.nickname}}">
                 </vn-label-value>
+                <vn-label-value label="Responsible">
+                    <span 
+                        ng-click="workerDescriptor.show($event, $ctrl.summary.workerFk)"
+                        class="link">
+                        {{$ctrl.summary.worker.user.nickname}}
+                    </span>
+                </vn-label-value>
                 <vn-label-value no-ellipsize
                     label="Notes" 
                     value="{{::$ctrl.summary.note}}">
diff --git a/modules/supplier/front/summary/locale/es.yml b/modules/supplier/front/summary/locale/es.yml
index 6afaf857dc..512b75f9d4 100644
--- a/modules/supplier/front/summary/locale/es.yml
+++ b/modules/supplier/front/summary/locale/es.yml
@@ -6,4 +6,5 @@ Is Farmer: Es agrícola
 Sage tax type: Tipo de impuesto Sage
 Sage transaction type: Tipo de transacción Sage
 Sage withholding: Retencion Sage
-Go to the supplier: Ir al proveedor
\ No newline at end of file
+Go to the supplier: Ir al proveedor
+Responsible: Responsable
\ No newline at end of file

From 623b90279ba7856b7e420df5a90369f95e78397f Mon Sep 17 00:00:00 2001
From: joan <joan@verdnatura.es>
Date: Mon, 8 Feb 2021 07:28:00 +0100
Subject: [PATCH 02/10] Update dms fix access

---
 back/methods/dms/updateFile.js | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/back/methods/dms/updateFile.js b/back/methods/dms/updateFile.js
index 4182148f7c..314761932b 100644
--- a/back/methods/dms/updateFile.js
+++ b/back/methods/dms/updateFile.js
@@ -38,8 +38,7 @@ module.exports = Self => {
         {
             arg: 'hasFile',
             type: 'Boolean',
-            description: 'True if has an attached file',
-            required: true
+            description: 'True if has an attached file'
         },
         {
             arg: 'hasFileAttached',

From b3f5559fc3fc8ce4befa96de5360015326f1f9fd Mon Sep 17 00:00:00 2001
From: joan <joan@verdnatura.es>
Date: Mon, 8 Feb 2021 07:30:36 +0100
Subject: [PATCH 03/10] Updated node version

---
 Jenkinsfile | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/Jenkinsfile b/Jenkinsfile
index 8f87ffe610..85914ad623 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -49,7 +49,7 @@ pipeline {
                 NODE_ENV = ""
             }
             steps {
-                nodejs('node-lts') {
+                nodejs('node-v12') {
                     sh 'npm install --no-audit --prefer-offline'
                     sh 'gulp install --ci'
                 }
@@ -66,14 +66,14 @@ pipeline {
             parallel {
                 stage('Frontend') {
                     steps {
-                        nodejs('node-lts') {
+                        nodejs('node-v12') {
                             sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2'
                         }
                     }
                 }
                 // stage('Backend') {
                 //     steps {
-                //         nodejs('node-lts') {
+                //         nodejs('node-v12') {
                 //             sh 'gulp launchBackTest --ci'
                 //         }
                 //     }
@@ -89,7 +89,7 @@ pipeline {
                 CREDS = credentials('docker-registry')
             }
             steps {
-                nodejs('node-lts') {
+                nodejs('node-v12') {
                     sh 'gulp build'
                 }
 

From a62bebd51edf08885b180242ae3d3fab4408412a Mon Sep 17 00:00:00 2001
From: carlosjr <carlosjr@verdnatura.es>
Date: Mon, 8 Feb 2021 10:14:41 +0100
Subject: [PATCH 04/10] minor refactor

---
 .../{00-supplierWorker.sql => 00-supplier.sql}                  | 0
 modules/supplier/front/basic-data/index.html                    | 2 +-
 2 files changed, 1 insertion(+), 1 deletion(-)
 rename db/changes/10281-valentineDay/{00-supplierWorker.sql => 00-supplier.sql} (100%)

diff --git a/db/changes/10281-valentineDay/00-supplierWorker.sql b/db/changes/10281-valentineDay/00-supplier.sql
similarity index 100%
rename from db/changes/10281-valentineDay/00-supplierWorker.sql
rename to db/changes/10281-valentineDay/00-supplier.sql
diff --git a/modules/supplier/front/basic-data/index.html b/modules/supplier/front/basic-data/index.html
index 8d5376f1f8..7d2f801a44 100644
--- a/modules/supplier/front/basic-data/index.html
+++ b/modules/supplier/front/basic-data/index.html
@@ -23,7 +23,7 @@
                 show-field="nickname"
                 value-field="id"
                 where="{role: 'employee'}"
-                label="Sales person"
+                label="Responsible"
                 info="Responsible for approving invoices">
             </vn-autocomplete>
         </vn-horizontal>

From 3d948ef317f615dab2dc90223dba104ef623ba75 Mon Sep 17 00:00:00 2001
From: carlosjr <carlosjr@verdnatura.es>
Date: Tue, 9 Feb 2021 10:43:19 +0100
Subject: [PATCH 05/10] warning color added lines with clientType loses

---
 .../10281-valentineDay/00-item_getBalance.sql | 137 ++++++++++++++++++
 db/changes/10281-valentineDay/delete.keep     |   0
 modules/item/back/methods/item/getBalance.js  |   6 +-
 .../methods/item/specs/getBalance.spec.js     |  33 +++++
 modules/item/front/diary/index.html           |  18 ++-
 5 files changed, 185 insertions(+), 9 deletions(-)
 create mode 100644 db/changes/10281-valentineDay/00-item_getBalance.sql
 delete mode 100644 db/changes/10281-valentineDay/delete.keep
 create mode 100644 modules/item/back/methods/item/specs/getBalance.spec.js

diff --git a/db/changes/10281-valentineDay/00-item_getBalance.sql b/db/changes/10281-valentineDay/00-item_getBalance.sql
new file mode 100644
index 0000000000..96c82cc016
--- /dev/null
+++ b/db/changes/10281-valentineDay/00-item_getBalance.sql
@@ -0,0 +1,137 @@
+DROP PROCEDURE `vn`.`item_getBalance`;
+
+DELIMITER $$
+$$
+CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`item_getBalance`(IN vItemId INT, IN vWarehouse INT)
+BEGIN
+    DECLARE vDateInventory DATETIME;
+    DECLARE vCurdate DATE DEFAULT CURDATE();
+    DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate);
+    
+    SELECT inventoried INTO vDateInventory FROM config;
+    SET @a = 0;
+	SET @currentLineFk = 0;
+    SET @shipped = '';
+    
+    SELECT DATE(@shipped:= shipped) shipped,
+		alertLevel,
+		stateName,
+		origin,
+		reference,
+		clientFk,
+		name,
+		`in`,
+		`out`,
+		@a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance,
+		@currentLineFk := IF (@shipped < CURDATE() 
+							OR (@shipped = CURDATE() AND (isPicked OR alertLevel >= 2)),
+						lineFk,@currentLineFk) lastPreparedLineFk,
+        isTicket,
+        lineFk,
+        isPicked,
+        clientType
+        FROM
+            ( SELECT  tr.landed AS shipped,
+                    b.quantity AS `in`,
+                    NULL AS `out`,
+                    al.alertLevel AS alertLevel,
+                    st.name AS stateName,
+                    s.name AS name,
+                    e.ref AS reference,
+                    e.id AS origin,
+                    s.id AS clientFk,
+                    IF(al.alertLevel = 3, TRUE, FALSE) isPicked,
+                    FALSE AS isTicket,
+                    b.id lineFk,
+                    NULL `order`,
+                    NULL AS clientType
+                FROM buy b
+                    JOIN entry e ON e.id = b.entryFk
+                    JOIN travel tr ON tr.id = e.travelFk
+                    JOIN supplier s ON s.id = e.supplierFk
+                    JOIN alertLevel al ON al.alertLevel = 
+						CASE
+							WHEN tr.shipped < CURDATE() THEN 3
+							WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3
+                            ELSE 0
+						END
+                    JOIN state st ON st.code = al.code
+                WHERE tr.landed >= vDateInventory
+                    AND vWarehouse = tr.warehouseInFk 
+                    AND b.itemFk = vItemId
+                    AND e.isInventory = FALSE
+					AND e.isRaid = FALSE
+            UNION ALL
+
+            SELECT tr.shipped,
+                    NULL as `in`,
+                    b.quantity AS `out`,
+                    al.alertLevel AS alertLevel,
+                    st.name AS stateName,
+                    s.name AS name,
+                    e.ref AS reference,
+                    e.id AS origin,
+                    s.id AS clientFk,
+                    IF(al.alertLevel = 3, TRUE, FALSE) isPicked,
+                    FALSE AS isTicket,
+                    b.id,
+                    NULL `order`,
+                    NULL AS clientType
+                FROM buy b
+                    JOIN entry e ON e.id = b.entryFk
+                    JOIN travel tr ON tr.id = e.travelFk
+                    JOIN warehouse w ON w.id = tr.warehouseOutFk
+                    JOIN supplier s ON s.id = e.supplierFk
+                    JOIN alertLevel al ON al.alertLevel = 
+						CASE
+							WHEN tr.shipped < CURDATE() THEN 3
+							WHEN tr.shipped = CURDATE() AND tr.isReceived = TRUE THEN 3
+                            ELSE 0
+						END
+                    JOIN state st ON st.code = al.code
+                WHERE tr.shipped >= vDateInventory
+                    AND vWarehouse =tr.warehouseOutFk
+                    AND s.id <> 4
+                    AND b.itemFk = vItemId
+                    AND e.isInventory = FALSE
+                    AND w.isFeedStock = FALSE
+					AND e.isRaid = FALSE
+            UNION ALL
+
+            SELECT DATE(t.shipped),
+                NULL as `in`,
+                s.quantity AS `out`,
+                al.alertLevel AS alertLevel,
+                st.name AS stateName,
+                t.nickname AS name,
+                t.refFk AS reference,
+                t.id AS origin,
+                t.clientFk,
+                stk.id AS isPicked,
+                TRUE AS isTicket,
+                s.id,
+				st.`order`,
+                ct.code AS clientType
+				FROM sale s
+                    JOIN ticket t ON t.id = s.ticketFk
+                    LEFT JOIN ticketState ts ON ts.ticket = t.id
+                    LEFT JOIN state st ON st.code = ts.code
+                    JOIN client c ON c.id = t.clientFk
+				    JOIN clientType ct ON ct.id = c.clientTypeFk
+                    JOIN alertLevel al ON al.alertLevel = 
+						CASE
+							WHEN t.shipped < curdate() THEN 3
+							WHEN t.shipped > util.dayEnd(curdate()) THEN 0
+                            ELSE IFNULL(ts.alertLevel, 0)
+						END
+					LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED'
+                    LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id
+                WHERE t.shipped >= vDateInventory
+                    AND s.itemFk = vItemId
+                    AND vWarehouse =t.warehouseFk
+				ORDER BY shipped, alertLevel DESC, isTicket, `order` DESC, isPicked DESC, `in` DESC, `out` DESC
+            ) AS itemDiary;
+        
+END$$
+DELIMITER ;
+
diff --git a/db/changes/10281-valentineDay/delete.keep b/db/changes/10281-valentineDay/delete.keep
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/modules/item/back/methods/item/getBalance.js b/modules/item/back/methods/item/getBalance.js
index 26fc2a7dc5..916757c463 100644
--- a/modules/item/back/methods/item/getBalance.js
+++ b/modules/item/back/methods/item/getBalance.js
@@ -20,8 +20,12 @@ module.exports = Self => {
     });
 
     Self.getBalance = async filter => {
-        let where = filter.where;
+        const where = filter.where;
         let [diary] = await Self.rawSql(`CALL vn.item_getBalance(?, ?)`, [where.itemFk, where.warehouseFk]);
+
+        for (const entry of diary)
+            if (entry.clientType === 'loses') entry.highlighted = true;
+
         return diary;
     };
 };
diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js
new file mode 100644
index 0000000000..671b8c1036
--- /dev/null
+++ b/modules/item/back/methods/item/specs/getBalance.spec.js
@@ -0,0 +1,33 @@
+const app = require('vn-loopback/server/server');
+const LoopBackContext = require('loopback-context');
+
+describe('item getBalance()', () => {
+    it('should return the balance lines of a client type loses in which one has highlighted true', async() => {
+        const activeCtx = {
+            accessToken: {userId: 9},
+        };
+        spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
+            active: activeCtx
+        });
+
+        const losesClientId = 111;
+        const ticket = await app.models.Ticket.findById(7);
+        const originalClientId = ticket.clientFk;
+        await ticket.updateAttribute('clientFk', losesClientId);
+
+        const filter = {
+            where: {
+                itemFk: 1,
+                warehouseFk: 1
+            }
+        };
+        const results = await app.models.Item.getBalance(filter);
+
+        const result = results.find(element => element.clientType == 'loses');
+
+        expect(result.highlighted).toBe(true);
+
+        // restores
+        await ticket.updateAttribute('clientFk', originalClientId);
+    });
+});
diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html
index 3fdc9a9e49..7c210a26a6 100644
--- a/modules/item/front/diary/index.html
+++ b/modules/item/front/diary/index.html
@@ -64,14 +64,16 @@
                     <vn-td>{{::sale.stateName | dashIfEmpty}}</vn-td>
                     <vn-td>{{::sale.reference | dashIfEmpty}}</vn-td>
                     <vn-td class="truncate" expand>
-                        <span ng-if="::!sale.isTicket">
-                            {{::sale.name | dashIfEmpty}}
-                        </span>
-                        <span
-                            ng-if="::sale.isTicket"
-                            vn-click-stop="clientDescriptor.show($event, sale.clientFk)"
-                            class="link">
-                            {{::sale.name | dashIfEmpty}}
+                        <span ng-class="::{'warning chip': sale.highlighted}">
+                            <span ng-if="::!sale.isTicket">
+                                {{::sale.name | dashIfEmpty}}
+                            </span>
+                            <span
+                                ng-if="::sale.isTicket"
+                                vn-click-stop="clientDescriptor.show($event, sale.clientFk)"
+                                class="link">
+                                {{::sale.name | dashIfEmpty}}
+                            </span>
                         </span>
                     </vn-td>
                     <vn-td number class="in">{{::sale.in | dashIfEmpty}}</vn-td>

From 8b97236f22478bdd902c574748bb5e0f8a43ce35 Mon Sep 17 00:00:00 2001
From: carlosjr <carlosjr@verdnatura.es>
Date: Tue, 9 Feb 2021 12:53:40 +0100
Subject: [PATCH 06/10] texfield no longer performs queries

---
 e2e/helpers/selectors.js           | 2 +-
 e2e/paths/04-item/04_tags.spec.js  | 8 ++++----
 modules/item/front/tags/index.html | 4 ++--
 3 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js
index fe35dcfe3b..ca521f4454 100644
--- a/e2e/helpers/selectors.js
+++ b/e2e/helpers/selectors.js
@@ -316,7 +316,7 @@ export default {
         fourthRelevancy: 'vn-item-tags vn-horizontal:nth-child(4) [ng-model="itemTag.priority"]',
         fourthRemoveTagButton: 'vn-item-tags vn-horizontal:nth-child(4) vn-icon-button[icon="delete"]',
         fifthTag: 'vn-item-tags vn-horizontal:nth-child(5) > vn-autocomplete[ng-model="itemTag.tagFk"]',
-        fifthValue: 'vn-item-tags vn-horizontal:nth-child(5) vn-textfield[ng-model="itemTag.value"]',
+        fifthValue: 'vn-item-tags vn-horizontal:nth-child(5) vn-autocomplete[ng-model="itemTag.value"]',
         fifthRelevancy: 'vn-item-tags vn-horizontal:nth-child(5) vn-input-number[ng-model="itemTag.priority"]',
         sixthTag: 'vn-item-tags vn-horizontal:nth-child(6) > vn-autocomplete[ng-model="itemTag.tagFk"]',
         sixthValue: 'vn-item-tags vn-horizontal:nth-child(6) vn-textfield[ng-model="itemTag.value"]',
diff --git a/e2e/paths/04-item/04_tags.spec.js b/e2e/paths/04-item/04_tags.spec.js
index 9f2a8e2952..574ff7562b 100644
--- a/e2e/paths/04-item/04_tags.spec.js
+++ b/e2e/paths/04-item/04_tags.spec.js
@@ -16,7 +16,7 @@ describe('Item create tags path', () => {
         await browser.close();
     });
 
-    it(`should create a new tag and delete a former one`, async() => {
+    it('should create a new tag and delete a former one', async() => {
         await page.waitToClick(selectors.itemTags.fourthRemoveTagButton);
         await page.waitToClick(selectors.itemTags.addItemTagButton);
         await page.autocompleteSearch(selectors.itemTags.seventhTag, 'Ancho de la base');
@@ -29,7 +29,7 @@ describe('Item create tags path', () => {
         expect(message.text).toContain('Data saved!');
     });
 
-    it(`should confirm the fourth row data is the expected one`, async() => {
+    it('should confirm the fourth row data is the expected one', async() => {
         await page.reloadSection('item.card.tags');
         await page.waitForSelector('vn-item-tags');
         let result = await page.waitToGetProperty(selectors.itemTags.fourthTag, 'value');
@@ -47,7 +47,7 @@ describe('Item create tags path', () => {
         expect(result).toEqual('4');
     });
 
-    it(`should confirm the fifth row data is the expected one`, async() => {
+    it('should confirm the fifth row data is the expected one', async() => {
         let tag = await page
             .waitToGetProperty(selectors.itemTags.fifthTag, 'value');
 
@@ -62,7 +62,7 @@ describe('Item create tags path', () => {
         expect(relevancy).toEqual('5');
     });
 
-    it(`should confirm the sixth row data is the expected one`, async() => {
+    it('should confirm the sixth row data is the expected one', async() => {
         let tag = await page
             .waitToGetProperty(selectors.itemTags.sixthTag, 'value');
 
diff --git a/modules/item/front/tags/index.html b/modules/item/front/tags/index.html
index 3775526be8..c040b99849 100644
--- a/modules/item/front/tags/index.html
+++ b/modules/item/front/tags/index.html
@@ -32,14 +32,14 @@
                 rule>
             </vn-autocomplete>
             <vn-textfield vn-three
-                ng-show="tag.selection.isFree || tag.selection.isFree == undefined"
+                ng-if="tag.selection.isFree || tag.selection.isFree == undefined"
                 vn-id="text"
                 label="Value"
                 ng-model="itemTag.value"
                 rule>
             </vn-textfield>
             <vn-autocomplete vn-three
-                ng-show="tag.selection.isFree === false"
+                ng-if="tag.selection.isFree === false"
                 url="{{'Tags/' + itemTag.tagFk + '/filterValue'}}"
                 search-function="{value: $search}"
                 label="Value"

From 3a3dae179cc1576e821fee48e979317856acf6cc Mon Sep 17 00:00:00 2001
From: jgallego <jgallego@verdnatura.es>
Date: Wed, 10 Feb 2021 07:58:11 +0100
Subject: [PATCH 07/10] done

---
 .eslintrc.yml                                 |  3 +-
 db/dump/fixtures.sql                          | 22 ++++++-------
 loopback/locale/es.json                       |  3 +-
 .../back/methods/client/createReceipt.js      | 13 ++++----
 .../client/specs/createReceipt.spec.js        | 23 ++++++++++++++
 modules/ticket/back/methods/ticket/new.js     |  2 +-
 .../back/methods/ticket/specs/new.spec.js     | 31 ++++++++++++++++---
 modules/ticket/front/create/card.html         |  2 +-
 modules/ticket/front/create/card.js           |  9 ++++--
 9 files changed, 80 insertions(+), 28 deletions(-)

diff --git a/.eslintrc.yml b/.eslintrc.yml
index 82a1af5010..708bf422db 100644
--- a/.eslintrc.yml
+++ b/.eslintrc.yml
@@ -34,4 +34,5 @@ rules:
     no-multiple-empty-lines: ["error", { "max": 1, "maxEOF": 1 }]
     space-in-parens: ["error", "never"]
     jasmine/no-focused-tests: 0
-    jasmine/prefer-toHaveBeenCalledWith: 0
\ No newline at end of file
+    jasmine/prefer-toHaveBeenCalledWith: 0
+    arrow-spacing: { "before": true, "after": true }
\ No newline at end of file
diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql
index 8742c161f1..3200cf4abd 100644
--- a/db/dump/fixtures.sql
+++ b/db/dump/fixtures.sql
@@ -150,20 +150,20 @@ INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `isPrinted`, `priority`, `park
 
 INSERT INTO `vn`.`accountingType`(`id`, `description`, `receiptDescription`,`code`)
     VALUES 
-        (1,     'CC y Polizas de crédito',  NULL,              NULL),
-        (2,     'Cash',                     NULL,              'cash'),
-        (3,     'Credit card',              NULL,              'creditCard'),
-        (4,     'Finalcial lines',          NULL,              NULL),
-        (5,     'Other products',           NULL,              NULL),
-        (6,     'Loans',                    NULL,              NULL),
-        (7,     'Leasing',                  NULL,              NULL),
-        (8,     'Compensations',           'Compensations',    'Compensations');
+        (1,     'CC y Polizas de crédito',  NULL,           NULL),
+        (2,     'Cash',                     'Cash',         'cash'),
+        (3,     'Credit card',              'Credit Card',  'creditCard'),
+        (4,     'Finalcial lines',          NULL,           NULL),
+        (5,     'Other products',           NULL,           NULL),
+        (6,     'Loans',                    NULL,           NULL),
+        (7,     'Leasing',                  NULL,           NULL),
+        (8,     'Compensations',           'Compensations', 'compensation');
         
 INSERT INTO `vn`.`bank`(`id`, `bank`, `account`, `cash`, `entityFk`, `isActive`, `currencyFk`)
     VALUES 
-        (1, 'Pay on receipt',   '0000000000', 3, 0, 1, 1),
-        (2, 'Cash',             '1111111111', 2, 0, 1, 1),
-        (3, 'Compensation',     '0000000000', 8, 0, 1, 1);
+        (1, 'Pay on receipt',   '5720000001', 3, 0, 1, 1),
+        (2, 'Cash',             '5700000001', 2, 0, 1, 1),
+        (3, 'Compensation',     '4000000000', 8, 0, 1, 1);
 
 INSERT INTO `vn`.`deliveryMethod`(`id`, `code`, `description`)
     VALUES
diff --git a/loopback/locale/es.json b/loopback/locale/es.json
index 16bd1d3610..bbd092b3ef 100644
--- a/loopback/locale/es.json
+++ b/loopback/locale/es.json
@@ -171,5 +171,6 @@
 	"New ticket request has been created with price": "Se ha creado una nueva petición de compra *'{{description}}'* para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*",
 	"New ticket request has been created": "Se ha creado una nueva petición de compra *'{{description}}'* para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
 	"That item doesn't exists": "Ese artículo no existe",
-	"There's a new urgent ticket": "Hay un nuevo ticket urgente: [{{title}}](https://cau.verdnatura.es/WorkOrder.do?woMode=viewWO&woID={{issueId}})"
+	"There's a new urgent ticket": "Hay un nuevo ticket urgente: [{{title}}](https://cau.verdnatura.es/WorkOrder.do?woMode=viewWO&woID={{issueId}})",
+	"Compensation account is empty": "La cuenta para compensar esta vacia"
 }
\ No newline at end of file
diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js
index 75ad02373c..976ff7cf27 100644
--- a/modules/client/back/methods/client/createReceipt.js
+++ b/modules/client/back/methods/client/createReceipt.js
@@ -62,7 +62,10 @@ module.exports = function(Self) {
             const bank = await models.Bank.findById(args.bankFk);
             const accountingType = await models.AccountingType.findById(bank.accountingTypeFk);
 
-            if (args.compensationAccount) {
+            if (accountingType.code == 'compensation') {
+                if (!args.compensationAccount)
+                    throw new UserError('Compensation account is empty');
+
                 const supplierCompensation = await models.Supplier.findOne({
                     where: {
                         account: args.compensationAccount
@@ -92,12 +95,11 @@ module.exports = function(Self) {
                     ],
                     options);
             } else {
-                const description = `${clientOriginal.id} : ${clientOriginal.nickname} - ${accountingType.receiptDescription}`;
+                const description = `${clientOriginal.id} : ${clientOriginal.socialName} - ${accountingType.receiptDescription}`;
                 const [xdiarioNew] = await Self.rawSql(
-                    `SELECT xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`,
+                    `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`,
                     [
                         null,
-                        Date(),
                         bank.account,
                         clientOriginal.accountingAccount,
                         description,
@@ -114,10 +116,9 @@ module.exports = function(Self) {
                     options);
 
                 await Self.rawSql(
-                    `SELECT xdiario_new(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
+                    `SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
                     [
                         xdiarioNew.ledger,
-                        Date(),
                         clientOriginal.accountingAccount,
                         bank.account,
                         description,
diff --git a/modules/client/back/methods/client/specs/createReceipt.spec.js b/modules/client/back/methods/client/specs/createReceipt.spec.js
index 59bf8f52a2..3bd560cdd7 100644
--- a/modules/client/back/methods/client/specs/createReceipt.spec.js
+++ b/modules/client/back/methods/client/specs/createReceipt.spec.js
@@ -38,6 +38,29 @@ describe('Client createReceipt', () => {
         await till.destroy();
     });
 
+    it('should throw Compensation account is empty', async() => {
+        const bankFk = 3;
+        let ctx = {
+            args: {
+                clientFk: clientFk,
+                payed: payed,
+                companyFk: companyFk,
+                bankFk: bankFk,
+                amountPaid: amountPaid,
+                description: description
+            }
+        };
+
+        try {
+            await app.models.Client.createReceipt(ctx);
+        } catch (e) {
+            error = e;
+        }
+
+        expect(error).toBeDefined();
+        expect(error.message).toEqual('Compensation account is empty');
+    });
+
     it('should throw Invalid account if compensationAccount does not belongs to a client nor a supplier', async() => {
         let error;
         const bankFk = 3;
diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js
index 8bafe5403e..cec7857bd1 100644
--- a/modules/ticket/back/methods/ticket/new.js
+++ b/modules/ticket/back/methods/ticket/new.js
@@ -101,7 +101,7 @@ module.exports = Self => {
             if (!shipped && landed) {
                 const shippedResult = await models.Agency.getShipped(landed,
                     address.id, agencyModeId, warehouseId);
-                shipped = shippedResult && shippedResult.shipped;
+                shipped = (shippedResult && shippedResult.shipped) || landed;
             }
 
             if (shipped && !landed) {
diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js
index f240ce3729..60f3c61822 100644
--- a/modules/ticket/back/methods/ticket/specs/new.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/new.spec.js
@@ -1,7 +1,7 @@
 const app = require('vn-loopback/server/server');
 let UserError = require('vn-loopback/util/user-error');
 
-describe('ticket new()', () => {
+fdescribe('ticket new()', () => {
     let ticket;
     let today = new Date();
     let ctx = {req: {accessToken: {userId: 1}}};
@@ -28,7 +28,7 @@ describe('ticket new()', () => {
             params.shipped,
             params.landed,
             params.warehouseId,
-            params.companyFk,
+            params.companyId,
             params.addressId
         ).catch(e => {
             error = e;
@@ -53,7 +53,7 @@ describe('ticket new()', () => {
             params.shipped,
             params.landed,
             params.warehouseId,
-            params.companyFk,
+            params.companyId,
             params.addressId
         ).catch(response => {
             expect(response.message).toEqual(`This address doesn't exist`);
@@ -79,7 +79,7 @@ describe('ticket new()', () => {
             params.shipped,
             params.landed,
             params.warehouseId,
-            params.companyFk,
+            params.companyId,
             params.addressId,
             params.agencyModeId);
 
@@ -87,4 +87,27 @@ describe('ticket new()', () => {
 
         expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures);
     });
+
+    it('should return the set a shipped when the agency is not especified', async() => {
+        let params = {
+            clientId: 104,
+            landed: today,
+            shipped: null,
+            warehouseId: 2,
+            companyId: 442,
+            addressId: 4,
+            agencyModeId: null
+        };
+
+        ticket = await app.models.Ticket.new(ctx,
+            params.clientId,
+            params.shipped,
+            params.landed,
+            params.warehouseId,
+            params.companyId,
+            params.addressId,
+            params.agencyModeId);
+
+        expect(ticket.shipped).toEqual(jasmine.any(Date));
+    });
 });
diff --git a/modules/ticket/front/create/card.html b/modules/ticket/front/create/card.html
index 36e62d8e65..65c45d3dce 100644
--- a/modules/ticket/front/create/card.html
+++ b/modules/ticket/front/create/card.html
@@ -39,7 +39,7 @@
 </vn-autocomplete>
 <vn-autocomplete
     disabled="!$ctrl.clientId || !$ctrl.landed || !$ctrl.warehouseId"
-    data="$ctrl._availableAgencies"
+    data="$ctrl.agencies"
     label="Agency"
     show-field="agencyMode"
     value-field="agencyModeFk"
diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js
index 213a0b0826..188d12d4d4 100644
--- a/modules/ticket/front/create/card.js
+++ b/modules/ticket/front/create/card.js
@@ -100,9 +100,12 @@ class Controller extends Component {
             ticket.agencyModeFk = null;
 
             this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}).then(res => {
-                this._availableAgencies = res.data;
-
-                this.agencyModeId = this.defaultAddress.agencyModeFk;
+                this.agencies = res.data;
+                const defaultAgency = this.agencies.find(agency=> {
+                    return agency.agencyModeFk == this.defaultAddress.agencyModeFk;
+                });
+                if (defaultAgency)
+                    this.agencyModeId = defaultAgency.agencyModeFk;
             });
         }
     }

From f87ea1b0517e3ef112943ca615a198d31ee5dcda Mon Sep 17 00:00:00 2001
From: jgallego <jgallego@verdnatura.es>
Date: Wed, 10 Feb 2021 08:13:45 +0100
Subject: [PATCH 08/10] arrow-spacing

---
 .eslintrc.yml                                        | 2 +-
 loopback/locale/es.json                              | 2 +-
 modules/order/front/create/card.js                   | 2 +-
 modules/ticket/back/methods/ticket/specs/new.spec.js | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/.eslintrc.yml b/.eslintrc.yml
index 708bf422db..d8b869d919 100644
--- a/.eslintrc.yml
+++ b/.eslintrc.yml
@@ -35,4 +35,4 @@ rules:
     space-in-parens: ["error", "never"]
     jasmine/no-focused-tests: 0
     jasmine/prefer-toHaveBeenCalledWith: 0
-    arrow-spacing: { "before": true, "after": true }
\ No newline at end of file
+    arrow-spacing: ["error", { "before": true, "after": true }]
\ No newline at end of file
diff --git a/loopback/locale/es.json b/loopback/locale/es.json
index bbd092b3ef..1b5fbd917c 100644
--- a/loopback/locale/es.json
+++ b/loopback/locale/es.json
@@ -172,5 +172,5 @@
 	"New ticket request has been created": "Se ha creado una nueva petición de compra *'{{description}}'* para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
 	"That item doesn't exists": "Ese artículo no existe",
 	"There's a new urgent ticket": "Hay un nuevo ticket urgente: [{{title}}](https://cau.verdnatura.es/WorkOrder.do?woMode=viewWO&woID={{issueId}})",
-	"Compensation account is empty": "La cuenta para compensar esta vacia"
+	"Compensation account is empty": "La cuenta para compensar está vacia"
 }
\ No newline at end of file
diff --git a/modules/order/front/create/card.js b/modules/order/front/create/card.js
index 315cc82557..de04484bda 100644
--- a/modules/order/front/create/card.js
+++ b/modules/order/front/create/card.js
@@ -37,7 +37,7 @@ class Controller extends Component {
             };
             filter = encodeURIComponent(JSON.stringify(filter));
             let query = `Clients?filter=${filter}`;
-            this.$http.get(query).then(res => {
+            this.$http.get(query).then(res=> {
                 if (res.data) {
                     let client = res.data[0];
                     let defaultAddress = client.defaultAddress;
diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js
index 60f3c61822..671b9bffde 100644
--- a/modules/ticket/back/methods/ticket/specs/new.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/new.spec.js
@@ -1,7 +1,7 @@
 const app = require('vn-loopback/server/server');
 let UserError = require('vn-loopback/util/user-error');
 
-fdescribe('ticket new()', () => {
+describe('ticket new()', () => {
     let ticket;
     let today = new Date();
     let ctx = {req: {accessToken: {userId: 1}}};

From 745d25f0c75bf728fcf4fa53552eee4fbf750d11 Mon Sep 17 00:00:00 2001
From: Jorge Padawan <jorgebl@verdnatura.es>
Date: Thu, 11 Feb 2021 11:14:52 +0100
Subject: [PATCH 09/10] Showed filter on browser search bar

---
 modules/item/front/routes.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json
index 564eab4843..4b4be3c3d2 100644
--- a/modules/item/front/routes.json
+++ b/modules/item/front/routes.json
@@ -162,7 +162,7 @@
             "acl": ["buyer"]
         },
         {
-            "url" : "/fixed-price",
+            "url" : "/fixed-price?q",
             "state": "item.fixedPrice",
             "component": "vn-fixed-price",
             "description": "Fixed prices",

From 3374356d5831888bd6924f66ae5fceb6ddd5261d Mon Sep 17 00:00:00 2001
From: carlosjr <carlosjr@verdnatura.es>
Date: Thu, 11 Feb 2021 11:53:30 +0100
Subject: [PATCH 10/10] both created tickets are now discarded after tests

---
 .../ticket/back/methods/ticket/specs/new.spec.js    | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js
index 671b9bffde..7ffcab68e5 100644
--- a/modules/ticket/back/methods/ticket/specs/new.spec.js
+++ b/modules/ticket/back/methods/ticket/specs/new.spec.js
@@ -2,12 +2,13 @@ const app = require('vn-loopback/server/server');
 let UserError = require('vn-loopback/util/user-error');
 
 describe('ticket new()', () => {
-    let ticket;
+    let ticketIdsToDelete = [];
     let today = new Date();
     let ctx = {req: {accessToken: {userId: 1}}};
 
     afterAll(async done => {
-        await app.models.Ticket.destroyById(ticket.id);
+        for (id of ticketIdsToDelete)
+            await app.models.Ticket.destroyById(id);
 
         done();
     });
@@ -74,7 +75,7 @@ describe('ticket new()', () => {
             agencyModeId: 1
         };
 
-        ticket = await app.models.Ticket.new(ctx,
+        const ticket = await app.models.Ticket.new(ctx,
             params.clientId,
             params.shipped,
             params.landed,
@@ -85,6 +86,8 @@ describe('ticket new()', () => {
 
         let newestTicketIdInFixtures = 21;
 
+        ticketIdsToDelete.push(ticket.id);
+
         expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures);
     });
 
@@ -99,7 +102,7 @@ describe('ticket new()', () => {
             agencyModeId: null
         };
 
-        ticket = await app.models.Ticket.new(ctx,
+        const ticket = await app.models.Ticket.new(ctx,
             params.clientId,
             params.shipped,
             params.landed,
@@ -108,6 +111,8 @@ describe('ticket new()', () => {
             params.addressId,
             params.agencyModeId);
 
+        ticketIdsToDelete.push(ticket.id);
+
         expect(ticket.shipped).toEqual(jasmine.any(Date));
     });
 });