View Javadoc
1   package com.srv4pos.server.api.registration;
2   
3   import com.srv4pos.server.api.activation.GeolocationInfo;
4   import com.srv4pos.server.api.activation.RegistrationDetailedOverviewInfo;
5   import com.srv4pos.server.api.activation.RegistrationInfo;
6   import com.srv4pos.server.api.day.RegistrationVersion;
7   import com.srv4pos.server.api.exceptions.ReferenceNotFoundJsonException;
8   import com.srv4pos.server.api.infrastructure.EmptyConnectionWriter;
9   import com.srv4pos.server.api.infrastructure.HttpMethod;
10  import com.srv4pos.server.api.infrastructure.StringConnectionWriter;
11  import com.srv4pos.server.api.infrastructure.credentials.Credentials;
12  import com.srv4pos.server.api.infrastructure.exceptions.enums.ForbiddenErrorType;
13  import com.srv4pos.server.api.infrastructure.exceptions.enums.InconsistentDataErrorType;
14  import com.srv4pos.server.api.infrastructure.exceptions.enums.UnprocessableEntityErrorType;
15  import com.srv4pos.server.api.infrastructure.http.HttpHelper;
16  import com.srv4pos.server.api.infrastructure.http.Transport;
17  import com.srv4pos.server.api.infrastructure.request.StringResponse;
18  import com.srv4pos.server.api.posplus.KdInfo;
19  import com.srv4pos.server.api.posplus.KdReplyInfo;
20  import com.srv4pos.server.api.posplus.SVKdInfo;
21  
22  import java.net.URL;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  
27  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestString;
28  import static com.srv4pos.server.api.infrastructure.request.RequestHelper.requestVoid;
29  import static java.lang.String.format;
30  
31  
32  /**
33   * Service to reach registrations.
34   *
35   * @author Ruslan Kashapov.
36   */
37  public class RegistrationService {
38  
39      private URL url;
40      private Credentials credentials;
41      private Transport transport;
42  
43      /**
44       * Constructs the service.
45       *
46       * @param url         of the server
47       * @param credentials to work with the server
48       * @param transport   to know the method to reach the server
49       */
50      public RegistrationService(URL url, Credentials credentials, Transport transport) {
51          this.url = url;
52          this.credentials = credentials;
53          this.transport = transport;
54      }
55  
56      /**
57       * Get balance of registration.
58       *
59       * @param version          version of seller, may be null (if latest data needed)
60       * @param cashRegisterName described in swedish regulations as "cash register designation"
61       * @return balance of registration
62       * @throws ReferenceNotFoundJsonException                                     if cashRegisterName is not found
63       * @throws com.srv4pos.server.api.exceptions.UnprocessableEntityJsonException see:
64       *                                                                            {@link UnprocessableEntityErrorType#DAY_IS_NOT_CLOSED},
65       *                                                                            {@link UnprocessableEntityErrorType#REPORT_IS_NOT_PRINTED}
66       */
67      public BalanceInfo getBalance(Integer version, String cashRegisterName) {
68          StringResponse response = requestString(
69                  format("%s/registrations/%s/balance", credentials.getSellerId(), cashRegisterName),
70                  HttpMethod.GET,
71                  url,
72                  credentials.toAuthentication(),
73                  HttpHelper.integerToETag(version),
74                  null,
75                  EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
76                  HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
77                  transport);
78  
79          return response == null ? null : BalanceInfo.fromJsonToBalanceInfo(response.getContent());
80      }
81  
82      /**
83       * Set balance of registration.
84       *
85       * @param version           expected latest version of seller
86       * @param cashRegisterName  described in swedish regulations as "cash register designation"
87       * @param changeBalanceInfo registration balance and action
88       * @throws ReferenceNotFoundJsonException                                     if cashRegisterName is not found
89       * @throws com.srv4pos.server.api.exceptions.UnprocessableEntityJsonException see:
90       *                                                                            {@link UnprocessableEntityErrorType#DAY_IS_CLOSED},
91       *                                                                            {@link UnprocessableEntityErrorType#DAY_IS_NOT_CLOSED},
92       *                                                                            {@link UnprocessableEntityErrorType#REPORT_IS_NOT_PRINTED}
93       */
94      public void setBalance(int version, String cashRegisterName, ChangeBalanceInfo changeBalanceInfo) {
95          requestVoid(
96                  format("%s/registrations/%s/balance", credentials.getSellerId(), cashRegisterName),
97                  HttpMethod.POST,
98                  url,
99                  credentials.toAuthentication(),
100                 HttpHelper.integerToETag(version),
101                 null,
102                 new StringConnectionWriter(changeBalanceInfo.toJson()),
103                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
104                 transport);
105     }
106 
107     /**
108      * Returns list of all registrations.
109      *
110      * @param version version of seller, may be null (if latest data needed)
111      * @return list of all registrations
112      */
113     public List<RegistrationInfo> list(Integer version) {
114         return list(version, null, null, null, null, false);
115     }
116 
117     /**
118      * Returns list of registrations.
119      *
120      * @param version     version of seller, may be null (if latest data needed)
121      * @param firstResult when pagination starts or null
122      * @param maxResults  amount of items per page or null
123      * @param orderBy     field to order by, possible values are "IDENTIFIER", "NAME"
124      * @param orderDesc   field to direction of ordering
125      * @param activeOnly  True if need only active registrations, otherwise all registrations
126      * @return list of registrations
127      */
128     public List<RegistrationInfo> list(Integer version,
129                                        Integer firstResult,
130                                        Integer maxResults,
131                                        RegistrationInfo.Fields orderBy,
132                                        Boolean orderDesc,
133                                        Boolean activeOnly) {
134         Map<String, String> params = new HashMap<String, String>();
135 
136         if (activeOnly != null) {
137             params.put("activeOnly", String.valueOf(activeOnly));
138         }
139         if (firstResult != null) {
140             params.put("firstResult", Integer.toString(firstResult));
141         }
142         if (maxResults != null) {
143             params.put("maxResults", Integer.toString(maxResults));
144         }
145         if (orderBy != null) {
146             params.put("orderBy", orderBy.name());
147         }
148         if (orderDesc != null) {
149             params.put("orderDesc", orderDesc.toString());
150         }
151 
152         StringResponse response = requestString(
153                 format("%s/registrations", credentials.getSellerId()),
154                 HttpMethod.GET,
155                 url,
156                 credentials.toAuthentication(),
157                 null,
158                 params,
159                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
160                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
161                 transport);
162 
163         return response == null ? null : (List<RegistrationInfo>) RegistrationInfo.fromJsonArrayToRegistrationInfoes(response.getContent());
164     }
165 
166     /**
167      * Returns stats by registrations.
168      *
169      * @param period filters by date period
170      * @return
171      */
172     public List<RegistrationStatsInfo> stats(String period) {
173         Map<String, String> params = new HashMap<String, String>();
174         if (period != null) {
175             params.put("period", period);
176         }
177         StringResponse response = requestString(
178                 format("%s/registrations/stats", credentials.getSellerId()),
179                 HttpMethod.GET,
180                 url,
181                 credentials.toAuthentication(),
182                 null,
183                 params,
184                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
185                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
186                 transport
187         );
188         return response == null ? null : (List<RegistrationStatsInfo>) RegistrationStatsInfo.fromJsonArrayToRegistrationStatsInfoes(response.getContent());
189     }
190 
191     /**
192      * Returns an registration info.
193      *
194      * @param seller           seller's identifier
195      * @param cashRegisterName cash register name
196      * @return the entity
197      * @throws com.srv4pos.server.api.exceptions.NotFoundJsonException  if registration wasn't found
198      * @throws com.srv4pos.server.api.exceptions.ForbiddenJsonException see:
199      *                                                                  {@link ForbiddenErrorType#INSUFFICIENT_ACCESS_RIGHTS}
200      */
201     public RegistrationDetailedOverviewInfo getOverviewInfo(String seller, String cashRegisterName) {
202         return RegistrationDetailedOverviewInfo.fromJsonToRegistrationDetailedOverviewInfo(requestString(
203                 format("%s/registrations/%s", seller, cashRegisterName),
204                 HttpMethod.GET,
205                 url,
206                 credentials.toAuthentication(),
207                 null,
208                 null,
209                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
210                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
211                 transport).getContent());
212     }
213 
214     /**
215      * Returns latest version of registration.
216      *
217      * @param cashRegisterName described in swedish regulations as "cash register designation"
218      * @return version number
219      * @see RegistrationServiceSample
220      */
221     public RegistrationVersion getRegistrationVersion(String cashRegisterName) {
222         return RegistrationVersion.fromJsonToRegistrationVersion(
223                 requestString(
224                         format("%s/registrations/%s/version", credentials.getSellerId(), cashRegisterName),
225                         HttpMethod.GET,
226                         url,
227                         credentials.toAuthentication(),
228                         null,
229                         null,
230                         EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
231                         HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
232                         transport
233                 ).getContent()
234         );
235     }
236 
237     /**
238      * Returns list of item changes between two versions.
239      *
240      * @param versionFrom version from included
241      * @param versionTo   version to included
242      * @return list of items to be added, edited or deleted ({@link com.srv4pos.server.api.activation.RegistrationInfo#deleted} = true)
243      */
244     public List<RegistrationInfo> listDiff(int versionFrom, int versionTo) {
245         StringResponse response = requestString(
246                 String.format("%s/registrations-diff/%s/%s", credentials.getSellerId(), versionFrom, versionTo),
247                 HttpMethod.GET,
248                 url,
249                 credentials.toAuthentication(),
250                 null,
251                 null,
252                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
253                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
254                 transport
255         );
256         return (List<RegistrationInfo>) RegistrationInfo.fromJsonArrayToRegistrationInfoes(response.getContent());
257     }
258 
259     /**
260      * Delete registration from the server.
261      *
262      * @param version    current version of the entity
263      * @param identifier identifies entity
264      * @throws com.srv4pos.server.api.exceptions.VersionConflictJsonException if version mismatch
265      */
266     public void delete(int version, String identifier) {
267         requestVoid(
268                 format("%s/registrations/%s", credentials.getSellerId(), identifier),
269                 HttpMethod.DELETE,
270                 url,
271                 credentials.toAuthentication(),
272                 HttpHelper.integerToETag(version),
273                 null,
274                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
275                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
276                 transport
277         );
278     }
279 
280     public List<GeolocationInfo> listGeolocations(String sellerId) {
281         StringResponse response = requestString(
282                 format("%s/registrations-locations", sellerId),
283                 HttpMethod.GET,
284                 url,
285                 credentials.toAuthentication(),
286                 null,
287                 null,
288                 EmptyConnectionWriter.EMPTY_CONNECTION_WRITER,
289                 HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
290                 transport
291         );
292         return (List<GeolocationInfo>) GeolocationInfo.fromJsonArrayToGeolocationInfoes(response.getContent());
293     }
294     /**
295      * Sends data to control unit.
296      *
297      * @param kdInfo data to send
298      * @param sellerId seller identifier
299      * @param cashRegisterName cash register name
300      *
301      * @return result of sending
302      * @throws com.srv4pos.server.api.exceptions.ControlUnitReceiptJsonException       when Control Unit decides something is
303      *                                                                                 wrong according to it's internal business logic
304      * @throws com.srv4pos.server.api.exceptions.InconsistentDataJsonException         see:
305      *                                                                                 {@link InconsistentDataErrorType#WORKING_WITH_CU_IS_NOT_SUPPORTED_BY_APP}
306      * @throws com.srv4pos.server.api.exceptions.ControlUnitUnavailableJsonException   when server is unable to reach the control
307      *                                                                                 unit device (for instance it's ejected from the server)
308      * @throws com.srv4pos.server.api.exceptions.ControlUnitCommunicationJsonException when error has happened during transmission data to the control unit
309      *                                                                                 (for instance, it was ejected from the server during sending the data)
310      *                                                                                 workable yet
311      */
312     public KdReplyInfo kd(KdInfo kdInfo, String sellerId, String cashRegisterName) {
313         return KdReplyInfo.fromJsonToKdReplyInfo(
314                 requestString(
315                         format("%s/registration/%s/kd", sellerId, cashRegisterName),
316                         HttpMethod.POST,
317                         url,
318                         credentials.toAuthentication(),
319                         null,
320                         null,
321                         new StringConnectionWriter(kdInfo.toJson()),
322                         HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
323                         transport).getContent());
324     }
325 
326     /**
327      * Sends data to control unit.
328      *
329      * @param kdInfo data to send
330      * @param sellerId seller identifier
331      * @param cashRegisterName cash register name
332      *
333      * @return result of sending
334      * @throws com.srv4pos.server.api.exceptions.ControlUnitReceiptJsonException       when Control Unit decides something is
335      *                                                                                 wrong according to it's internal business logic
336      * @throws com.srv4pos.server.api.exceptions.InconsistentDataJsonException         see:
337      *                                                                                 {@link InconsistentDataErrorType#WORKING_WITH_CU_IS_NOT_SUPPORTED_BY_APP}
338      * @throws com.srv4pos.server.api.exceptions.ControlUnitUnavailableJsonException   when server is unable to reach the control
339      *                                                                                 unit device (for instance it's ejected from the server)
340      * @throws com.srv4pos.server.api.exceptions.ControlUnitCommunicationJsonException when error has happened during transmission data to the control unit
341      *                                                                                 (for instance, it was ejected from the server during sending the data)
342      *                                                                                 workable yet
343      */
344     public KdReplyInfo kdForSV(SVKdInfo kdInfo, String sellerId, String cashRegisterName) {
345         return KdReplyInfo.fromJsonToKdReplyInfo(
346                 requestString(
347                         format("%s/registration/%s/kd", sellerId, cashRegisterName),
348                         HttpMethod.POST,
349                         url,
350                         credentials.toAuthentication(),
351                         null,
352                         null,
353                         new StringConnectionWriter(kdInfo.toJson()),
354                         HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
355                         transport).getContent());
356     }
357 
358     /**
359      * The same as {@link #kd(KdInfo, String, String)}, but also has param logId for load testing.
360      * For logging details, see com.srv4pos.server.core.web.infrastructure.MethodProfiler
361      * and com.srv4pos.server.core.web.infrastructure.ServletTimeMeasurementFilter.
362      *
363      * @param kdInfo data to send
364      * @param logId  the identifier of log
365      * @return result of sending
366      */
367     public KdReplyInfo kd(KdInfo kdInfo, String sellerId, String cashRegisterName, String logId) {
368         return KdReplyInfo.fromJsonToKdReplyInfo(
369                 requestString(
370                         format("%s/registration/%s/kd", sellerId, cashRegisterName),
371                         HttpMethod.POST,
372                         url,
373                         credentials.toAuthentication(),
374                         null,
375                         null,
376                         new StringConnectionWriter(kdInfo.toJson()),
377                         HttpHelper.CONTENT_TYPE_APPLICATION_JSON,
378                         transport).getContent());
379     }
380 }