Commit 1cbc86e7 by Antti Väyrynen

Merge branch 'feature/i18n-for-angular' into 'master'

Feature/i18n for angular

See merge request !395
2 parents b1f00ba6 396250da
Showing with 738 additions and 879 deletions
......@@ -40,3 +40,4 @@ package-lock.json
#System Files
.DS_Store
Thumbs.db
......@@ -12,10 +12,10 @@ Kehittäminen on nopeampaa jos saa muutokset suoraan käyttöön, tämän takia
ng-palvelimessa on bugi, ja se ei osaa jakaa tavaraa muusta hakemistosta kuin /.
moyaproxy.conf.json sisältää proxyasetukset porttiin 8080.
moyaproxy.conf.json sisältää proxyasetukset localhostin porttiin 8080.
Käyttö:
`ng serve --preserve-symlinks --proxy-config=moyaproxy.conf.json --base-href=/`
`npm run start`
Tämän jälkeen kirjaa selaimesi sisään moyaan: http://localhost:4200/MoyaWeb/ ja surffata softaan: http://localhost:4200/
......@@ -34,6 +34,8 @@ Jos tulee muita järkeviä kokonaisuuksia, joita voi käyttää muualla, jaa oma
## Hakemistohierarkia
Älykäs komponentti:
* app
* pages `tämän alla on käytännössä "älykkäät" komponentit (stateful), eli componentit jotka tietää mitä dataa haetaan ja mistä. Käytännössä route -targetit`
* user `Loppukäyttäjälle näkyvät jutut, ohjleman ns. main moduuli`
......@@ -69,11 +71,14 @@ Jos tulee muita järkeviä kokonaisuuksia, joita voi käyttää muualla, jaa oma
* html
* ts
* scss
* components `servicet sekä componenttien geneeriset tyhmät osat tulevat tämän hakemiston alle `
* components `servicet sekä componenttien geneeriset tyhmät osat tulevat tämän hakemiston alle. Tänne voi myös pistää älykkäitä pieniä komponentteja `
* viplist
* list.component.ts
* add.component.ts
* modules `Kokonaiset, monessa paikassa olevt kokonaisuuksien tyhmät osat tulevat tänne. Sen verta isot että ne kannattaa tehdä moduuleiksi`
* moya-locale
* moya-locale.service.ts
* moya-locale.model.ts `model -tiedosto joka on käytössä vaan moya-locale -servicessä`
* modules `Kokonaiset, monessa paikassa olevat kokonaisuuksien tyhmät osat tulevat tänne. Sen verta isot että ne kannattaa tehdä moduuleiksi`
* pizzatilaus
* anna-pizza.component.ts
* list-pizzat.component.ts,html,jne
......@@ -86,12 +91,17 @@ Jos tulee muita järkeviä kokonaisuuksia, joita voi käyttää muualla, jaa oma
## I18N & Localization
Kieleistyksessä on käytössä [ngx-translate](https://github.com/ngx-translate/core). (koska angularin oma kieleistys oli rikki kieleistyksen toteutushetkellä).
Lokalisointi -tukea ei vielä ole.
Kielitiedostot sijaitsevat: assets/i18n -hakemistossa. You figure it out how they works.
## TODO
Tekemistä jota voi esim kämpissä säätää
### I18N
I18N loaderi webpackkiin. Esim. muuntaa properties-filun taulukoksi ja siihen joku localisointikirjasto, tai jotain.
### Paketointi
Miten paketoidaan moya niin että mukaan kääntyy myös angular -jutukkeet?
......
{
"compileOnSave": false,
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"outDir": "../dist/out-tsc-e2e",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
......@@ -25,6 +25,8 @@
"@angular/platform-browser": "^5.2.9",
"@angular/platform-browser-dynamic": "^5.2.9",
"@angular/router": "^5.2.9",
"@ngx-translate/core": "^9.0.0",
"@ngx-translate/http-loader": "^2.0.0",
"bootstrap": "^4.0.0",
"core-js": "^2.5.1",
"ngx-bootstrap": "^2.0.2",
......
......@@ -8,8 +8,10 @@
<div id="contentarea">
<div id="topbar">
<top-menu></top-menu>
<moya-locale></moya-locale>
</div>
<div id="content">
<router-outlet></router-outlet>
</div>
</div>
......
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var AppComponent = (function () {
function AppComponent(router, zone) {
this.router = router;
this.zone = zone;
this.counter = 4;
this.title = 'app works!';
window.angularRoute = (function (url) {
zone.run(function () {
router.navigateByUrl(url);
});
});
// Enable change detection sometimes to see that it's not overflooded.
// bcause it takes time
//zone.onMicrotaskEmpty.subscribe(() => {console.log(".");}); // <-- Print "." everytime change detection is possibly
}
AppComponent = __decorate([
core_1.Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
], AppComponent);
return AppComponent;
}());
exports.AppComponent = AppComponent;
......@@ -8,7 +8,6 @@
}
#contentarea {
flex-grow: 1;
display: flex;
......@@ -17,6 +16,9 @@
#topbar {
margin-bottom: 30px;
display: flex;
justify-content: space-between;
align-items: center;
}
#content {
......
......@@ -14,21 +14,21 @@ describe('AppComponent', () => {
});
it('should create the app', async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app works!'`, async(() => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app works!');
}));
it('should render title in a h1 tag', async(() => {
let fixture = TestBed.createComponent(AppComponent);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('app works!');
}));
});
......@@ -19,6 +19,8 @@ export class AppComponent {
router.navigateByUrl(url);
});
});
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var platform_browser_1 = require('@angular/platform-browser');
var core_1 = require('@angular/core');
var forms_1 = require('@angular/forms');
var http_1 = require('@angular/http');
var app_component_1 = require('./app.component');
var viplist_component_1 = require('./viplist/viplist.component');
var ng2_bootstrap_1 = require("ng2-bootstrap");
var moya_angular_common_1 = require("moya-angular-common");
var router_1 = require('@angular/router');
var test_component_1 = require("./test/test.component");
var old_moya_component_1 = require('./old-moya/old-moya.component');
var safe_pipe_1 = require('./safe.pipe');
var appRoutes = [
{ path: 'vip/viplist', component: viplist_component_1.ViplistComponent },
{ path: 'test', component: test_component_1.TestComponent },
{ path: 'old', component: old_moya_component_1.OldMoyaComponent }
];
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
declarations: [
app_component_1.AppComponent,
viplist_component_1.ViplistComponent,
test_component_1.TestComponent,
old_moya_component_1.OldMoyaComponent,
safe_pipe_1.SafePipe,
],
imports: [
platform_browser_1.BrowserModule,
forms_1.FormsModule,
http_1.HttpModule,
ng2_bootstrap_1.AlertModule.forRoot(),
moya_angular_common_1.MoyaRestModule.forRoot(),
router_1.RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [app_component_1.AppComponent]
})
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
import {BrowserModule} from '@angular/platform-browser';
import {Injector, NgModule, ReflectiveInjector} from '@angular/core';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {AppComponent} from './app.component';
import {ViplistComponent} from './viplist/viplist.component';
import {ViplistComponent} from './pages/info/viplist/viplist.component';
import {AlertModule} from 'ngx-bootstrap';
......@@ -18,13 +18,17 @@ import {UserMenuComponent} from './menu/user-menu/user-menu.component';
import {UserComponent} from './pages/user/user.component';
import {InfoComponent} from './pages/info/info.component';
import {AdminComponent} from './pages/admin/admin.component';
import {HttpClientModule, HttpHandler } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import {StaticInjector} from "@angular/core/src/di/injector";
import {CommonModule} from "@angular/common";
import {CacheService} from "./shared/services/cache.service";
import {MoyaRestModule} from "./moya-rest";
import {SafePipe} from "./shared/pipes/safe.pipe";
import {HTTP_INTERCEPTORS, HttpClient, HttpClientModule} from '@angular/common/http';
import {CommonModule} from '@angular/common';
import {CacheService} from './shared/services/cache.service';
import {SafePipe} from './shared/pipes/safe.pipe';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {MoyaLocaleService} from './components/moya-locale/moya-locale.service';
import { MoyaLocaleComponent } from './components/moya-locale/moya-locale.component';
import {ErrorInterceptor} from './shared/interceptors/error.interceptor';
import {ViplistService} from './pages/info/viplist/viplist.service';
import {UserService} from './shared/services/user.service';
const appRoutes: Routes = [
{
......@@ -71,7 +75,8 @@ const appRoutes: Routes = [
UserComponent,
InfoComponent,
AdminComponent,
SafePipe
SafePipe,
MoyaLocaleComponent
],
imports: [
......@@ -80,11 +85,22 @@ const appRoutes: Routes = [
FormsModule,
HttpClientModule,
AlertModule.forRoot(),
MoyaRestModule,
//MoyaRestModule.forRoot(),
RouterModule.forRoot(appRoutes)
RouterModule.forRoot(appRoutes),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: function (http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
},
deps: [HttpClient]
}
})
],
providers: [CacheService],
providers: [
CacheService,
MoyaLocaleService,
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
UserService],
bootstrap: [AppComponent]
})
export class AppModule {
......
<div id="flagBond">
<img src="assets/Flag_of_Finland.svg" [className]="(fiSelected)? 'disabledFlag':'flag' "height="20px" (click)="selectFinnish()" />
<img src="assets/Flag_of_Britain.svg" [className]="(enSelected)? 'disabledFlag':'flag'" height="20px" (click)="selectEnglish()" />
<img src="assets/Flag_of_Sweden.svg" [className]="(svSelected)? 'disabledFlag':'flag'" height="20px" (click)="selectSwedish()" />
</div>
.disabledFlag,
.flag {
border: 1px solid black;
margin-right: 3px;
cursor: pointer;
}
.disabledFlag {
opacity: 0.0;
cursor: auto;
border: none;
}
/* http://flexboxfroggy.com/ */
#flagBond {
display: flex;
}
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MoyaLocaleComponent } from './moya-locale.component';
describe('MoyaLocaleComponent', () => {
let component: MoyaLocaleComponent;
let fixture: ComponentFixture<MoyaLocaleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MoyaLocaleComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MoyaLocaleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import {DEFAULT_LOCALE, MoyaLocaleService} from './moya-locale.service';
import {TranslateService} from '@ngx-translate/core';
const ENGLISH = 'en';
const FINNISH = 'fi';
const SWEDISH = 'sv';
@Component({
selector: 'moya-locale',
templateUrl: './moya-locale.component.html',
styleUrls: ['./moya-locale.component.scss']
})
export class MoyaLocaleComponent implements OnInit {
fiSelected = true;
svSelected = true;
enSelected = true;
constructor(private localeService: MoyaLocaleService, private translate: TranslateService) {
// fallback language
translate.setDefaultLang(DEFAULT_LOCALE);
this.selectLocale(DEFAULT_LOCALE);
}
ngOnInit() {
this.localeService.getUserLocale().subscribe(locale => { this.selectLocale(locale); } );
}
selectLocale(locale: string, save = false): void {
if (![ENGLISH, FINNISH, SWEDISH].includes(locale)) {
return;
}
this.translate.use(locale);
this.fiSelected = this.svSelected = this.enSelected = false;
switch (locale) {
case FINNISH:
this.fiSelected = true;
break;
case ENGLISH:
this.enSelected = true;
break;
case SWEDISH:
this.svSelected = true;
break;
}
if (save) {
this.localeService.setUserLocale(locale);
}
}
selectEnglish() {
this.selectLocale(ENGLISH, true);
}
selectFinnish() {
this.selectLocale(FINNISH, true);
}
selectSwedish() {
this.selectLocale(SWEDISH, true);
}
}
export interface MoyaLocale {
userLocale: string;
eventLocale: string;
}
/* tslint:disable:no-unused-variable */
import { TestBed, inject } from '@angular/core/testing';
import { TestBed, async, inject } from '@angular/core/testing';
import { MoyaRestService } from './moya-rest.service';
import { MoyaLocaleService } from './moya-locale.service';
describe('MoyaRestService', () => {
describe('MoyaLocaleService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [MoyaRestService]
providers: [MoyaLocaleService]
});
});
it('should ...', inject([MoyaRestService], (service: MoyaRestService) => {
it('should be created', inject([MoyaLocaleService], (service: MoyaLocaleService) => {
expect(service).toBeTruthy();
}));
});
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {MoyaLocale} from './moya-locale.model';
import {MOYA_BASE_URL, MoyaRestTool} from '../../shared/tools/moya-rest.tool';
import {HttpClient} from '@angular/common/http';
import 'rxjs/add/operator/catch';
export const DEFAULT_LOCALE = 'fi';
const LOCALSTORAGE_NAME = 'currently used locale code';
@Injectable()
export class MoyaLocaleService {
constructor(private http: HttpClient) { }
/**
* Order of Locale:
* 1. User's locale from database
* 2. User's locale from cookie
* 3. Event's locale from database
* 4. Default
*
* @return {Observable<string>} Return current locale as a string. No errors.
*/
public getUserLocale(): Observable<string> {
return this.http.get<MoyaLocale>(MOYA_BASE_URL + '/v3/locale/')
.catch(x => Observable.of({} as MoyaLocale))
.map(locale => {
if (locale && locale.userLocale) {
return locale.userLocale;
}
const storageLocale = localStorage.getItem(LOCALSTORAGE_NAME);
if (storageLocale) {
return storageLocale;
}
if (locale.eventLocale) {
return locale.eventLocale;
}
return DEFAULT_LOCALE;
});
}
/**
* Store user's locale. This will store it to server. Or server is not available, into localstorage.
*
* There is no errors
* @param {string} locale
*/
public setUserLocale(locale: string): void {
const newLocale: MoyaLocale = {
userLocale: locale,
eventLocale: undefined
};
// let's save locale to database, if it fails, we save it into localstorage. No errors to show for user.
this.http.post(MOYA_BASE_URL + '/v3/locale/', newLocale).catch(x => {
localStorage.setItem(LOCALSTORAGE_NAME, locale);
return 'ok';
}).subscribe();
}
}
......@@ -6,7 +6,7 @@ import {MenuGroup} from '../models/menu-group.model';
export class MENU {
static ADMIN: MenuGroup[]= [
static ADMIN: MenuGroup[] = [
{
'name': 'Kauppa',
'items': [
......
......@@ -9,7 +9,7 @@ import {MENU} from '../defines/menu';
})
export class InfoMenuComponent implements OnInit {
menu: MenuGroup[]= MENU.INFO;
menu: MenuGroup[] = MENU.INFO;
constructor() { }
......
......@@ -9,7 +9,7 @@ import {MENU} from '../defines/menu';
})
export class UserMenuComponent implements OnInit {
menu: MenuGroup[]= MENU.USER;
menu: MenuGroup[] = MENU.USER;
constructor() { }
......
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var common_1 = require('@angular/common');
var http_1 = require("@angular/http");
var moya_rest_service_1 = require("../shared/services/moya-rest.service");
var viplist_service_1 = require("../shared/services/viplist.service");
var cache_service_1 = require("../shared/services/cache.service");
var user_service_1 = require("../shared/services/user.service");
var MoyaRestModule = (function () {
function MoyaRestModule() {
}
MoyaRestModule.forRoot = function () {
return {
ngModule: MoyaRestModule,
providers: [
moya_rest_service_1.MoyaRestService,
viplist_service_1.ViplistService,
cache_service_1.CacheService,
user_service_1.UserService
]
};
};
MoyaRestModule = __decorate([
core_1.NgModule({
imports: [
common_1.CommonModule,
http_1.HttpModule
],
declarations: []
})
], MoyaRestModule);
return MoyaRestModule;
}());
exports.MoyaRestModule = MoyaRestModule;
import {NgModule, ModuleWithProviders, NgZone, Injector} from '@angular/core';
import { CommonModule } from '@angular/common';
import {MoyaRestService} from "../shared/services/moya-rest.service";
import {ViplistService} from "../shared/services/viplist.service";
import {CacheService} from "../shared/services/cache.service";
import {UserService} from "../shared/services/user.service";
import {HttpClientModule} from "@angular/common/http";
import {HttpModule} from "@angular/http";
export * from "../shared/services/moya-rest.service";
export * from "../shared/services/viplist.service";
export * from "../shared/services/cache.service";
export * from "../shared/services/user.service";
export * from "../shared/models/user.model";
export * from "../shared/models/vip.model";
export * from "../shared/models/vip-product.model";
export * from "../shared/models/vip-product-delivery.model";
@NgModule({
imports: [
CommonModule,
HttpClientModule
],
declarations: [ ],
providers: [
MoyaRestService,
ViplistService,
CacheService,
UserService,
HttpClientModule
/*{ provide: NgZone, useFactory: () => new NgZone({}) },
{ provide: Injector, useFactory: () => Injector.create({providers: []}) } */
],
exports: [
],
})
export class MoyaRestModule {
/*
static forRoot(): ModuleWithProviders {
return {
ngModule: MoyaRestModule,
providers: [
MoyaRestService,
ViplistService,
CacheService,
UserService,
HttpClientModule
/*{ provide: NgZone, useFactory: () => new NgZone({}) },
{ provide: Injector, useFactory: () => Injector.create({providers: []}) }
]
};
}*/
}
import {Component, NgZone, OnInit} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Vip} from "../shared/models/vip.model";
import {ViplistService} from "../shared/services/viplist.service";
import {Observable} from 'rxjs/Observable';
import {Vip} from '../../../shared/models/vip.model';
import {ViplistService} from './viplist.service';
@Component({
selector: 'moya-viplist',
templateUrl: './viplist.component.html',
styleUrls: ['./viplist.component.scss']
styleUrls: ['./viplist.component.scss'],
providers: [ViplistService]
})
export class ViplistComponent implements OnInit {
......
import {Injectable} from '@angular/core';
import {MoyaRestService} from "./moya-rest.service";
import {Vip} from "../models/vip.model";
import {Response} from "@angular/http";
import {User} from "../models/user.model";
import {UserService} from "./user.service";
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/switchMap";
import "rxjs/add/observable/forkJoin";
import "rxjs/add/operator/first";
import {HttpResponse} from "@angular/common/http";
import {Vip} from '../../../shared/models/vip.model';
import {User} from '../../../shared/models/user.model';
import {UserService} from '../../../shared/services/user.service';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/first';
import {HttpClient} from '@angular/common/http';
import {MOYA_BASE_URL} from '../../../shared/tools/moya-rest.tool';
@Injectable()
export class ViplistService {
constructor(private moyaRestService: MoyaRestService, private userService : UserService) {
constructor(private http: HttpClient, private userService: UserService) {
}
......@@ -26,12 +25,12 @@ export class ViplistService {
public get(searchString?: string): Observable<Array<Vip>> {
if (!searchString) {
return this.moyaRestService.get("v3/vip/all")
.switchMap(res => Observable.forkJoin(...res.map(apiRow => this.hostPopulator(apiRow))));
return this.http.get(MOYA_BASE_URL + 'v3/vip/all')
.switchMap(res => Observable.forkJoin(...(res as Array<any>).map(apiRow => this.hostPopulator(apiRow))));
}
return this.moyaRestService.get("v3/vip/search/" + searchString)
.switchMap(v => Observable.forkJoin(...v.map(x => this.hostPopulator(x))));
return this.http.get(MOYA_BASE_URL + 'v3/vip/search/' + searchString)
.switchMap(v => Observable.forkJoin(...(v as Array<any>).map(x => this.hostPopulator(x))));
}
......@@ -43,10 +42,11 @@ export class ViplistService {
*/
public async delete(vip: Vip): Promise<boolean> {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
if (!vip.id) {
throw new Error('TODO: errori, tyhmä vippi');
}
let res: HttpResponse<any> = await this.moyaRestService.delete("v3/vip/" + vip.id)
const res: any = await this.http.delete(MOYA_BASE_URL + 'v3/vip/' + vip.id)
.first()
.toPromise();
......@@ -55,19 +55,19 @@ export class ViplistService {
public getWithId(id: number): Observable<Vip> {
return this.moyaRestService.get("v3/vip/" + id)
return this.http.get(MOYA_BASE_URL + 'v3/vip/' + id).map(x => x as Vip);
}
public create(vip: Vip): Observable<Vip> {
return this.moyaRestService.post("v3/vip/create", vip)
return this.http.post(MOYA_BASE_URL + 'v3/vip/create', vip).map(x => x as Vip);
}
private hostPopulator(rawVip : any): Observable<Vip> {
private hostPopulator(rawVip: any): Observable<Vip> {
return this.userService.get(rawVip.hostId)
.map((u: User) => {rawVip.host = u; return <Vip> rawVip });
.map((u: User) => {rawVip.host = u; return <Vip> rawVip; }).map(x => x as Vip);
}
......
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var common_1 = require("@angular/common");
var OldMoyaComponent = (function () {
function OldMoyaComponent(location) {
this.location = location;
this.frameUrl = "/MoyaWeb/";
}
OldMoyaComponent.prototype.ngOnInit = function () {
};
OldMoyaComponent.prototype.logIt = function () {
console.log(this.frameUrl);
console.log(this.frametus.nativeElement.contentWindow.location.href);
console.log(location.path(true));
};
__decorate([
core_1.ViewChild('frametus')
], OldMoyaComponent.prototype, "frametus", void 0);
OldMoyaComponent = __decorate([
core_1.Component({
selector: 'app-old-moya',
providers: [common_1.Location, { provide: common_1.LocationStrategy, useClass: common_1.PathLocationStrategy }],
templateUrl: './old-moya.component.html',
styleUrls: ['./old-moya.component.css']
})
], OldMoyaComponent);
return OldMoyaComponent;
}());
exports.OldMoyaComponent = OldMoyaComponent;
......@@ -25,7 +25,7 @@ export class OldMoyaComponent implements OnInit {
route.queryParamMap.map(a => a.get('p')).subscribe(x => {
console.log(x);
if (x) {
this.frameUrl = '/MoyaWeb/' + x.replace("::", "?");
this.frameUrl = '/MoyaWeb/' + x.replace('::', '?');
}
});
}
......@@ -34,10 +34,10 @@ export class OldMoyaComponent implements OnInit {
ngOnInit() { }
changeUrl() {
let tmpFrameUrl = this.iframe.nativeElement.contentWindow.location.href.split('/MoyaWeb/', 2);
const tmpFrameUrl = this.iframe.nativeElement.contentWindow.location.href.split('/MoyaWeb/', 2);
if (tmpFrameUrl.length > 1) {
this.location.replaceState(this.location.path(false).split('?', 1)[0] + '?p=' + tmpFrameUrl[1].replace("?", "::") );
this.location.replaceState(this.location.path(false).split('?', 1)[0] + '?p=' + tmpFrameUrl[1].replace('?', '::') );
}
......
<p>
user works!
{{'test.user' | translate}} works!
</p>
<div translate>test.user</div>
......@@ -12,4 +12,5 @@ export class UserComponent implements OnInit {
ngOnInit() {
}
}
import {HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<HttpEventType.Response>> {
return next.handle(req).catch(this.handleException);
}
private handleException(error: HttpResponse<any>) {
console.log('error on MOYA rest connection', error);
// TODO: add handlers to 403's and other "not logged in" or "invalid permissions"
// -statuscodes, and route them using some nice global parameter
return Observable.throw(error);
}
}
/**
* Created by tuukka on 15/02/17.
*/
"use strict";
// vim magic: %s/^\s*\w\+\s\+\(\w\+\)\s\+\(\w\+\)\s*.*;$/ \2: \L\1;/
(function (UserGender) {
UserGender[UserGender["MALE"] = 0] = "MALE";
UserGender[UserGender["FEMALE"] = 1] = "FEMALE";
UserGender[UserGender["UNSPECIFIED"] = 2] = "UNSPECIFIED";
})(exports.UserGender || (exports.UserGender = {}));
var UserGender = exports.UserGender;
var User = (function () {
function User() {
}
return User;
}());
exports.User = User;
/**
* Created by tuukka on 04/02/17.
*/
"use strict";
var VipProductDelivery = (function () {
function VipProductDelivery() {
}
return VipProductDelivery;
}());
exports.VipProductDelivery = VipProductDelivery;
"use strict";
/**
* Created by tuukka on 04/02/17.
*/
var VipProduct = (function () {
function VipProduct() {
}
return VipProduct;
}());
exports.VipProduct = VipProduct;
import {VipProductDelivery} from "./vip-product-delivery.model";
import {VipProductDelivery} from './vip-product-delivery.model';
/**
* Created by tuukka on 04/02/17.
*/
......@@ -25,7 +25,7 @@ export class VipProduct {
notes: string;
quantity: number;
delivered: number;
deliveries : VipProductDelivery[];
deliveries: VipProductDelivery[];
constructor() {}
......
"use strict";
/**
* Created by tuukka on 04/02/17.
*/
var Vip = (function () {
function Vip() {
}
return Vip;
}());
exports.Vip = Vip;
import {VipProduct} from "./vip-product.model";
import {User} from "./user.model";
import {VipProduct} from './vip-product.model';
import {User} from './user.model';
/**
* Created by tuukka on 04/02/17.
*/
......
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var DEFAULT_EXPIRE_MS = 300000; // 5min
var CachedItem = (function () {
function CachedItem(moduleName, path, value, isObservable) {
this.moduleName = moduleName;
this.path = path;
this.value = value;
this.expires = new Date();
this.expires.setTime(Date.now() + DEFAULT_EXPIRE_MS);
this.isObservable = isObservable;
}
CachedItem.prototype.isExpired = function () {
return this.expires.getTime() < Date.now();
};
return CachedItem;
}());
/**
* Basic cacheService.
*
* First this was part of moyaRestService, but I thinked that if cache is too easy to use, someone will kill this application with it.
* So let's make it litlebit harder
*/
var CacheService = (function () {
// TODO: timed clearup for cache to save memory
function CacheService(zone) {
this.zone = zone;
this.cache = new Map();
this.timerObservable = rxjs_1.Observable.timer(30000, 30000); // afther 0.5min, every 0.5min.
}
/**
* This will return observable with value from cache, or cache value from your observable and return it in observable.
*
* example: return cacheService.cacheObservable("mymodule",<url>, http.get(<url>).map(v => v.json()));
*
* @param moduleName
* @param cachePath
* @param source: {Observable<any>} Observable where the values, which are cached, is coming from
* @return {Observable<any>}: if value is in cache, this is observable made from this value. Otherwise this is source observable.
*/
CacheService.prototype.cacheObservable = function (moduleName, cachePath, source) {
var _this = this;
var cacheName = this.generateCachename(moduleName, cachePath);
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
console.log(cacheName, " Expired version in cache");
this.cache.delete(cacheName);
}
if (!this.cache.has(cacheName)) {
/*
not in cache, let's change source to hot -observable, and return one instance from it
problem is, that before this observable is runned, there can be queries for this value from cache.
So, let's change this to hot-observable, and put that hot-observable into the cache.
And in first run, we change this hot observable to it's value.
Javascript is asynchronous, so there is no need to worry some weird things that could happen in multithreaded languages.
*/
console.log(cacheName, " not in cache");
var hotSource = source
.do(function (val) { return _this.cache.set(cacheName, new CachedItem(moduleName, cachePath, val)); })
.publishLast().refCount();
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, hotSource, true));
this.checkCleanTimer();
return hotSource;
}
var cacheItem = this.cache.get(cacheName);
// if value is hotObservable, return it, otherwise create observable from value
if (cacheItem.isObservable) {
console.log(cacheName, " hot observable in cache ");
return cacheItem.value;
}
console.log(cacheName, " value in cache");
this.checkCleanTimer();
return rxjs_1.Observable.of(cacheItem.value);
};
CacheService.prototype.clean = function () {
this.cache.clear();
this.checkCleanTimer();
};
CacheService.prototype.cleanExpired = function () {
var _this = this;
this.cache.forEach(function (v, k) {
if (v.isExpired()) {
console.log(k, " Cache expired");
_this.cache.delete(k);
}
});
this.checkCleanTimer();
};
CacheService.prototype.checkCleanTimer = function () {
var _this = this;
if (this.cache.size > 0) {
if (!this.timerSubscription) {
console.log("adding clearing timer");
this.zone.runOutsideAngular(function () {
_this.timerSubscription = _this.timerObservable.subscribe(function (v) {
_this.cleanExpired();
});
});
}
}
else {
if (this.timerSubscription) {
console.log("removing clearing timer");
this.timerSubscription.unsubscribe();
}
}
};
/**
*
* @param moduleName
* @param cachePath
* @param value
*/
CacheService.prototype.set = function (moduleName, cachePath, value) {
var cacheName = this.generateCachename(moduleName, cachePath);
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, value));
};
/**
* Get one value from cache.
*
* Now when there is this observablethingy. Make public afther rethinking this.
*
* @param moduleName
* @param cachePath
* @return {any|null} Null if nothing is in cache.
*/
CacheService.prototype.get = function (moduleName, cachePath) {
var cacheName = this.generateCachename(moduleName, cachePath);
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
this.cache.delete(cacheName);
}
if (this.cache.has(cacheName)) {
return this.cache.get(cacheName);
}
return null;
};
CacheService.prototype.generateCachename = function (moduleName, cachePath) {
return moduleName + "::" + cachePath;
};
CacheService = __decorate([
core_1.Injectable()
], CacheService);
return CacheService;
}());
exports.CacheService = CacheService;
import {Injectable, NgZone} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Injectable, NgZone} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/timer';
import {forkJoin} from "rxjs/observable/forkJoin";
import "rxjs/add/operator/do";
import "rxjs/add/operator/publishLast";
import "rxjs/add/observable/of";
import {Subscription} from "rxjs/Subscription";
import {forkJoin} from 'rxjs/observable/forkJoin';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/publishLast';
import 'rxjs/add/observable/of';
import {Subscription} from 'rxjs/Subscription';
const DEFAULT_EXPIRE_MS = 300000; // 5min
......@@ -17,7 +17,7 @@ class CachedItem {
expires: Date;
isObservable: boolean;
constructor(moduleName: string, path: string, value: any, isObservable? : boolean) {
constructor(moduleName: string, path: string, value: any, isObservable?: boolean) {
this.moduleName = moduleName;
this.path = path;
this.value = value;
......@@ -42,7 +42,7 @@ class CachedItem {
@Injectable()
export class CacheService {
private timerSubscription : Subscription;
private timerSubscription: Subscription;
private timerObservable: Observable<any>;
......@@ -50,7 +50,7 @@ export class CacheService {
// TODO: timed clearup for cache to save memory
constructor(private zone : NgZone) {
constructor(private zone: NgZone) {
this.cache = new Map<string, CachedItem>();
this.timerObservable = Observable.timer(30000, 30000); // afther 0.5min, every 0.5min.
......@@ -68,15 +68,15 @@ export class CacheService {
* @return {Observable<any>}: if value is in cache, this is observable made from this value. Otherwise this is source observable.
*/
public cacheObservable(moduleName: string, cachePath: string, source: Observable<any>): Observable<any> {
let cacheName = this.generateCachename(moduleName, cachePath);
const cacheName = this.generateCachename(moduleName, cachePath);
if(this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
console.log(cacheName, " Expired version in cache");
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
console.log(cacheName, ' Expired version in cache');
this.cache.delete(cacheName);
}
if(!this.cache.has(cacheName)) {
if (!this.cache.has(cacheName)) {
/*
not in cache, let's change source to hot -observable, and return one instance from it
problem is, that before this observable is runned, there can be queries for this value from cache.
......@@ -86,13 +86,13 @@ export class CacheService {
Javascript is asynchronous, so there is no need to worry some weird things that could happen in multithreaded languages.
*/
console.log(cacheName," not in cache");
console.log(cacheName, ' not in cache');
let hotSource = source
.do(val => this.cache.set(cacheName, new CachedItem(moduleName,cachePath, val)))
const hotSource = source
.do(val => this.cache.set(cacheName, new CachedItem(moduleName, cachePath, val)))
.publishLast().refCount();
this.cache.set(cacheName, new CachedItem(moduleName,cachePath, hotSource, true));
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, hotSource, true));
this.checkCleanTimer();
......@@ -101,15 +101,15 @@ export class CacheService {
let cacheItem = this.cache.get(cacheName);
const cacheItem = this.cache.get(cacheName);
// if value is hotObservable, return it, otherwise create observable from value
if(cacheItem.isObservable) {
console.log(cacheName, " hot observable in cache ");
if (cacheItem.isObservable) {
console.log(cacheName, ' hot observable in cache ');
return cacheItem.value;
}
console.log(cacheName, " value in cache");
console.log(cacheName, ' value in cache');
this.checkCleanTimer();
return Observable.of(cacheItem.value);
......@@ -124,9 +124,9 @@ export class CacheService {
public cleanExpired(): void {
this.cache.forEach((v,k) => {
if(v.isExpired()) {
console.log(k, " Cache expired");
this.cache.forEach((v, k) => {
if (v.isExpired()) {
console.log(k, ' Cache expired');
this.cache.delete(k);
}});
......@@ -134,9 +134,9 @@ export class CacheService {
}
private checkCleanTimer() {
if(this.cache.size > 0) {
if(!this.timerSubscription) {
console.log("adding clearing timer");
if (this.cache.size > 0) {
if (!this.timerSubscription) {
console.log('adding clearing timer');
this.zone.runOutsideAngular(() => {
this.timerSubscription = this.timerObservable.subscribe(v => {
......@@ -146,9 +146,9 @@ export class CacheService {
}
} else {
if(this.timerSubscription) {
if (this.timerSubscription) {
console.log("removing clearing timer");
console.log('removing clearing timer');
this.timerSubscription.unsubscribe();
}
}
......@@ -163,9 +163,9 @@ export class CacheService {
* @param value
*/
private set(moduleName: string, cachePath: string, value: any): void {
let cacheName = this.generateCachename(moduleName, cachePath);
const cacheName = this.generateCachename(moduleName, cachePath);
this.cache.set(cacheName, new CachedItem(moduleName,cachePath, value));
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, value));
}
/**
......@@ -178,14 +178,14 @@ export class CacheService {
* @return {any|null} Null if nothing is in cache.
*/
private get(moduleName: string, cachePath: string): CachedItem {
let cacheName = this.generateCachename(moduleName, cachePath);
const cacheName = this.generateCachename(moduleName, cachePath);
if(this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
this.cache.delete(cacheName);
}
if(this.cache.has(cacheName)) {
if (this.cache.has(cacheName)) {
return this.cache.get(cacheName);
}
......@@ -194,7 +194,7 @@ export class CacheService {
private generateCachename(moduleName: string, cachePath: string): string {
return moduleName + "::" + cachePath;
return moduleName + '::' + cachePath;
}
}
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpResponse} from "@angular/common/http";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";
@Injectable()
export class MoyaRestService {
constructor(private http: HttpClient) { }
post(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<any> {
return this.http.post(this.genUrl(subUrl, pathParameters), body)
.catch(this.handleException);
}
put(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<any> {
return this.http.put(this.genUrl(subUrl, pathParameters), body)
.catch(this.handleException);
}
delete(subUrl: string, pathParameters?: Map<string, string>): Observable<any> {
return this.http.delete(this.genUrl(subUrl, pathParameters))
.catch(this.handleException);
}
get(subUrl: string, pathParameters?: Map<string, string>): Observable<any> {
return this.http.get(this.genUrl(subUrl, pathParameters))
.catch(this.handleException);
}
private genUrl(subUrl: string, urlParams?: Map<string, string>): string {
let suffix = "";
if(urlParams) {
urlParams.forEach(function(value: string, key: string) {
if(suffix.length <= 0) {
suffix = "?";
} else {
suffix += "&";
}
suffix += key + "=" + value;
});
}
return "/MoyaWeb/rest/" + subUrl + suffix; // <-- TODO: kauneista
}
/*
private handleResponse(res: HttpResponse<any>) {
console.log(res);
// basicly, 200 statuscodes means success
if(!(res.status >= 200 && res.status <= 299 )) {
console.log("statuscode not between 200 and 299", res.status);
// next stop: handlerException
throw res;
}
return res;
}*/
private handleException(error: HttpResponse<any> | any) {
console.log("error on jira rest connection", error);
// TODO: add handlers to 403's and other "not logged in" or "invalid permissions"
// -statuscodes, and route them using some nice global parameter
return Observable.throw(error);
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var UserService = (function () {
function UserService(moyaRest, cacheService) {
this.moyaRest = moyaRest;
this.cacheService = cacheService;
}
UserService.prototype.get = function (id) {
if (!id || id < 0) {
return rxjs_1.Observable.throw("There should be userid");
}
var path = "v2/user/" + id;
return this.cacheService.cacheObservable("moya:UserService", path, this.moyaRest.get(path)
.do(function (v) { console.log("getting user outside of cache", path); })
.map(function (res) { return (res.json()); }));
};
UserService = __decorate([
core_1.Injectable()
], UserService);
return UserService;
}());
exports.UserService = UserService;
import {Injectable} from "@angular/core";
import {User} from "../models/user.model";
import {MoyaRestService} from "./moya-rest.service";
import {CacheService} from "./cache.service";
import {Observable} from "rxjs/Observable";
import {Injectable} from '@angular/core';
import {User} from '../models/user.model';
import {CacheService} from './cache.service';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from '@angular/common/http';
import {MOYA_BASE_URL} from '../tools/moya-rest.tool';
@Injectable()
export class UserService {
constructor(private moyaRest : MoyaRestService, private cacheService : CacheService) { }
constructor(private http: HttpClient, private cacheService: CacheService) { }
public get(id: number): Observable<User> {
if(!id || id < 0) {
return Observable.throw("There should be userid");
if (!id || id < 0) {
return Observable.throw('There should be userid');
}
let path = "v2/user/" + id;
const path = MOYA_BASE_URL + 'v2/user/' + id;
return this.cacheService.cacheObservable("moya:UserService", path,
this.moyaRest.get(path)
.do(v => {console.log("getting user outside of cache", path)})
.map(res => (<User> res.body)));
return this.cacheService.cacheObservable('moya:UserService', path,
this.http.get<User>(path)
.do(v => {console.log('getting user outside of cache', path); }));
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
var core_1 = require('@angular/core');
var rxjs_1 = require("rxjs");
var ViplistService = (function () {
function ViplistService(moyaRestService, userService) {
this.moyaRestService = moyaRestService;
this.userService = userService;
}
/**
* get vips
* @param searchString: searchString, skip to return all vips
*/
ViplistService.prototype.get = function (searchString) {
var _this = this;
if (!searchString) {
return this.moyaRestService.get("v3/vip/all")
.switchMap(function (res) { return rxjs_1.Observable.forkJoin.apply(rxjs_1.Observable, res.json().map(function (apiRow) { return _this.hostPopulator(apiRow); })); });
}
return this.moyaRestService.get("v3/vip/search/" + searchString)
.switchMap(function (v) { return rxjs_1.Observable.forkJoin.apply(rxjs_1.Observable, v.json().map(function (x) { return _this.hostPopulator(x); })); });
};
/**
* Delete vip.
*
* @param vip
* @return Observable
*/
ViplistService.prototype.delete = function (vip) {
return __awaiter(this, void 0, Promise, function* () {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
var res = yield this.moyaRestService.delete("v3/vip/" + vip.id)
.first()
.toPromise();
return res.ok;
});
};
/*
public deleteProm(vip: Vip): Promise<boolean> {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
return this.moyaRestService.delete("v3/vip/" + vip.id)
.first()
.toPromise()
.then(r => r.ok);
}
*/
ViplistService.prototype.getWithId = function (id) {
return this.moyaRestService.get("v3/vip/" + id)
.map(function (v) { return v.json(); });
};
ViplistService.prototype.create = function (vip) {
return this.moyaRestService.post("v3/vip/create", vip)
.map(function (v) { return v.json(); });
};
ViplistService.prototype.hostPopulator = function (rawVip) {
return this.userService.get(rawVip.hostId)
.map(function (u) { rawVip.host = u; return rawVip; });
};
ViplistService = __decorate([
core_1.Injectable()
], ViplistService);
return ViplistService;
}());
exports.ViplistService = ViplistService;
export const MOYA_BASE_URL = '/MoyaWeb/rest/';
export abstract class MoyaRestTool {
/*
genUrl(subUrl: string, urlParams?: Map<string, string>): string {
let suffix = '';
if (urlParams) {
urlParams.forEach(function(value: string, key: string) {
if (suffix.length <= 0) {
suffix = '?';
} else {
suffix += '&';
}
suffix += key + '=' + value;
});
}
return '/MoyaWeb/rest/' + subUrl + suffix; // <-- TODO: kauneista
} */
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var TestComponent = (function () {
function TestComponent() {
this.counter = 0;
}
TestComponent.prototype.ngOnInit = function () {
};
TestComponent.prototype.addOne = function () {
this.counter++;
};
__decorate([
core_1.Input()
], TestComponent.prototype, "counter", void 0);
TestComponent = __decorate([
core_1.Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
], TestComponent);
return TestComponent;
}());
exports.TestComponent = TestComponent;
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var ViplistComponent = (function () {
function ViplistComponent(viplistService) {
this.viplistService = viplistService;
}
ViplistComponent.prototype.ngOnInit = function () {
this.vips = this.viplistService.get();
};
ViplistComponent = __decorate([
core_1.Component({
selector: 'moya-viplist',
templateUrl: './viplist.component.html',
styleUrls: ['./viplist.component.css']
})
], ViplistComponent);
return ViplistComponent;
}());
exports.ViplistComponent = ViplistComponent;
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
viewBox="0 0 60 30"
width="1200"
height="600"
id="svg3403"
version="1.1"
inkscape:version="0.91 r13725"
sodipodi:docname="Flag_of_the_United_Kingdom.svg">
<metadata
id="metadata3422">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3420" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1600"
inkscape:window-height="837"
id="namedview3418"
showgrid="false"
inkscape:zoom="0.3375"
inkscape:cx="177.77778"
inkscape:cy="300"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:current-layer="svg3403" />
<clipPath
id="t">
<path
d="M30,15 h30 v15 z v15 h-30 z h-30 v-15 z v-15 h30 z"
id="path3406" />
</clipPath>
<path
id="path3408"
d="m 1.7728048e-6,2e-6 0,29.999996 59.9999962271952,0 0,-29.999996 z"
style="fill:#00247d"
inkscape:connector-curvature="0" />
<g
transform="matrix(0.99923007,0,0,0.99796116,-41.704693,34.67408)"
id="g3504">
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;baseline-shift:baseline;text-anchor:start;white-space:normal;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:6;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 41.743796,-34.736135 -0.0052,3.399613 23.299453,11.656015 -23.29292,11.6456408 -0.0083,3.3390294 6.709976,0.0081 23.299108,-11.6411232 23.34047,11.6413252 6.695117,0.0039 -1.9e-4,-3.3197576 -23.325557,-11.6770916 23.324297,-11.658534 0.003,-3.404701 -6.671587,-0.0012 -23.36561,11.710902 -23.408517,-11.705182 z"
id="path3410"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccccccccccccccc" />
<g
id="g3475"
transform="matrix(1.000467,0,0,1.0025461,-90.083492,-1.0167386)">
<path
id="path3473"
style="opacity:1;fill:#cf142b;fill-opacity:1;stroke:none;stroke-width:0;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
d="m 161.74139,-18.612942 4.47326,-0.01609 25.56234,12.8005343 -0.0419,2.1537942 -29.99365,-14.9382355 z m 25.50494,-15.029538 4.33491,0.0062 -29.84225,15.030397 -0.002,-2.252586 25.50972,-12.784027 z m -42.74835,8.567988 -12.73919,-6.383243 0,-2.184788 29.98658,15.024487 -4.41926,0.0058 -12.82813,-6.46226 z m 17.24195,6.456629 0,2.184787 -25.50624,12.7726879 -4.46056,0.00281 29.9668,-14.9602819 z"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccccccccccccccccccccccc" />
</g>
</g>
<g
transform="matrix(0.99923007,0,0,0.99796116,-71.704693,6.7005857)"
id="g3457">
<g
id="g3500">
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;baseline-shift:baseline;text-anchor:start;white-space:normal;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:10;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 96.779206,-6.714273 0,10.0204288 -25.019259,0 0,10.0204282 25.019259,0 0,10.020429 10.007704,0 0,-10.020429 25.01926,0 0,-10.0204282 -25.01926,0 0,-10.0204288 -10.007704,0 z"
id="path3414"
inkscape:connector-curvature="0" />
<path
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;baseline-shift:baseline;text-anchor:start;white-space:normal;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;fill:#cf142b;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:6;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
d="m 98.780746,-6.714273 0,12.0245146 -27.020799,0 0,6.0122564 27.020799,0 0,12.024515 6.004624,0 0,-12.024515 27.0208,0 0,-6.0122564 -27.0208,0 0,-12.0245146 -6.004624,0 z"
id="path3416"
inkscape:connector-curvature="0" />
</g>
</g>
</svg>
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1100">
<rect width="1800" height="1100" fill="#fff"/>
<rect width="1800" height="300" y="400" fill="#003580"/>
<rect width="300" height="1100" x="500" fill="#003580"/>
</svg>
<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1000" viewBox="0 0 16 10">
<rect width="16" height="10" fill="#006aa7"/>
<rect width="2" height="10" x="5" fill="#fecc00"/>
<rect width="16" height="2" y="4" fill="#fecc00"/>
</svg>
{
"test": {
"user": "User"
}
}
{
"test": {
"user": "Käyttäjä"
}
}
{
"test": {
"user": "Userna"
}
}
......@@ -25,7 +25,7 @@ getTestBed().initTestEnvironment(
platformBrowserDynamicTesting()
);
// Then we find all the tests.
let context = require.context('./', true, /\.spec\.ts$/);
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
......
......@@ -3,18 +3,30 @@
"node_modules/codelyzer"
],
"rules": {
"arrow-return-shorthand": true,
"callable-types": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"curly": true,
"deprecation": {
"severity": "warn"
},
"eofline": true,
"forin": true,
"import-blacklist": [
true,
"rxjs",
"rxjs/Rx"
],
"import-spacing": true,
"indent": [
true,
"spaces"
],
"interface-over-type-literal": true,
"label-position": true,
"max-line-length": [
true,
......@@ -23,8 +35,14 @@
"member-access": false,
"member-ordering": [
true,
"static-before-instance",
"variables-before-functions"
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-arg": true,
"no-bitwise": true,
......@@ -38,14 +56,22 @@
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-variable": true,
"no-duplicate-super": true,
"no-empty": false,
"no-empty-interface": true,
"no-eval": true,
"no-inferrable-types": true,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-misused-new": true,
"no-non-null-assertion": true,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unnecessary-initializer": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-var-keyword": true,
......@@ -57,12 +83,14 @@
"check-else",
"check-whitespace"
],
"prefer-const": true,
"quotemark": [
true,
"single"
],
"radix": true,
"semicolon": [
true,
"always"
],
"triple-equals": [
......@@ -79,6 +107,7 @@
"variable-declaration": "nospace"
}
],
"unified-signatures": true,
"variable-name": false,
"whitespace": [
true,
......@@ -88,9 +117,19 @@
"check-separator",
"check-type"
],
"directive-selector": [true, "attribute", "", "camelCase"],
"component-selector": [true, "element", "", "kebab-case"],
"directive-selector": [
true,
"attribute",
"moya",
"camelCase"
],
"component-selector": [
true,
"element",
"moya",
"kebab-case"
],
"no-output-on-prefix": true,
"use-input-property-decorator": true,
"use-output-property-decorator": true,
"use-host-property-decorator": true,
......@@ -99,9 +138,6 @@
"use-life-cycle-interface": true,
"use-pipe-transform-interface": true,
"component-class-suffix": true,
"directive-class-suffix": true,
"no-access-missing-member": true,
"templates-use-public": true,
"invoke-injectable": true
"directive-class-suffix": true
}
}
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.beans;
......@@ -44,6 +44,11 @@ import fi.codecrew.moya.utilities.SearchResult;
@Local
public interface UserBeanLocal {
String getUsersLocale();
boolean setUsersLocale(String locale);
List<EventUser> getUsers();
SearchResult<User> getUsers(SearchQuery search);
......@@ -62,15 +67,14 @@ public interface UserBeanLocal {
boolean resetPassword(User user, String password, String hash);
boolean resetPassword(User user, String password);
boolean resetPassword(User user, String password);
public User getUser(Integer id);
/**
* Search EventUser entity by User entity ID
*
* @param userid
* ID of the User entity to be searcher
*
* @param userid ID of the User entity to be searcher
* @return
*/
EventUser findByUserId(Integer userid, boolean createEventuser);
......@@ -94,13 +98,9 @@ public interface UserBeanLocal {
boolean userExistsByEmail(String email);
/**
*
* @param invitemail
* Target mail
* @param url
* Url to send
* @param membership
* target group membership, if null we generate new one
* @param invitemail Target mail
* @param url Url to send
* @param membership target group membership, if null we generate new one
* @return
*/
boolean invite(String invitemail, String url, GroupMembership membership);
......@@ -114,7 +114,7 @@ public interface UserBeanLocal {
/**
* NOTICE! If the user parameter is a persisted object the returned
* EventUser has a reloaded user, eg changes to the User object are lost!
*
*
* @param user
* @return
*/
......@@ -157,11 +157,11 @@ public interface UserBeanLocal {
* <li>Organisation must be the same.
* <li>All users should have positive or zero balance on source event.
* </ul>
*
*
* @param source
* @param dstEventuser
* @return Saldo transferred. Zero if no transfer was made, Null if there
* was error..
* was error..
*/
BigDecimal transferAccountSaldoFromPreviousEvent(List<User> dstEventuser, LanEvent source);
......@@ -171,7 +171,7 @@ public interface UserBeanLocal {
/**
* Find username by email or username, this is kind of login-helper.
*
*
* @param filter
* @return
*/
......@@ -187,22 +187,23 @@ public interface UserBeanLocal {
EventUser findEventuserByLogin(String username);
/**
* Check that user's password matches.
* @param eventUser
* @param password
* @return true if matches, false if does not, null if user not found.
*/
Boolean checkPassword(EventUser eventUser, String password);
/**
* Check that user's password matches.
*
* @param eventUser
* @param password
* @return true if matches, false if does not, null if user not found.
*/
Boolean checkPassword(EventUser eventUser, String password);
/**
* @return List of moya -surperusers
*/
List<User> findSuperusers();
/**
* There is a textcode type that looks up the code in EventUser object. Do the lookup.
*
* @param code
* @return EventUser with the matching code
*/
......
......@@ -441,7 +441,11 @@ public class BootstrapBean implements BootstrapBeanLocal {
dbUpdates.add(new String[]{
"ALTER TABLE account_events DROP COLUMN delivered_count;"
});
dbUpdates.add(new String[] {
"ALTER TABLE users ADD COLUMN locale TEXT DEFAULT NULL;"
});
}
public BootstrapBean() {
......
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in
* future versions of the Software.
*
*/
package fi.codecrew.moya.beans;
......@@ -180,6 +180,29 @@ public class UserBean implements UserBeanLocal {
private OrgRoleFacade orgRoleFacade;
@Override
public String getUsersLocale() {
if (!permbean.getCurrentUser().isAnonymous()) {
return permbean.getCurrentUser().getUser().getLocale();
}
return null;
}
@Override
public boolean setUsersLocale(String locale) {
if(permbean.getCurrentUser().isAnonymous()) {
return false;
}
// Attach user to database
User u = userFacade.reload(permbean.getCurrentUser().getUser());
u.setLocale(locale);
return true;
}
@Override
@RolesAllowed(UserPermission.S_VIEW_ALL)
public List<EventUser> getUsers() {
......@@ -351,7 +374,7 @@ public class UserBean implements UserBeanLocal {
PrintedCard card = ctbean.checkPrintedCard(user);
if(card != null)
if (card != null)
ctbean.cardImageUpdated(card.getId());
return userimage;
......@@ -498,10 +521,10 @@ public class UserBean implements UserBeanLocal {
logger.info("Initializing password sending: {}, hash: {}", user, hash);
if (hash == null || hash.length() < 20 || user == null || user.getEmail() == null || user.getEmail().length() <= 5) {
logger.info("Not sending email with params {} {}", new Object[] { user, hash });
logger.info("Not sending email with params {} {}", new Object[]{user, hash});
return false;
}
String path = MessageFormat.format(url, new Object[] { user.getId().toString(), hash });
String path = MessageFormat.format(url, new Object[]{user.getId().toString(), hash});
LanEvent event = eventBean.getCurrentEvent();
MailMessage msg = new MailMessage();
......@@ -509,7 +532,7 @@ public class UserBean implements UserBeanLocal {
msg.setSubject(I18n.get("passwordreset.mailSubject", event.getName()));
msg.setMessage(I18n.get("passwordreset.mailBody", path));
logger.info("sending mail! user {} hash {} path {}", new Object[] { user, hash, path });
logger.info("sending mail! user {} hash {} path {}", new Object[]{user, hash, path});
utilbean.sendMail(msg);
user.setConfirmHash(hash);
return true;
......@@ -641,7 +664,7 @@ public class UserBean implements UserBeanLocal {
if (eu == null)
return null;
loggerbean.sendMessage(MoyaEventType.INVITE_ACCEPTED, eu, "Invite accepted by current user ", gm, gm.getUser());
loggerbean.sendMessage(MoyaEventType.INVITE_ACCEPTED, eu, "Invite accepted by current user ", gm, gm.getUser());
gm.setUser(eu);
gm.setInviteAccepted(Calendar.getInstance());
......@@ -944,7 +967,7 @@ public class UserBean implements UserBeanLocal {
@Override
public boolean isUserInRole(EventUser user, Integer roleId) {
Set<Role> roles = localFindUsersRoles(user);
logger.info("CHecking user {} roleid {} from roles {}, roles size{}", new Object[] { user, roleId, roles, roles.size() });
logger.info("CHecking user {} roleid {} from roles {}, roles size{}", new Object[]{user, roleId, roles, roles.size()});
addRecursive(roles, eventBean.getCurrentEvent().getDefaultRole());
for (Role r : roles) {
......@@ -1023,7 +1046,7 @@ public class UserBean implements UserBeanLocal {
dstUser.addAccountevent(dstacc);
accountEventFacade.create(dstacc);
logger.info("Transferred {} credits with price {} for user {} from {} to {}",
new Object[] { count, creditPrice, srcUser.getUser(), srcUser, dstUser });
new Object[]{count, creditPrice, srcUser.getUser(), srcUser, dstUser});
dstTotal = dstTotal.add(dstacc.getTotal());
}
......@@ -1090,15 +1113,13 @@ public class UserBean implements UserBeanLocal {
public String findUsernameByEmailUsername(String filter) {
User user = findUserByEmailUsername(filter);
if(user == null)
if (user == null)
return null;
return user.getLogin();
}
@Override
public User findUserByEmailUsername(String filter) {
User user = userFacade.findByLogin(filter);
......@@ -1159,7 +1180,7 @@ public class UserBean implements UserBeanLocal {
return eventUser;
}
@Override
@RolesAllowed(EventPermission.S_MANAGE_EVENT)
public EventUser getUserByAuthcode(String authcode) {
......
......@@ -104,6 +104,9 @@ public class User extends GenericEntity implements IUser {
@Column(name = "phone")
private String phone = "";
@Column(name = "locale")
private String locale = "";
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "current_image_id", referencedColumnName = "id")
private UserImage currentImage;
......@@ -438,4 +441,11 @@ public class User extends GenericEntity implements IUser {
setMetaStringValue("shirtSize", size);
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
}
package fi.codecrew.moya.rest.v3;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.rest.v3.pojo.LocalePojoV3;
import io.swagger.annotations.Api;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@RequestScoped
@Path("/v3/locale")
@Api(value = "/v3/locale", description = "Locale operations")
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8"})
@Consumes({MediaType.APPLICATION_JSON})
public class LocaleRestViewV3 {
@EJB
private UserBeanLocal userBean;
@EJB
private EventBeanLocal eventBean;
@GET
@Path("/")
public Response getCurrentLocale() {
return Response.ok(LocalePojoV3.create(userBean.getUsersLocale(), eventBean.getCurrentEvent().getOrganiser().getBundleCountry())).build();
}
@POST
@Path("/")
public Response setCurrentLocale(LocalePojoV3 locale) {
if(userBean.setUsersLocale(locale.userLocale)) {
return Response.ok().build();
}
return Response.status(420).build();
}
}
package fi.codecrew.moya.rest.v3.pojo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement()
public class LocalePojoV3 {
public String userLocale = null;
public String eventLocale = null;
public static LocalePojoV3 create(String userLocale, String eventLocale) {
LocalePojoV3 p = new LocalePojoV3();
p.userLocale = userLocale;
p.eventLocale = eventLocale;
return p;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!