Skip to content

Commit eb4d297

Browse files
authored
Merge pull request #8 from cap-js/feat/mock_variant
Enable Local Variant
2 parents d9f4421 + 3a29482 commit eb4d297

File tree

5 files changed

+1026
-10062
lines changed

5 files changed

+1026
-10062
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,14 @@ If you are running the application in a production way locally(E.g. adding VCAP_
143143
}
144144
```
145145

146+
If you are running the application in offline mode which is without remote connection to the online environment, you can add the environmental variable `PRINT_CONSOLE_MODE=true cds watch` in the `package.json` as shown below.
147+
148+
```json
149+
"scripts": {
150+
"watch-offline": "PRINT_CONSOLE_MODE=true cds watch"
151+
}
152+
```
153+
146154
## Support, Feedback, Contributing
147155

148156
This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-js/print/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md).

lib/authUtil.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Include SAP Cloud SDK reuse functions for JWT decoding and other SAP services
22
const { decodeJwt } = require('@sap-cloud-sdk/connectivity');
33
const cds = require('@sap/cds');
4-
const logger = cds.log("printservice");
4+
const logger = cds.log("print");
55
const xssec = require('@sap/xssec');
66

77

lib/printUtil.js

Lines changed: 113 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,58 @@
11
const { getJwt, readVcapServices } = require("./authUtil");
22
const { getPrintConfigFromActionOrEntity } = require('./annotation-helper');
33
const axios = require('axios');
4-
const logger = cds.log("printservice");
4+
const logger = cds.log("print");
5+
const CONSOLE_MODE = process.env.PRINT_CONSOLE_MODE === 'true';
56

67
/**
78
* Populates the queue value help with available printers.
89
* @param {Object} _ - Unused parameter.
910
* @param {Object} req - The request object.
1011
*/
1112
const populateQueueValueHelp = async function (_, req) {
12-
const vcap = await readVcapServices();
13-
if (!vcap || vcap?.status === 500) {
14-
// For Production, return the error if print service is not found
15-
logger.error('Print service not found');
16-
return req.error(500, 'Print service not found');
17-
}
18-
const jwt = await getJwt(req, vcap);
19-
if (jwt?.code === 500) {
20-
logger.error('Failed to retrieve token');
21-
return req.error(500, 'Failed to retrieve token');
22-
}
23-
24-
const api = axios.create({
25-
baseURL: vcap.service_url,
26-
headers: {
27-
'Authorization': `Bearer ${jwt}`,
28-
"Accept": "*/*",
29-
"Content-Type": "application/json"
13+
if (!CONSOLE_MODE) {
14+
const vcap = await readVcapServices();
15+
if (!vcap || vcap?.status === 500) {
16+
// For Production, return the error if print service is not found
17+
logger.error('Print service not found');
18+
return req.error(500, 'Print service not found');
3019
}
31-
});
32-
const resp = await api.get(`/qm/api/v1/rest/queues`);
33-
resp.data.forEach((item, index) => {
34-
req.results[index] = { ID: item.qname };
35-
});
36-
req.results.$count = resp.data.length;
20+
const jwt = await getJwt(req, vcap);
21+
if (jwt?.code === 500) {
22+
logger.error('Failed to retrieve token');
23+
return req.error(500, 'Failed to retrieve token');
24+
}
25+
26+
const api = axios.create({
27+
baseURL: vcap.service_url,
28+
headers: {
29+
'Authorization': `Bearer ${jwt}`,
30+
"Accept": "*/*",
31+
"Content-Type": "application/json"
32+
}
33+
});
34+
const resp = await api.get(`/qm/api/v1/rest/queues`);
35+
36+
resp.data.forEach((item, index) => {
37+
req.results[index] = { ID: item.qname };
38+
});
39+
req.results.$count = resp.data.length;
40+
} else { // Offline / Console Mode - Mocked printer queues
41+
const offlineQueues = [
42+
{ ID: 'DEFAULT_PRINTER' },
43+
{ ID: 'HP_LASERJET_PRO' },
44+
{ ID: 'CANON_IMAGECLASS' },
45+
{ ID: 'XEROX_WORKCENTRE' },
46+
{ ID: 'OFFICE_PRINTER_01' },
47+
{ ID: 'OFFICE_PRINTER_02' }
48+
];
49+
50+
offlineQueues.forEach((item, index) => {
51+
req.results[index] = { ID: item.ID };
52+
});
53+
req.results.$count = offlineQueues.length;
54+
return;
55+
}
3756
}
3857

3958
/**
@@ -43,77 +62,82 @@ const populateQueueValueHelp = async function (_, req) {
4362
*/
4463
const print = async function (_, req) {
4564
let { qname, numberOfCopies, docsToPrint } = await getPrintConfigFromActionOrEntity(req);
46-
const vcap = await readVcapServices(req);
47-
if (!vcap || vcap?.status === 500) {
48-
// For Production, return the error if print service is not found
49-
logger.error('Print service not found');
50-
return req.error(500, 'Print service not found');
51-
}
52-
const jwt = await getJwt(req, vcap);
53-
if (jwt?.code === 500) {
54-
logger.error('Failed to retrieve token');
55-
return req.error(500, 'Failed to retrieve token');
56-
}
57-
58-
const api = axios.create({
59-
baseURL: vcap.service_url,
60-
headers: {
61-
'Authorization': `Bearer ${jwt}`,
62-
"DataServiceVersion": "2.0",
63-
"Accept": "*/*",
64-
"Content-Type": "application/json",
65-
'If-None-Match': '*',
66-
'scan': true
67-
}
68-
});
69-
70-
// Upload documents to be printed
71-
for (const doc of docsToPrint) {
72-
if (!doc.content) {
73-
logger.error('No content provided for printing');
74-
return req.error('No content provided for printing');
65+
if (!CONSOLE_MODE) {
66+
const vcap = await readVcapServices(req);
67+
if (!vcap || vcap?.status === 500) {
68+
// For Production, return the error if print service is not found
69+
logger.error('Print service not found');
70+
return req.error(500, 'Print service not found');
7571
}
76-
let documentResp;
77-
try {
78-
documentResp = await api.post('/dm/api/v1/rest/print-documents', doc.content);
79-
doc.objectKey = documentResp.data;
80-
} catch (e) {
81-
logger.error(`Error in uploading document ${doc.fileName}: `, e.response?.data?.error?.message);
82-
return req.error(e.response?.data?.error?.message);
72+
const jwt = await getJwt(req, vcap);
73+
if (jwt?.code === 500) {
74+
logger.error('Failed to retrieve token');
75+
return req.error(500, 'Failed to retrieve token');
8376
}
84-
}
8577

86-
let printTask = {
87-
numberOfCopies: numberOfCopies,
88-
username: cds.context?.user?.id,
89-
qname: qname,
90-
printContents: []
91-
}
92-
let itemId = "";
93-
// Create Print Content
94-
docsToPrint.forEach(async (doc) => {
95-
printTask.printContents.push({
96-
objectKey: doc.objectKey,
97-
documentName: doc.fileName
98-
})
78+
const api = axios.create({
79+
baseURL: vcap.service_url,
80+
headers: {
81+
'Authorization': `Bearer ${jwt}`,
82+
"DataServiceVersion": "2.0",
83+
"Accept": "*/*",
84+
"Content-Type": "application/json",
85+
'If-None-Match': '*',
86+
'scan': true
87+
}
88+
});
9989

100-
if (doc.isMainDocument) {
101-
itemId = doc.objectKey;
90+
// Upload documents to be printed
91+
for (const doc of docsToPrint) {
92+
if (!doc.content) {
93+
logger.error('No content provided for printing');
94+
return req.error('No content provided for printing');
95+
}
96+
let documentResp;
97+
try {
98+
documentResp = await api.post('/dm/api/v1/rest/print-documents', doc.content);
99+
doc.objectKey = documentResp.data;
100+
} catch (e) {
101+
logger.error(`Error in uploading document ${doc.fileName}: `, e.response?.data?.error?.message);
102+
return req.error(e.response?.data?.error?.message);
103+
}
102104
}
103-
});
104105

105-
// Print Task
106-
let printTaskResp;
107-
try {
108-
printTaskResp = await api.put(`/qm/api/v1/rest/print-tasks/${itemId}`, printTask);
109-
} catch (e) {
110-
logger.error('Error in sending to print queue: ', e.response?.data?.error?.message);
111-
return req.error('Print task failed');
106+
let printTask = {
107+
numberOfCopies: numberOfCopies,
108+
username: cds.context?.user?.id,
109+
qname: qname,
110+
printContents: []
111+
}
112+
let itemId = "";
113+
// Create Print Content
114+
docsToPrint.forEach(async (doc) => {
115+
printTask.printContents.push({
116+
objectKey: doc.objectKey,
117+
documentName: doc.fileName
118+
})
119+
120+
if (doc.isMainDocument) {
121+
itemId = doc.objectKey;
122+
}
123+
});
124+
125+
// Print Task
126+
let printTaskResp;
127+
try {
128+
printTaskResp = await api.put(`/qm/api/v1/rest/print-tasks/${itemId}`, printTask);
129+
} catch (e) {
130+
logger.error('Error in sending to print queue: ', e.response?.data?.error?.message);
131+
return req.error('Print task failed');
132+
}
133+
logger.info(`Document sent to print queue ${qname}`);
134+
return req.info(200, `Document sent to print queue ${qname} \n
135+
No. of copies requested: ${numberOfCopies}`);
136+
} else { // Offline / Console Mode
137+
docsToPrint.forEach((doc) => {
138+
logger.info(`Document ${doc.fileName} with object key ${doc.objectKey} and content length ${doc.content.length} has been sent to print queue ${qname}`);
139+
});
112140
}
113-
logger.info(`Document sent to print queue ${qname}`);
114-
return req.info(200, `Document sent to print queue ${qname} \n
115-
No. of copies requested: ${numberOfCopies}`);
116141
}
117142

118143
module.exports = { print, populateQueueValueHelp };
119-

0 commit comments

Comments
 (0)