source: ether_megapoli/trunk/web/src/com/ether/ControllerBackoffice.java @ 474

Last change on this file since 474 was 474, checked in by vmipsl, 12 years ago

BO insertion données

File size: 23.9 KB
Line 
1package com.ether;
2
3import com.ether.annotation.ControllerMethod;
4import com.ether.annotation.ParamName;
5import com.ether.mco.Mco;
6import com.ether.mco.McoFilter;
7import com.ether.mco.McoState;
8import com.ether.mco.McoType;
9import com.ether.user.User;
10import com.ether.user.UserFilter;
11import com.ether.user.UserRole;
12import com.ether.user.UserState;
13import com.medias.database.objects.Jeu;
14import com.medias.mail.Mail;
15import com.medias.mail.MailFactory;
16import net.sf.json.JSONObject;
17import org.apache.commons.logging.Log;
18import org.apache.commons.logging.LogFactory;
19import org.jetbrains.annotations.NotNull;
20import org.jetbrains.annotations.Nullable;
21
22import javax.mail.MessagingException;
23import java.security.DigestException;
24import java.security.NoSuchAlgorithmException;
25import java.util.ArrayList;
26import java.util.Date;
27import java.util.HashMap;
28import java.util.List;
29import java.util.Map;
30
31/**
32 * @author vmipsl
33 * @date 13 nov 2011
34 */
35public class ControllerBackoffice
36        extends ControllerEther
37{
38    /** *********************************************************** **/
39    /** *********************** VIEWS ***************************** **/
40    /** *********************************************************** **/
41    /**
42     * Default view
43     *
44     * @return
45     * @throws ServiceException
46     */
47    @ControllerMethod(view = VIEW_BO_INDEX, backofficeMethod = true, defaultView = VIEW_BO_INDEX)
48    public Map<String, Object> home()
49            throws WebException
50    {
51        return new HashMap<String, Object>();
52    }
53
54    @ControllerMethod(view = VIEW_BO_USER, backofficeMethod = true, defaultView = VIEW_BO_INDEX, jsonResult = true)
55    public JSONObject viewUser()
56            throws WebException
57    {
58        final JSONObject jsonObject = sortUser( "lastName", null, "ALL", "ALL", true, true, 5, 1 );
59        jsonObject.put( "jSonUserStates", getJSONUserStates() );
60        jsonObject.put( "jSonUserRoles", getJSONUserRoles() );
61        return jsonObject;
62    }
63
64    @ControllerMethod(view = VIEW_BO_MCO, backofficeMethod = true, defaultView = VIEW_BO_INDEX, jsonResult = true)
65    public JSONObject viewMco()
66            throws WebException
67    {
68        final JSONObject jsonObject = sortRequest( "creationDate", null, "ALL", "ALL", 5, 1 );
69        jsonObject.put( "jSonRequestStates", getJSONMcoStates() );
70        jsonObject.put( "jSonRequestTypes", getJSONMcoTypes() );
71        return jsonObject;
72    }
73
74    @ControllerMethod(view = VIEW_BO_DATA_INSERTION, backofficeMethod = true, defaultView = VIEW_BO_INDEX)
75    public JSONObject viewDataInsertion()
76            throws WebException
77    {
78        return sortDataSet( "jeuId", null, 5, 1 );
79    }
80
81    /** *********************************************************** **/
82    /** *********************** CALLS ***************************** **/
83    /** *********************************************************** **/
84    /**
85     * This method add a new user
86     *
87     * @param lastName
88     * @param firstName
89     * @param email
90     * @param pwd
91     * @param role
92     * @param state
93     * @param hasAccessToBO
94     * @return
95     * @throws WebException
96     * @throws ServiceException
97     */
98    @ControllerMethod(jsonResult = true)
99    public JSONObject addUser( @NotNull @ParamName(ParameterConstants.PARAMETER_NAME) final String lastName,
100                               @Nullable @ParamName(ParameterConstants.PARAMETER_FIRST_NAME) final String firstName,
101                               @NotNull @ParamName(ParameterConstants.PARAMETER_EMAIL) final String email,
102                               @NotNull @ParamName(ParameterConstants.PARAMETER_PWD) final String pwd,
103                               @Nullable @ParamName(ParameterConstants.PARAMETER_ROLE) final String role,
104                               @NotNull @ParamName(ParameterConstants.PARAMETER_STATE) final String state,
105                               @NotNull @ParamName(ParameterConstants.PARAMETER_HAS_ACCESS) final Boolean hasAccessToBO )
106            throws WebException
107    {
108        try
109        {
110            final User existingUser = getEtherService().getUserByEmail( email );
111            if( null == existingUser )
112            {
113                final Date creationDate = new Date();
114                final String encryptedPassword = EtherHelper.encryptPassword( pwd );
115                final User user = new User( lastName, firstName, email, encryptedPassword, role, state, hasAccessToBO, creationDate );
116
117                getEtherService().createUser( user );
118            }
119            else
120                throw new WebException( WebException.WebCode.USER_ALREADY_EXISTS, "This email already corresponds to an User", WebException.getExceptionThrowable() );
121
122        }
123        catch( DigestException e )
124        {
125            throw new WebException( WebException.WebCode.ERROR_ENCRYPT_PASSWORD, "This password cannot be encrypted" );
126        }
127        catch( NoSuchAlgorithmException e )
128        {
129            throw new WebException( WebException.WebCode.ERROR_ENCRYPT_PASSWORD, "This password cannot be encrypted" );
130        }
131        catch( ServiceException e )
132        {
133            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
134        }
135
136        return getAllAndWaitingUsers();
137    }
138
139    @ControllerMethod(jsonResult = true)
140    public JSONObject removeUser( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer userId )
141            throws WebException
142    {
143        try
144        {
145            getEtherService().removeUserById( userId );
146            return getAllAndWaitingUsers();
147        }
148        catch( ServiceException e )
149        {
150            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
151        }
152    }
153
154    @ControllerMethod(jsonResult = true)
155    public JSONObject modifyUser( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer userId,
156                                  @NotNull @ParamName(ParameterConstants.PARAMETER_NAME) final String lastName,
157                                  @Nullable @ParamName(ParameterConstants.PARAMETER_FIRST_NAME) final String firstName,
158                                  @NotNull @ParamName(ParameterConstants.PARAMETER_EMAIL) final String email,
159                                  @Nullable @ParamName(ParameterConstants.PARAMETER_PWD) final String pwd,
160                                  @Nullable @ParamName(ParameterConstants.PARAMETER_ROLE) final String role,
161                                  @NotNull @ParamName(ParameterConstants.PARAMETER_STATE) final String state,
162                                  @NotNull @ParamName(ParameterConstants.PARAMETER_HAS_ACCESS) final Boolean hasAccessToBO,
163                                  @NotNull @ParamName(ParameterConstants.PARAMETER_KEEP_SAME_PASSWORD) final Boolean keepSamePassword )
164            throws WebException
165    {
166        try
167        {
168            final User existingUser = getEtherService().getUserByEmail( email );
169            if( null == existingUser || userId.equals( existingUser.getId() ) )
170            {
171                final User user = getEtherService().getUserById( userId );
172                user.setLastName( lastName );
173                user.setFirstName( firstName );
174                user.setEmail( email );
175                if( !keepSamePassword && null != pwd )
176                {
177                    final String encryptedPassword = EtherHelper.encryptPassword( pwd );
178                    user.setPassword( encryptedPassword );
179                }
180                user.setRole( UserRole.valueOf( role ) );
181                user.setState( UserState.valueOf( state ) );
182                user.setAccessToBO( hasAccessToBO );
183
184                getEtherService().updateUser( user );
185            }
186            else
187                throw new WebException( WebException.WebCode.USER_ALREADY_EXISTS, "This email already corresponds to an User", WebException.getExceptionThrowable() );
188        }
189        catch( DigestException e )
190        {
191            throw new WebException( WebException.WebCode.ERROR_ENCRYPT_PASSWORD, "This password cannot be encrypted" );
192        }
193        catch( NoSuchAlgorithmException e )
194        {
195            throw new WebException( WebException.WebCode.ERROR_ENCRYPT_PASSWORD, "This password cannot be encrypted" );
196        }
197        catch( ServiceException e )
198        {
199            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
200        }
201
202        return getAllAndWaitingUsers();
203    }
204
205    /**
206     * This method changes the state user and sends an email to inform of the administrator decision.
207     * If the email can't be sent, the state will be not changed
208     *
209     * @param userId
210     * @param isAccepted
211     * @return
212     * @throws WebException
213     * @throws ServiceException
214     */
215    @ControllerMethod(jsonResult = true)
216    public JSONObject acceptOrRefuseUser( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer userId,
217                                          @ParamName(ParameterConstants.PARAMETER_OK) final boolean isAccepted )
218            throws WebException
219    {
220        final User user;
221        try
222        {
223            user = getEtherService().getUserById( userId );
224        }
225        catch( ServiceException e )
226        {
227            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
228        }
229
230        try
231        {
232            sendEmailToUser( user, isAccepted );
233            getEtherService().acceptOrRefuseUser( userId, isAccepted );
234        }
235        catch( MessagingException e )
236        {
237            throw new WebException( WebException.WebCode.ERROR_EMAIL_CANNOT_BE_SEND, "The email cannot be send to the user : " + user.getEmail(), WebException.getExceptionThrowable() );
238        }
239        catch( ServiceException e )
240        {
241            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
242        }
243
244        return getAllAndWaitingUsers();
245    }
246
247    @ControllerMethod(jsonResult = true)
248    public JSONObject sortUser( @NotNull @ParamName("sort") final String sort,
249                                @Nullable @ParamName("searchText") final String searchText,
250                                @NotNull @ParamName("sortRole") final String sortRole,
251                                @NotNull @ParamName("sortState") final String sortState,
252                                @NotNull @ParamName("sortAccessBoTrue") final Boolean sortAccessBoTrue,
253                                @NotNull @ParamName("sortAccessBoFalse") final Boolean sortAccessBoFalse,
254                                @ParamName(ParameterConstants.PARAMETER_MAX_RESULTS) final Integer maxResults,
255                                @ParamName(ParameterConstants.PARAMETER_PAGE) final Integer page )
256            throws WebException
257    {
258        try
259        {
260            final UserFilter filter = new UserFilter( sort, searchText, sortAccessBoFalse, sortAccessBoTrue, maxResults, page );
261            if( !"ALL".equals( sortRole ) )
262                filter.setSortRole( UserRole.valueOf( sortRole ) );
263
264            if( !"ALL".equals( sortState ) )
265                filter.setSortState( UserState.valueOf( sortState ) );
266
267            final List<User> waitingUsers = getEtherService().getUsersByState( UserState.WAITING );
268            final PaginatedResult<User> users = getEtherService().searchUsers( filter );
269
270            final JSONObject result = new JSONObject();
271            result.put( "jSonWaitingUsers", getJsonHelper().toJSON( waitingUsers ) );
272            result.put( "jSonUsers", getJsonHelper().toJSON( users.getPaginatedResults() ) );
273            result.put( "usersNumber", users.getTotalCount() );
274            return result;
275        }
276        catch( ServiceException e )
277        {
278            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
279        }
280    }
281
282    /**
283     * This method sorts the MCO's requests
284     *
285     * @param sort
286     * @param searchText
287     * @param sortState
288     * @param sortType
289     * @param maxResults
290     * @param page
291     * @return
292     * @throws WebException
293     */
294    @ControllerMethod(jsonResult = true)
295    public JSONObject sortRequest( @NotNull @ParamName("sort") final String sort,
296                                   @Nullable @ParamName("searchText") final String searchText,
297                                   @NotNull @ParamName("sortState") final String sortState,
298                                   @NotNull @ParamName("sortType") final String sortType,
299                                   @ParamName(ParameterConstants.PARAMETER_MAX_RESULTS) final Integer maxResults,
300                                   @ParamName(ParameterConstants.PARAMETER_PAGE) final Integer page )
301            throws WebException
302    {
303        try
304        {
305            final McoFilter filter = new McoFilter( sort, searchText, maxResults, page );
306            if( !"ALL".equals( sortState ) )
307                filter.setSortState( McoState.valueOf( sortState ) );
308
309            if( !"ALL".equals( sortType ) )
310                filter.setSortType( McoType.valueOf( sortType ) );
311
312            final PaginatedResult<Mco> requests = getEtherService().searchMcos( filter );
313
314            final JSONObject result = new JSONObject();
315            result.put( "jSonRequests", getJsonHelper().toJSON( requests.getPaginatedResults() ) );
316            result.put( "requestNumber", requests.getTotalCount() );
317            return result;
318        }
319        catch( ServiceException e )
320        {
321            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
322        }
323    }
324
325    @ControllerMethod(jsonResult = true)
326    public void addRequest( @Nullable @ParamName(ParameterConstants.PARAMETER_CODE) final String code,
327                            @NotNull @ParamName(ParameterConstants.PARAMETER_EMAIL) final String email,
328                            @NotNull @ParamName(ParameterConstants.PARAMETER_STATE) final String state,
329                            @NotNull @ParamName(ParameterConstants.PARAMETER_TYPE) final String type,
330                            @Nullable @ParamName(ParameterConstants.PARAMETER_TITLE) final String title,
331                            @Nullable @ParamName(ParameterConstants.PARAMETER_INFORMATIONS) final String informations )
332            throws WebException, NoSuchAlgorithmException
333    {
334        try
335        {
336//            final Mco existingMco = getEtherService().getMcoByCode( code );
337//            if( null == existingMco )
338//            {
339            final Date creationDate = new Date();
340            final Mco mco = new Mco( code, creationDate, email, title, McoState.valueOf( state ), McoType.valueOf( type ), informations );
341            if( state.equals( McoState.D_CLOSED.name() ) )
342                mco.setClosingDate( new Date() );
343            else
344                mco.setClosingDate( null );
345
346            getEtherService().createMco( mco );
347//            }
348//            else
349//                throw new WebException( WebException.WebCode.MCO_ALREADY_EXISTS, "This code already corresponds to a MCO", WebException.getExceptionThrowable() );
350        }
351        catch( ServiceException e )
352        {
353            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
354        }
355    }
356
357    @ControllerMethod(jsonResult = true)
358    public void closeRequest( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer requestId )
359            throws WebException
360    {
361        try
362        {
363            final Mco mco = getEtherService().getMcoById( requestId );
364            if( null == mco )
365                throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, "Request id not found : " + requestId );
366
367            mco.setState( McoState.D_CLOSED );
368            mco.setClosingDate( new Date() );
369            getEtherService().updateMco( mco );
370        }
371        catch( ServiceException e )
372        {
373            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
374        }
375    }
376
377    @ControllerMethod(jsonResult = true)
378    public void removeRequest( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer requestId )
379            throws WebException
380    {
381        try
382        {
383            getEtherService().removeMcoById( requestId );
384        }
385        catch( ServiceException e )
386        {
387            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
388        }
389    }
390
391    @ControllerMethod(jsonResult = true)
392    public void modifyRequest( @NotNull @ParamName(ParameterConstants.PARAMETER_ID) final Integer requestId,
393                               @Nullable @ParamName(ParameterConstants.PARAMETER_CODE) final String code,
394                               @NotNull @ParamName(ParameterConstants.PARAMETER_EMAIL) final String email,
395                               @NotNull @ParamName(ParameterConstants.PARAMETER_STATE) final String state,
396                               @NotNull @ParamName(ParameterConstants.PARAMETER_TYPE) final String type,
397                               @Nullable @ParamName(ParameterConstants.PARAMETER_TITLE) final String title,
398                               @Nullable @ParamName(ParameterConstants.PARAMETER_INFORMATIONS) final String informations )
399            throws WebException
400    {
401        try
402        {
403//            final Mco existingMco = getEtherService().getMcoByCode( code );
404//            if( null == existingMco || requestId.equals( existingMco.getId() ) )
405//            {
406            final Mco mco = getEtherService().getMcoById( requestId );
407            mco.setCode( code );
408            mco.setEmailUser( email );
409            mco.setState( McoState.valueOf( state ) );
410            if( state.equals( McoState.D_CLOSED.name() ) )
411                mco.setClosingDate( new Date() );
412            else
413                mco.setClosingDate( null );
414            mco.setType( McoType.valueOf( type ) );
415            mco.setTitle( title );
416            mco.setInformations( informations );
417
418            getEtherService().updateMco( mco );
419//            }
420//            else
421//                throw new WebException( WebException.WebCode.MCO_ALREADY_EXISTS, "This code already corresponds to a MCO", WebException.getExceptionThrowable() );
422        }
423        catch( ServiceException e )
424        {
425            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
426        }
427    }
428
429
430    /**
431     * This method sorts the datasets
432     *
433     * @param sort
434     * @param searchText
435     * @param maxResults
436     * @param page
437     * @return
438     * @throws WebException
439     */
440    @ControllerMethod(jsonResult = true)
441    public JSONObject sortDataSet( @NotNull @ParamName("sort") final String sort,
442                                   @Nullable @ParamName("searchText") final String searchText,
443                                   @ParamName(ParameterConstants.PARAMETER_MAX_RESULTS) final Integer maxResults,
444                                   @ParamName(ParameterConstants.PARAMETER_PAGE) final Integer page )
445            throws WebException
446    {
447        try
448        {
449            final JeuFilter filter = new JeuFilter( sort, searchText, maxResults, page );
450
451            final PaginatedResult<Jeu> datasets = getEtherService().searchDatasets( filter );
452
453            final JSONObject result = new JSONObject();
454            result.put( "jSonDatasets", getJsonHelper().toJSON( datasets.getPaginatedResults() ) );
455            result.put( "datasetNumber", datasets.getTotalCount() );
456            return result;
457        }
458        catch( ServiceException e )
459        {
460            throw new WebException( WebException.WebCode.ERROR_NO_REQUEST_FOUND, e );
461        }
462    }
463
464    /**
465     * This method create and send an email to the user to inform of the administrator decision
466     *
467     * @param user
468     * @param isAccepted
469     * @throws WebException
470     */
471    private void sendEmailToUser( @NotNull final User user, final boolean isAccepted )
472            throws MessagingException
473    {
474        final MailFactory mailFactory = (MailFactory) getServletContext().getAttribute( "APP_MAILFACTORY" );
475        final String from = (String) getServletContext().getAttribute( "APP_WEBMASTER" );
476        final String subject = "[MEGAPOLI] User inscription";
477        String content = "Dear user, \n\nThe Megapoli administrator has ";
478        if( isAccepted )
479            content += "accepted your inscription. You can now access to data with you login (" + user.getEmail() + ") and the password you gave during inscription.\n";
480        else
481            content += "refused your inscription. You can reply to this email if you want more information.\n";
482
483        content += "\nBest regards,\nMegapoli administrator";
484
485        final Mail mail = new Mail( from, user.getEmail(), null, content, subject );
486        mailFactory.sendMail( mail );
487    }
488
489
490    private JSONObject getAllAndWaitingUsers()
491            throws WebException
492    {
493        try
494        {
495            final List<User> waitingUsers = getEtherService().getUsersByState( UserState.WAITING );
496            final List<User> users = getEtherService().getAllUsersByNameOrder();
497
498            final JSONObject result = new JSONObject();
499            result.put( "jSonWaitingUsers", getJsonHelper().toJSON( waitingUsers ) );
500            result.put( "jSonUsers", getJsonHelper().toJSON( users ) );
501            return result;
502        }
503        catch( ServiceException e )
504        {
505            throw new WebException( WebException.WebCode.ERROR_NO_USER_FOUND, e );
506        }
507    }
508
509    /**
510     * This method return the list of user's states in "json"
511     *
512     * @return
513     */
514    private List<JSONObject> getJSONUserStates()
515    {
516        final UserState[] userStates = UserState.values();
517
518        final List<JSONObject> jsonUserStates = new ArrayList<JSONObject>( userStates.length );
519
520        for( final UserState userState : userStates )
521        {
522            final JSONObject jsonUserState = new JSONObject();
523            jsonUserState.put( "text", userState.name() );
524            jsonUserState.put( "value", userState.name() );
525            jsonUserStates.add( jsonUserState );
526        }
527        return jsonUserStates;
528    }
529
530    /**
531     * This method return the list of user's roles in "json"
532     *
533     * @return
534     */
535    private List<JSONObject> getJSONUserRoles()
536    {
537        final UserRole[] userRoles = UserRole.values();
538
539        final List<JSONObject> jsonUserRoles = new ArrayList<JSONObject>( userRoles.length );
540
541        for( final UserRole userRole : userRoles )
542        {
543            final JSONObject jsonUserRole = new JSONObject();
544            jsonUserRole.put( "text", userRole.name() );
545            jsonUserRole.put( "value", userRole.name() );
546            jsonUserRoles.add( jsonUserRole );
547        }
548        return jsonUserRoles;
549    }
550
551    /**
552     * This method return the list of mco's states in "json"
553     *
554     * @return
555     */
556    private List<JSONObject> getJSONMcoStates()
557    {
558        final McoState[] mcoStates = McoState.values();
559
560        final List<JSONObject> jsonMcoStates = new ArrayList<JSONObject>( mcoStates.length );
561
562        for( final McoState mcoState : mcoStates )
563        {
564            final JSONObject jsonMcoState = new JSONObject();
565            jsonMcoState.put( "text", mcoState.name() );
566            jsonMcoState.put( "value", mcoState.name() );
567            jsonMcoStates.add( jsonMcoState );
568        }
569        return jsonMcoStates;
570    }
571
572    /**
573     * This method return the list of mco's types in "json"
574     *
575     * @return
576     */
577    private List<JSONObject> getJSONMcoTypes()
578    {
579        final McoType[] mcoTypes = McoType.values();
580
581        final List<JSONObject> jsonMcoTypes = new ArrayList<JSONObject>( mcoTypes.length );
582
583        for( final McoType mcoType : mcoTypes )
584        {
585            final JSONObject jsonMcoType = new JSONObject();
586            jsonMcoType.put( "text", mcoType.name() );
587            jsonMcoType.put( "value", mcoType.name() );
588            jsonMcoTypes.add( jsonMcoType );
589        }
590        return jsonMcoTypes;
591    }
592
593    private static final Log LOGGER = LogFactory.getLog( ControllerBackoffice.class );
594
595    private static final String VIEW_BO_INDEX = "backoffice/index";
596    private static final String VIEW_BO_USER = "backoffice/user";
597    private static final String VIEW_BO_MCO = "backoffice/mco";
598    private static final String VIEW_BO_DATA_INSERTION = "backoffice/dataInsertion";
599}
Note: See TracBrowser for help on using the repository browser.