11const {
22 getFieldsHoldingPrintConfig,
3- getAnnotatedParamsOfAction
3+ getAnnotatedParamsOfAction,
4+ getPrintParamsAttributeFromAction
45} = require ( './lib/annotation-helper' ) ;
56
67const cds = require ( '@sap/cds' ) ;
8+ const LOG = cds . log ( 'print' ) ;
9+
10+ const PRINT = "@print" ;
711
812cds . once ( "served" , async ( ) => {
913 // Iterate over all services
@@ -24,35 +28,43 @@ cds.once("served", async () => {
2428 } ) ;
2529 }
2630
27- // Track the fields holding print configurations
28- await getFieldsHoldingPrintConfig ( entity ) ;
31+ if ( ! entity . actions ) continue
2932
30- // Check if the entity has actions
31- if ( entity . actions ) {
32- let actionsArray ;
33+ for ( const action of entity . actions ) {
34+ if ( action [ PRINT ] ) {
3335
34- // Convert actions to an array if it's an object
35- if ( Array . isArray ( entity . actions ) ) {
36- actionsArray = entity . actions ;
37- } else if ( typeof entity . actions === 'object' ) {
38- actionsArray = Object . values ( entity . actions ) ;
39- }
36+ const printer = await cds . connect . to ( "print" ) ;
37+
38+ const { numberOfCopiesAttribute, queueIDAttribute, fileNameAttribute, contentAttribute } = getPrintParamsAttributeFromAction ( entity , action ) ;
39+
40+ srv . on ( action . name , entity , async ( req ) => {
41+
42+
43+ const numberOfCopies = req . data [ numberOfCopiesAttribute ] ;
44+ const queueID = req . data [ queueIDAttribute ] ;
4045
41- // Iterate over all bound actions
42- for ( let boundAction of actionsArray ) {
43- if ( boundAction [ '@print' ] ) {
44-
45- // Track the action parameters holding print configurations
46- getAnnotatedParamsOfAction ( boundAction ) ;
47-
48- const actionName = boundAction . name . split ( '.' ) . pop ( ) ;
49-
50- // Register for print related handling
51- const printer = await cds . connect . to ( "print" ) ;
52- srv . after ( actionName , async ( results , req ) => {
53- return printer . print ( req ) ;
54- } ) ;
55- }
46+ const object = await SELECT . one . from ( req . subject ) . columns ( [ fileNameAttribute , contentAttribute ] ) ;
47+
48+ try {
49+
50+ await printer . print ( {
51+ qname : queueID ,
52+ numberOfCopies : numberOfCopies ,
53+ docsToPrint : [ {
54+ fileName : object [ fileNameAttribute ] ,
55+ content : object [ contentAttribute ] . toString ( 'base64' ) ,
56+ isMainDocument : true
57+ } ]
58+ } )
59+
60+ }
61+ catch ( error ) {
62+ LOG . error ( error )
63+ req . reject ( 500 , `Printing failed: ${ error . message ?? "Unknown error" } ` ) ;
64+ }
65+
66+
67+ } ) ;
5668 }
5769 }
5870 }
0 commit comments