├── VERSION ├── app ├── brewdis-ui │ ├── src │ │ ├── assets │ │ │ ├── .gitkeep │ │ │ ├── favicon.ico │ │ │ ├── map-marker.png │ │ │ ├── redislabs.png │ │ │ ├── redis.svg │ │ │ ├── store-low.svg │ │ │ ├── store-medium.svg │ │ │ ├── store-high.svg │ │ │ ├── brewdis.svg │ │ │ └── redislabs.svg │ │ ├── index.d.ts │ │ ├── app │ │ │ ├── catalog │ │ │ │ ├── dialog │ │ │ │ │ ├── dialog.component.css │ │ │ │ │ ├── dialog.component.ts │ │ │ │ │ ├── dialog.component.spec.ts │ │ │ │ │ └── dialog.component.html │ │ │ │ ├── catalog.component.spec.ts │ │ │ │ ├── catalog.component.css │ │ │ │ ├── catalog.component.ts │ │ │ │ └── catalog.component.html │ │ │ ├── availability │ │ │ │ ├── availability.component.css │ │ │ │ ├── availability.component.html │ │ │ │ ├── availability.component.spec.ts │ │ │ │ └── availability.component.ts │ │ │ ├── app.component.ts │ │ │ ├── app.component.css │ │ │ ├── search.service.spec.ts │ │ │ ├── material.module.ts │ │ │ ├── inventory │ │ │ │ ├── inventory.component.spec.ts │ │ │ │ ├── inventory.component.css │ │ │ │ ├── inventory.component.html │ │ │ │ └── inventory.component.ts │ │ │ ├── app-routing.module.ts │ │ │ ├── app.component.spec.ts │ │ │ ├── app.component.html │ │ │ ├── app.module.ts │ │ │ └── search.service.ts │ │ ├── environments │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── favicon.ico │ │ ├── styles.css │ │ ├── index.html │ │ ├── main.ts │ │ ├── test.ts │ │ ├── theme.scss │ │ └── polyfills.ts │ ├── start-ng.sh │ ├── gradle.properties │ ├── proxy.conf.json │ ├── brewdis-ui.gradle │ ├── e2e │ │ ├── tsconfig.json │ │ ├── src │ │ │ ├── app.po.ts │ │ │ └── app.e2e-spec.ts │ │ └── protractor.conf.js │ ├── .editorconfig │ ├── tsconfig.app.json │ ├── tsconfig.spec.json │ ├── browserslist │ ├── tsconfig.json │ ├── .gitignore │ ├── README.md │ ├── karma.conf.js │ ├── package.json │ ├── tslint.json │ └── angular.json └── brewdis-api │ ├── gradle.properties │ ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── redislabs │ │ │ └── demo │ │ │ └── brewdis │ │ │ ├── web │ │ │ ├── Style.java │ │ │ ├── Category.java │ │ │ ├── ResultsPage.java │ │ │ ├── BrewerySuggestion.java │ │ │ └── Query.java │ │ │ ├── BrewdisApplication.java │ │ │ ├── WebSocketConfig.java │ │ │ ├── BrewdisField.java │ │ │ ├── InventoryDemand.java │ │ │ ├── WebSocketPublisher.java │ │ │ ├── Config.java │ │ │ ├── InventorySupply.java │ │ │ ├── WebController.java │ │ │ ├── InventoryManager.java │ │ │ └── DataLoader.java │ │ └── resources │ │ ├── banner.txt │ │ ├── english_stopwords.txt │ │ └── application.properties │ └── brewdis-api.gradle ├── data ├── .gitattributes ├── stores.numbers ├── README.adoc ├── brewerydb.tgz ├── jq-process.sh └── load.sh ├── brewdis.png ├── lombok.config ├── app_preview_image.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .dockerignore ├── .gitignore ├── gradle.properties ├── Dockerfile ├── docker-compose.yml ├── marketplace.json ├── .github └── workflows │ ├── build.yml │ ├── early-access.yml │ └── release.yml ├── jreleaser.yml ├── settings.gradle ├── gradlew.bat ├── README.md └── gradlew /VERSION: -------------------------------------------------------------------------------- 1 | 0.2.1-SNAPSHOT 2 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'googlemaps'; -------------------------------------------------------------------------------- /app/brewdis-ui/start-ng.sh: -------------------------------------------------------------------------------- 1 | ng serve --proxy-config proxy.conf.json -------------------------------------------------------------------------------- /data/.gitattributes: -------------------------------------------------------------------------------- 1 | *.tgz filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /app/brewdis-api/gradle.properties: -------------------------------------------------------------------------------- 1 | project_description = Brewdis API 2 | -------------------------------------------------------------------------------- /app/brewdis-ui/gradle.properties: -------------------------------------------------------------------------------- 1 | project_description = Brewdis UI 2 | -------------------------------------------------------------------------------- /brewdis.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/brewdis.png -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | config.stopBubbling = true 2 | lombok.addLombokGeneratedAnnotation = true 3 | -------------------------------------------------------------------------------- /app_preview_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/app_preview_image.png -------------------------------------------------------------------------------- /data/stores.numbers: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/data/stores.numbers -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/dialog/dialog.component.css: -------------------------------------------------------------------------------- 1 | .product-detail { 2 | margin-bottom: 1em; 3 | } -------------------------------------------------------------------------------- /data/README.adoc: -------------------------------------------------------------------------------- 1 | = Retail Data Load 2 | 3 | == Products 4 | 5 | `jq '[.[] | . + {"sku": .id} | del(.id)]'` 6 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/app/brewdis-ui/src/favicon.ico -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/app/brewdis-ui/src/assets/favicon.ico -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | data 2 | docs 3 | brewdis-ui/node_modules 4 | brewdis-ui/dist 5 | brewdis-ui/build 6 | brewdis-api/build 7 | .git 8 | .gitignore -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | *.log 4 | /data/products.json.gz 5 | /data/products.json 6 | /data/brewerydb/all/ 7 | .gradle 8 | build 9 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/map-marker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/app/brewdis-ui/src/assets/map-marker.png -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/redislabs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redis-developer/brewdis/master/app/brewdis-ui/src/assets/redislabs.png -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/availability/availability.component.css: -------------------------------------------------------------------------------- 1 | agm-map { 2 | height: 640px; 3 | } 4 | 5 | .marker-info { 6 | color: black; 7 | } -------------------------------------------------------------------------------- /data/brewerydb.tgz: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:7e7041b9563913bd2d0a97943cb9837f88e78ee09f1de73a8607ecb16603cb1f 3 | size 78125362 4 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | group=com.redislabs 2 | kordampPluginVersion=0.46.0 3 | redislabsBuildVersion=0.1.0 4 | protobufVersion=3.14.0 5 | googleHttpVersion=1.38.0 6 | -------------------------------------------------------------------------------- /app/brewdis-ui/proxy.conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "/api": { 3 | "target": "http://localhost:8080/api", 4 | "secure": false, 5 | "changeOrigin": true, 6 | "pathRewrite": {"^/api" : ""} 7 | } 8 | } -------------------------------------------------------------------------------- /app/brewdis-ui/brewdis-ui.gradle: -------------------------------------------------------------------------------- 1 | node { 2 | version = '13.6.0' 3 | download = true 4 | } 5 | 6 | jar.dependsOn 'npm_run_build' 7 | 8 | jar { 9 | from 'dist/brewdis-ui' into 'static' 10 | } 11 | -------------------------------------------------------------------------------- /data/jq-process.sh: -------------------------------------------------------------------------------- 1 | cat beers.json | jq '.[] | select(.labels != null) | select(.labels.contentAwareLarge != null) | { abv, category: .style.category.name, description, id, label: .labels.contentAwareLarge, name, organic: .isOrganic, style: .style.name, styleId}' -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'Brewdis'; 10 | } 11 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/web/Style.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis.web; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Builder 7 | @Data 8 | public class Style { 9 | 10 | private String id; 11 | private String name; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /app/brewdis-ui/e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/web/Category.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis.web; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Builder 7 | @Data 8 | public class Category { 9 | 10 | private String id; 11 | private String name; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /app/brewdis-ui/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | @import "~@angular/material/prebuilt-themes/purple-green.css"; 3 | @import 'https://fonts.googleapis.com/icon?family=Material+Icons'; 4 | 5 | body { 6 | font-family: Roboto, "Helvetica Neue", sans-serif; 7 | margin: 0; 8 | } -------------------------------------------------------------------------------- /app/brewdis-ui/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /app/brewdis-ui/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ], 14 | "angularCompilerOptions": { 15 | "enableIvy": true 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Brewdis 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/web/ResultsPage.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis.web; 2 | 3 | import com.redislabs.mesclun.search.SearchResults; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class ResultsPage { 8 | private long count; 9 | private SearchResults results; 10 | private float duration; 11 | private long pageIndex; 12 | private long pageSize; 13 | } 14 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app.component.css: -------------------------------------------------------------------------------- 1 | .menu-spacer { 2 | flex: 1 1 auto; 3 | } 4 | 5 | .main { 6 | height: 3em; 7 | } 8 | 9 | .logo { 10 | height: 100%; 11 | margin-right: 5px; 12 | } 13 | 14 | .home { 15 | font-size: 2em; 16 | } 17 | 18 | .redislabs { 19 | height: 3em; 20 | } 21 | 22 | .link { 23 | font-size: 1em; 24 | } 25 | 26 | mat-toolbar-row { 27 | margin-top: 3px; 28 | margin-bottom: 3px; 29 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:13-jdk-slim AS build 2 | WORKDIR /app 3 | COPY . /app 4 | RUN ./gradlew build --no-daemon 5 | 6 | #### Stage 2: A minimal docker image with command to run the app 7 | FROM openjdk:13-jdk-slim 8 | 9 | EXPOSE 8080 10 | 11 | RUN mkdir /app 12 | 13 | COPY --from=build /app/app/brewdis-api/build/libs/*.jar /app/brewdis.jar 14 | 15 | ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/brewdis.jar"] 16 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/dialog/dialog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Inject } from '@angular/core'; 2 | import { MAT_DIALOG_DATA } from '@angular/material/dialog'; 3 | 4 | @Component({ 5 | selector: 'app-dialog', 6 | templateUrl: './dialog.component.html', 7 | styleUrls: ['./dialog.component.css'] 8 | }) 9 | export class DialogComponent { 10 | 11 | constructor(@Inject(MAT_DIALOG_DATA) public product: any) { } 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /app/brewdis-ui/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ], 18 | "angularCompilerOptions": { 19 | "enableIvy": true 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | 3 | services: 4 | server: 5 | build: 6 | context: ./ 7 | dockerfile: Dockerfile 8 | restart: always 9 | ports: 10 | - "80:8080" 11 | depends_on: 12 | - redisearch 13 | environment: 14 | SPRING_REDIS_HOST: redisearch 15 | STOMP_PORT: 80 16 | 17 | redisearch: 18 | image: redislabs/redisearch 19 | restart: always 20 | ports: 21 | - "6379:6379" 22 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/search.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing'; 2 | 3 | import { SearchService } from './search.service'; 4 | 5 | describe('SearchService', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [SearchService] 9 | }); 10 | }); 11 | 12 | it('should be created', inject([SearchService], (service: SearchService) => { 13 | expect(service).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /app/brewdis-ui/browserslist: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/material.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { 4 | MatSidenavModule, 5 | MatToolbarModule, 6 | MatIconModule, 7 | MatListModule, 8 | } from '@angular/material'; 9 | 10 | @NgModule({ 11 | imports: [MatSidenavModule, 12 | MatToolbarModule, 13 | MatIconModule, 14 | MatListModule], 15 | exports: [MatSidenavModule, 16 | MatToolbarModule, 17 | MatIconModule, 18 | MatListModule] 19 | }) 20 | export class MaterialModule { } 21 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/web/BrewerySuggestion.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis.web; 2 | 3 | import com.redislabs.mesclun.search.SearchResults; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | 7 | @Data 8 | public class BrewerySuggestion { 9 | private String id; 10 | private String name; 11 | private String icon; 12 | 13 | 14 | @Data 15 | public static class Payload { 16 | 17 | private String id; 18 | private String icon; 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/web/Query.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis.web; 2 | 3 | import com.redislabs.mesclun.search.SearchResults; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class Query { 8 | private String query = "*"; 9 | private String sortByField; 10 | private String sortByDirection = "Ascending"; 11 | private long pageIndex = 0; 12 | private long pageSize = 100; 13 | 14 | public long getOffset() { 15 | return pageIndex * pageSize; 16 | } 17 | 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/availability/availability.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 |

{{store.storeDescription}}

7 |
8 |
9 |
-------------------------------------------------------------------------------- /app/brewdis-ui/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ] 21 | }, 22 | "angularCompilerOptions": { 23 | "fullTemplateTypeCheck": true, 24 | "strictInjectionParameters": true 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | ${AnsiColor.BRIGHT_RED} 2 | 3 | 888888b. 888 d8b 4 | 888 "88b 888 Y8P 5 | 888 .88P 888 6 | 8888888K. 888d888 .d88b. 888 888 888 .d88888 888 .d8888b 7 | 888 "Y88b 888P" d8P Y8b 888 888 888 d88" 888 888 88K 8 | 888 888 888 88888888 888 888 888 888 888 888 "Y8888b. 9 | 888 d88P 888 Y8b. Y88b 888 d88P Y88b 888 888 X88 10 | 8888888P" 888 "Y8888 "Y8888888P" "Y88888 888 88888P' 11 | ${AnsiColor.DEFAULT} -------------------------------------------------------------------------------- /app/brewdis-ui/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /app/brewdis-ui/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('client app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/catalog.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { CatalogComponent } from './catalog.component'; 4 | 5 | describe('CatalogComponent', () => { 6 | let component: CatalogComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ CatalogComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(CatalogComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/dialog/dialog.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { DialogComponent } from './dialog.component'; 4 | 5 | describe('DialogComponent', () => { 6 | let component: DialogComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ DialogComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(DialogComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/inventory/inventory.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { InventoryComponent } from './inventory.component'; 4 | 5 | describe('InventoryComponent', () => { 6 | let component: InventoryComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ InventoryComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(InventoryComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/availability/availability.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { AvailabilityComponent } from './availability.component'; 4 | 5 | describe('AvailabilityComponent', () => { 6 | let component: AvailabilityComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ AvailabilityComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(AvailabilityComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/BrewdisApplication.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.ApplicationArguments; 5 | import org.springframework.boot.ApplicationRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.scheduling.annotation.EnableScheduling; 9 | 10 | @SpringBootApplication 11 | @EnableScheduling 12 | public class BrewdisApplication implements ApplicationRunner { 13 | 14 | @Autowired 15 | private DataLoader loader; 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(BrewdisApplication.class, args); 19 | } 20 | 21 | @Override 22 | public void run(ApplicationArguments args) throws Exception { 23 | loader.execute(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /app/brewdis-api/brewdis-api.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation 'org.springframework.boot:spring-boot-starter-web' 3 | implementation 'org.springframework.boot:spring-boot-starter-websocket' 4 | implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive' 5 | implementation 'com.redislabs:spring-redis-modules:1.3.2' 6 | implementation ('com.redislabs:riot-core:2.11.5') { 7 | exclude group: 'org.slf4j', module: 'slf4j-jdk14' 8 | } 9 | implementation ('com.redislabs:riot-file:2.11.5') { 10 | exclude group: 'org.slf4j', module: 'slf4j-jdk14' 11 | } 12 | compileOnly 'org.projectlombok:lombok' 13 | annotationProcessor 'org.projectlombok:lombok' 14 | implementation project(':brewdis-ui') 15 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 16 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { CatalogComponent } from './catalog/catalog.component'; 4 | import { InventoryComponent } from './inventory/inventory.component'; 5 | import { AvailabilityComponent } from './availability/availability.component'; 6 | 7 | const routes: Routes = [ 8 | {path: '', pathMatch: 'full', redirectTo: 'catalog'}, 9 | {path: 'catalog' , component: CatalogComponent}, 10 | {path: 'inventory', component: InventoryComponent}, 11 | {path: 'inventory/:store', component: InventoryComponent}, 12 | {path: 'availability', component: AvailabilityComponent}, 13 | {path: 'availability/:sku', component: AvailabilityComponent} 14 | ]; 15 | 16 | @NgModule({ 17 | imports: [RouterModule.forRoot(routes)], 18 | exports: [RouterModule] 19 | }) 20 | export class AppRoutingModule { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /app/brewdis-ui/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /build 6 | /bin 7 | /tmp 8 | /out-tsc 9 | /ui-src 10 | # Only exists if Bazel was run 11 | /bazel-out 12 | 13 | # dependencies 14 | /node_modules 15 | 16 | # profiling files 17 | chrome-profiler-events*.json 18 | speed-measure-plugin*.json 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json 35 | .history/* 36 | brewdis.code-workspace 37 | 38 | # misc 39 | /.sass-cache 40 | /connect.lock 41 | /coverage 42 | /libpeerconnection.log 43 | npm-debug.log 44 | yarn-error.log 45 | testem.log 46 | /typings 47 | 48 | # System Files 49 | .DS_Store 50 | Thumbs.db 51 | /target/ 52 | /node/ 53 | /.gradle/ 54 | -------------------------------------------------------------------------------- /app/brewdis-ui/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | 'browserName': 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/inventory/inventory.component.css: -------------------------------------------------------------------------------- 1 | table { 2 | margin-left: auto; 3 | margin-right: auto; 4 | width: 100%; 5 | } 6 | 7 | ::ng-deep .mat-sort-header-container { 8 | display:flex; 9 | justify-content:center; 10 | } 11 | 12 | table td { 13 | vertical-align: middle; 14 | position: relative; 15 | } 16 | 17 | table td img { 18 | width: 50px; 19 | padding-right: 5px; 20 | vertical-align: middle; 21 | display: inline-block; 22 | } 23 | 24 | table td p { 25 | display: inline-block; 26 | vertical-align: middle 27 | } 28 | 29 | .align-center { 30 | text-align: center; 31 | } 32 | 33 | .align-left { 34 | text-align: left; 35 | } 36 | 37 | .atp { 38 | color: azure; 39 | } 40 | 41 | .low { 42 | background-color: #d32f2f; 43 | } 44 | 45 | .medium { 46 | background-color: #f9a825; 47 | } 48 | 49 | .high { 50 | background-color: #388e3c; 51 | } 52 | 53 | .recent { 54 | /* border: 5px solid #fdd835; */ 55 | background-color: papayawhip; 56 | } -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | describe('AppComponent', () => { 4 | beforeEach(async(() => { 5 | TestBed.configureTestingModule({ 6 | declarations: [ 7 | AppComponent 8 | ], 9 | }).compileComponents(); 10 | })); 11 | it('should create the app', async(() => { 12 | const fixture = TestBed.createComponent(AppComponent); 13 | const app = fixture.debugElement.componentInstance; 14 | expect(app).toBeTruthy(); 15 | })); 16 | it(`should have as title 'client'`, async(() => { 17 | const fixture = TestBed.createComponent(AppComponent); 18 | const app = fixture.debugElement.componentInstance; 19 | expect(app.title).toEqual('client'); 20 | })); 21 | it('should render title in a h1 tag', async(() => { 22 | const fixture = TestBed.createComponent(AppComponent); 23 | fixture.detectChanges(); 24 | const compiled = fixture.debugElement.nativeElement; 25 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to client!'); 26 | })); 27 | }); 28 | -------------------------------------------------------------------------------- /app/brewdis-ui/README.md: -------------------------------------------------------------------------------- 1 | # Client 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.8. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /marketplace.json: -------------------------------------------------------------------------------- 1 | { 2 | "app_name": "Brewdis", 3 | "description": "Real-time Brewery Inventory built using Redis ", 4 | "type": "Building Block", 5 | "contributed_by": "Redis", 6 | "repo_url": "https://github.com/redis-developer/brewdis", 7 | "preview_image_url": "https://raw.githubusercontent.com/redis-developer/brewdis/master/app_preview_image.png", 8 | "download_url": "https://github.com/redis-developer/brewdis/archive/refs/heads/master.zip", 9 | "hosted_url": "", 10 | "quick_deploy": "false", 11 | "deploy_buttons": [], 12 | "language": [ 13 | "Java" 14 | ], 15 | "redis_commands": [ 16 | "FT.CREATE", 17 | "HSET", 18 | "FT.SEARCH" 19 | ], 20 | "redis_use_cases": [ 21 | "Caching" 22 | ], 23 | "redis_features": [ 24 | "Search and Query" 25 | ], 26 | "app_image_urls": [ 27 | "https://raw.githubusercontent.com/redis-developer/brewdis/master/brewdis.png" 28 | ], 29 | "youtube_url": "", 30 | "special_tags": [ 31 | "Hackathon" 32 | ], 33 | "verticals": [ 34 | "Retail" 35 | ], 36 | "markdown": "https://raw.githubusercontent.com/redis-developer/brewdis/master/README.md" 37 | } -------------------------------------------------------------------------------- /app/brewdis-ui/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/client'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 21 |
22 | 23 | Redis Labs 24 | 25 |
26 |
27 |
28 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 9 | 10 | @Configuration 11 | @EnableWebSocketMessageBroker 12 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 13 | 14 | @Autowired 15 | private Config config; 16 | 17 | @Override 18 | public void configureMessageBroker(MessageBrokerRegistry registry) { 19 | registry.enableSimpleBroker(config.getStomp().getDestinationPrefix()); 20 | registry.setApplicationDestinationPrefixes("/app"); 21 | } 22 | 23 | @Override 24 | public void registerStompEndpoints(StompEndpointRegistry registry) { 25 | registry.addEndpoint(config.getStomp().getEndpoint()).setAllowedOrigins("*"); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/availability/availability.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute } from '@angular/router'; 3 | import { SearchService } from '../search.service'; 4 | 5 | @Component({ 6 | selector: 'app-availability', 7 | templateUrl: './availability.component.html', 8 | styleUrls: ['./availability.component.css'] 9 | }) 10 | export class AvailabilityComponent implements OnInit { 11 | 12 | title = 'Product Availability'; 13 | lat = 34.0030; 14 | lng = -118.4298; 15 | stores: []; 16 | 17 | constructor(private searchService: SearchService, private route: ActivatedRoute) { } 18 | 19 | ngOnInit() { 20 | let sku: string; 21 | this.route.paramMap.subscribe(params => { 22 | sku = params.get('sku'); 23 | }); 24 | if (navigator.geolocation) { 25 | navigator.geolocation.getCurrentPosition((position) => { 26 | this.lat = position.coords.latitude; 27 | this.lng = position.coords.longitude; 28 | this.searchService.availability(sku, this.lng, this.lat).subscribe((data: []) => this.stores = data); 29 | }); 30 | } else { 31 | alert('Geolocation is not supported by this browser.'); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/theme.scss: -------------------------------------------------------------------------------- 1 | @import '~@angular/material/theming'; 2 | // Plus imports for other components in your app. 3 | 4 | // Include the common styles for Angular Material. We include this here so that you only 5 | // have to load a single css file for Angular Material in your app. 6 | // Be sure that you only ever include this mixin once! 7 | @include mat-core(); 8 | 9 | // Define the palettes for your theme using the Material Design palettes available in palette.scss 10 | // (imported above). For each palette, you can optionally specify a default, lighter, and darker 11 | // hue. Available color palettes: https://material.io/design/color/ 12 | 13 | $brewdis-app-primary: mat-palette($mat-cyan, 900, 500, 100); 14 | $brewdis-app-accent: mat-palette($mat-orange, A200, A100, A400); 15 | 16 | // The warn palette is optional (defaults to red). 17 | $brewdis-app-warn: mat-palette($mat-orange); 18 | 19 | // Create the theme object (a Sass map containing all of the palettes). 20 | $brewdis-app-theme: mat-light-theme($brewdis-app-primary, $brewdis-app-accent, $brewdis-app-warn); 21 | 22 | // Include theme styles for core and each component used in your app. 23 | // Alternatively, you can import and @include the theme mixins for each component 24 | // that you are using. 25 | @include angular-material-theme($brewdis-app-theme); -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | build: 8 | name: Build 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | os: [ ubuntu-latest, macos-latest, windows-latest ] 13 | runs-on: ${{ matrix.os }} 14 | if: startsWith(github.event.head_commit.message, 'Releasing version') != true 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - name: Set up Java 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 11 23 | 24 | - uses: actions/cache@v2 25 | with: 26 | path: ~/.gradle/caches 27 | key: ${{ runner.os }}-gradle-cache-${{ hashFiles('**/*.gradle') }}-${{ hashFiles('**/gradle.properties') }} 28 | restore-keys: | 29 | ${{ runner.os }}-gradle- 30 | 31 | - uses: actions/cache@v2 32 | with: 33 | path: ~/.gradle/wrapper 34 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradlew') }} 35 | restore-keys: | 36 | ${{ runner.os }}-gradlew- 37 | 38 | - name: Build 39 | run: ./gradlew build -S 40 | 41 | - name: Show Reports 42 | uses: actions/upload-artifact@v1 43 | if: failure() 44 | with: 45 | name: reports-${{ runner.os }} 46 | path: build/ 47 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/resources/english_stopwords.txt: -------------------------------------------------------------------------------- 1 | i 2 | me 3 | my 4 | myself 5 | we 6 | our 7 | ours 8 | ourselves 9 | you 10 | your 11 | yours 12 | yourself 13 | yourselves 14 | he 15 | him 16 | his 17 | himself 18 | she 19 | her 20 | hers 21 | herself 22 | it 23 | its 24 | itself 25 | they 26 | them 27 | their 28 | theirs 29 | themselves 30 | what 31 | which 32 | who 33 | whom 34 | this 35 | that 36 | these 37 | those 38 | am 39 | is 40 | are 41 | was 42 | were 43 | be 44 | been 45 | being 46 | have 47 | has 48 | had 49 | having 50 | do 51 | does 52 | did 53 | doing 54 | a 55 | an 56 | the 57 | and 58 | but 59 | if 60 | or 61 | because 62 | as 63 | until 64 | while 65 | of 66 | at 67 | by 68 | for 69 | with 70 | about 71 | against 72 | between 73 | into 74 | through 75 | during 76 | before 77 | after 78 | above 79 | below 80 | to 81 | from 82 | up 83 | down 84 | in 85 | out 86 | on 87 | off 88 | over 89 | under 90 | again 91 | further 92 | then 93 | once 94 | here 95 | there 96 | when 97 | where 98 | why 99 | how 100 | all 101 | any 102 | both 103 | each 104 | few 105 | more 106 | most 107 | other 108 | some 109 | such 110 | no 111 | nor 112 | not 113 | only 114 | own 115 | same 116 | so 117 | than 118 | too 119 | very 120 | s 121 | t 122 | can 123 | will 124 | just 125 | don 126 | should 127 | now 128 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/catalog.component.css: -------------------------------------------------------------------------------- 1 | .main-panel { 2 | margin: 20px; 3 | } 4 | 5 | .search-panel { 6 | display: flex; 7 | flex-direction: column; 8 | justify-content: center; 9 | margin-bottom: 10px; 10 | } 11 | 12 | .search-bar { 13 | display: flex; 14 | flex-direction: row; 15 | } 16 | 17 | .query { 18 | flex-grow: 1; 19 | } 20 | 21 | .submit { 22 | flex-shrink: 1; 23 | } 24 | 25 | .filter-button { 26 | flex-shrink: 1; 27 | } 28 | 29 | .filter-panel { 30 | display: flex; 31 | flex-direction: row; 32 | justify-content: flex-end; 33 | } 34 | 35 | .category-panel { 36 | display: flex; 37 | flex-direction: column; 38 | flex-basis: 20%; 39 | } 40 | 41 | .abv-panel { 42 | display: flex; 43 | flex-direction: column; 44 | } 45 | 46 | .brewery-panel { 47 | display: flex; 48 | flex-direction: column; 49 | flex-basis: 30%; 50 | } 51 | 52 | .brewery-img { 53 | vertical-align: middle; 54 | margin-right: 8px; 55 | } 56 | 57 | .sort-panel { 58 | display: flex; 59 | flex-direction: column; 60 | } 61 | 62 | .results-panel { 63 | background: #fafafa; 64 | } 65 | 66 | .mat-paginator { 67 | background: #fafafa; 68 | } 69 | 70 | mat-card { 71 | margin-bottom: 10px; 72 | max-width: 400px; 73 | } 74 | 75 | .mat-card-title { 76 | font-size: .9em; 77 | } 78 | 79 | .mat-card-actions { 80 | justify-content: space-between; 81 | } 82 | 83 | .mr-10 { 84 | margin-right: 10px; 85 | } 86 | 87 | .ml-10 { 88 | margin-left: 10px; 89 | } -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/BrewdisField.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | public class BrewdisField { 4 | 5 | public static final String ALLOCATED = "allocated"; 6 | public static final String AVAILABLE_TO_PROMISE = "availableToPromise"; 7 | public static final String BREWERY_ICON = "breweryIcon"; 8 | public static final String BREWERY_ID = "brewery"; 9 | public static final String BREWERY_NAME = "breweryName"; 10 | public static final String CATEGORY_ID = "category"; 11 | public static final String CATEGORY_NAME = "categoryName"; 12 | public static final String COUNT = "count"; 13 | public static final String DELTA = "delta"; 14 | public static final String EPOCH = "epoch"; 15 | public static final String FOOD_PAIRINGS = "foodPairings"; 16 | public static final String PRODUCT_LABEL = "label"; 17 | public static final String LEVEL = "level"; 18 | public static final String LOCATION = "location"; 19 | public static final String ON_HAND = "onHand"; 20 | public static final String PRODUCT_DESCRIPTION = "description"; 21 | public static final String PRODUCT_ID = "sku"; 22 | public static final String PRODUCT_NAME = "name"; 23 | public static final String RESERVED = "reserved"; 24 | public static final String STORE_ID = "store"; 25 | public static final String STYLE_ID = "style"; 26 | public static final String STYLE_NAME = "styleName"; 27 | public static final String TIME = "time"; 28 | public static final String VIRTUAL_HOLD = "virtualHold"; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/dialog/dialog.component.html: -------------------------------------------------------------------------------- 1 |

2 |
3 |
4 | ID: 5 | 6 | Brewery: 7 | 8 | Category: 9 | 10 | Style: 11 |
12 |
13 | ABV: {{product.abv}}% 14 | 15 | IBU: {{product.ibu}} 16 | 17 | Organic: {{product.isOrganic}} 18 |
19 |
20 | Availability: {{product['available.description']}} 21 |
22 |
23 | Serving Temperature: {{product.servingTemperatureDisplay}} 24 |
25 |
26 | Food Pairings: 27 |
28 |
29 | Description: 30 |
31 |
-------------------------------------------------------------------------------- /app/brewdis-ui/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "brewdis-ui", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve --proxy-config proxy.conf.json", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@agm/core": "^1.0.0", 15 | "@angular/animations": "~8.2.14", 16 | "@angular/cdk": "^8.2.3", 17 | "@angular/common": "~8.2.14", 18 | "@angular/compiler": "~8.2.14", 19 | "@angular/core": "~8.2.14", 20 | "@angular/flex-layout": "^8.0.0-beta.27", 21 | "@angular/forms": "~8.2.14", 22 | "@angular/material": "^8.2.3", 23 | "@angular/platform-browser": "~8.2.14", 24 | "@angular/platform-browser-dynamic": "~8.2.14", 25 | "@angular/router": "~8.2.14", 26 | "@stomp/ng2-stompjs": "^7.2.0", 27 | "@types/googlemaps": "^3.37.7", 28 | "hammerjs": "^2.0.8", 29 | "rxjs": "~6.5.4", 30 | "tslib": "^1.10.0", 31 | "zone.js": "~0.9.1" 32 | }, 33 | "devDependencies": { 34 | "@angular-devkit/build-angular": "~0.803.24", 35 | "@angular/cli": "~8.3.24", 36 | "@angular/compiler-cli": "~8.2.14", 37 | "@angular/language-service": "~8.2.14", 38 | "@types/node": "~8.9.4", 39 | "@types/jasmine": "~3.3.8", 40 | "@types/jasminewd2": "~2.0.3", 41 | "codelyzer": "^5.0.0", 42 | "jasmine-core": "~3.4.0", 43 | "jasmine-spec-reporter": "~4.2.1", 44 | "karma": "~4.1.0", 45 | "karma-chrome-launcher": "~2.2.0", 46 | "karma-coverage-istanbul-reporter": "~2.0.1", 47 | "karma-jasmine": "~2.0.1", 48 | "karma-jasmine-html-reporter": "^1.4.0", 49 | "protractor": "~5.4.0", 50 | "ts-node": "~7.0.0", 51 | "tslint": "~5.15.0", 52 | "typescript": "~3.5.3" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /jreleaser.yml: -------------------------------------------------------------------------------- 1 | project: 2 | name: brewdis 3 | description: Brewdis Demo 4 | longDescription: Real-time inventory demo using Redis 5 | website: https://github.com/redis-developer/brewdis 6 | authors: 7 | - Julien Ruaux 8 | license: Apache-2.0 9 | java: 10 | groupId: com.redislabs 11 | version: 8 12 | multiProject: true 13 | extraProperties: 14 | inceptionYear: 2020 15 | 16 | release: 17 | github: 18 | branch: master 19 | username: jruaux 20 | overwrite: true 21 | changelog: 22 | sort: DESC 23 | formatted: ALWAYS 24 | format: '- {{commitShortHash}} {{commitTitle}}' 25 | labelers: 26 | - label: 'feature' 27 | title: 'Resolves #' 28 | body: 'Resolves #' 29 | - label: 'issue' 30 | title: 'Fixes #' 31 | body: 'Fixes #' 32 | - label: 'issue' 33 | title: 'Relates to #' 34 | body: 'Relates to #' 35 | - label: 'task' 36 | title: '[chore]' 37 | - label: 'dependencies' 38 | title: '[deps]' 39 | categories: 40 | - title: '🚀 Features' 41 | labels: 42 | - 'feature' 43 | - title: '✅ Issues' 44 | labels: 45 | - 'issue' 46 | - title: '🧰 Tasks' 47 | labels: 48 | - 'task' 49 | - title: '⚙️ Dependencies' 50 | labels: 51 | - 'dependencies' 52 | replacers: 53 | - search: '\[chore\] ' 54 | replace: '' 55 | - search: '\[deps\] ' 56 | replace: '' 57 | 58 | distributions: 59 | brewdis: 60 | type: SINGLE_JAR 61 | artifacts: 62 | - path: app/brewdis-api/build/libs/brewdis-api-{{projectVersion}}.jar 63 | docker: 64 | active: never 65 | registries: 66 | - serverName: DEFAULT 67 | username: jruaux 68 | labels: 69 | 'org.opencontainers.image.title': 'brewdis' 70 | 71 | files: 72 | artifacts: 73 | - path: VERSION 74 | -------------------------------------------------------------------------------- /data/load.sh: -------------------------------------------------------------------------------- 1 | redis-cli flushall 2 | echo "Creating stores index" 3 | redis-cli FT.CREATE stores SCHEMA \ 4 | store TAG SORTABLE \ 5 | description TEXT \ 6 | market TAG SORTABLE \ 7 | parent TAG SORTABLE \ 8 | address TEXT \ 9 | city TEXT SORTABLE \ 10 | country TAG SORTABLE \ 11 | inventoryAvailableToSell TAG SORTABLE \ 12 | isDefault TAG SORTABLE \ 13 | preferred TAG SORTABLE \ 14 | latitude NUMERIC SORTABLE \ 15 | location GEO \ 16 | longitude NUMERIC SORTABLE \ 17 | rollupInventory TAG SORTABLE \ 18 | state TAG SORTABLE \ 19 | type TAG SORTABLE \ 20 | postalCode TAG SORTABLE 21 | riot file-import --file stores.csv --header --proc "location=#geo(longitude,latitude)" --index stores --keyspace store --keys store 22 | 23 | echo "Creating products index" 24 | redis-cli FT.CREATE products SCHEMA \ 25 | sku TAG SORTABLE \ 26 | name TEXT \ 27 | description TEXT PHONETIC dm:en \ 28 | category TAG SORTABLE \ 29 | categoryName TEXT \ 30 | style TAG SORTABLE \ 31 | styleName TEXT \ 32 | brewery TAG SORTABLE \ 33 | breweryName TEXT \ 34 | isOrganic TAG SORTABLE \ 35 | abv NUMERIC SORTABLE \ 36 | label TAG SORTABLE \ 37 | ibu NUMERIC SORTABLE 38 | riot file-import --file products.json.gz --proc "sku=id" "label=containsKey('labels')" "category=style.category.id" "categoryName=style.category.name" "styleName=style.shortName" "style=style.id" "brewery=containsKey('breweries')?breweries[0].id:null" "breweryName=containsKey('breweries')?breweries[0].nameShortDisplay:null" "breweryIcon=containsKey('breweries')?breweries[0].containsKey('images')?breweries[0].get('images').get('icon'):null:null" --index products --keyspace product --keys sku 39 | 40 | echo "Creating inventory index" 41 | redis-cli FT.CREATE inventory SCHEMA \ 42 | id TAG SORTABLE \ 43 | store TAG SORTABLE \ 44 | sku TAG SORTABLE \ 45 | location GEO \ 46 | availableToPromise NUMERIC SORTABLE \ 47 | onHand NUMERIC SORTABLE \ 48 | allocated NUMERIC SORTABLE \ 49 | reserved NUMERIC SORTABLE \ 50 | virtualHold NUMERIC SORTABLE \ 51 | epoch NUMERIC SORTABLE -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/InventoryDemand.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import com.redislabs.mesclun.RedisModulesCommands; 4 | import com.redislabs.mesclun.StatefulRedisModulesConnection; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.beans.factory.InitializingBean; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.scheduling.annotation.Scheduled; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.PrimitiveIterator.OfInt; 14 | import java.util.Random; 15 | 16 | import static com.redislabs.demo.brewdis.BrewdisField.*; 17 | 18 | @Component 19 | @Slf4j 20 | public class InventoryDemand implements InitializingBean { 21 | 22 | @Autowired 23 | private Config config; 24 | @Autowired 25 | private StatefulRedisModulesConnection connection; 26 | private OfInt delta; 27 | 28 | @Override 29 | public void afterPropertiesSet() { 30 | this.delta = new Random().ints(config.getInventory().getGenerator().getDeltaMin(), config.getInventory().getGenerator().getDeltaMax()).iterator(); 31 | } 32 | 33 | @Scheduled(fixedRateString = "${inventory.generator.rate}") 34 | public void generate() { 35 | RedisModulesCommands commands = connection.sync(); 36 | for (String session : commands.smembers("sessions")) { 37 | String store = commands.srandmember("session:stores:" + session); 38 | if (store == null) { 39 | continue; 40 | } 41 | String sku = commands.srandmember("session:skus:" + session); 42 | if (sku == null) { 43 | continue; 44 | } 45 | Map update = new HashMap<>(); 46 | update.put(STORE_ID, store); 47 | update.put(PRODUCT_ID, sku); 48 | update.put(ALLOCATED, String.valueOf(delta.nextInt())); 49 | commands.xadd(config.getInventory().getUpdateStream(), update); 50 | } 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | gradlePluginPortal() 4 | mavenCentral() 5 | mavenLocal() 6 | } 7 | dependencies { 8 | classpath "com.redislabs.gradle:redislabs-parentbuild:$redislabsBuildVersion" 9 | classpath "org.kordamp.gradle:java-project-gradle-plugin:$kordampPluginVersion" 10 | classpath "org.kordamp.gradle:guide-gradle-plugin:$kordampPluginVersion" 11 | classpath "org.springframework.boot:spring-boot-gradle-plugin:2.5.3" 12 | classpath "io.spring.gradle:dependency-management-plugin:1.0.11.RELEASE" 13 | classpath "com.github.node-gradle:gradle-node-plugin:3.0.1" 14 | } 15 | } 16 | 17 | apply plugin: 'com.redislabs.gradle.redislabs-parentbuild' 18 | 19 | rootProject.name = 'brewdis' 20 | 21 | projects { 22 | directories = ['app'] 23 | 24 | plugins { 25 | all { 26 | id 'idea' 27 | } 28 | path(':') { 29 | id 'org.kordamp.gradle.java-project' 30 | } 31 | path(':brewdis-ui') { 32 | id 'java-library' 33 | id 'com.github.node-gradle.node' 34 | } 35 | path(':brewdis-api') { 36 | id 'java-library' 37 | id 'org.springframework.boot' 38 | id 'io.spring.dependency-management' 39 | } 40 | } 41 | } 42 | 43 | enforce { 44 | mergeStrategy = 'append' 45 | 46 | rule(enforcer.rules.ForceDependencies) { r -> 47 | r.dependencies.addAll "com.redislabs:mesclun:1.3.2", 48 | "com.google.guava:guava:30.0-android", 49 | "com.google.errorprone:error_prone_annotations:2.4.0", 50 | "com.google.http-client:google-http-client:$googleHttpVersion", 51 | "com.google.http-client:google-http-client-jackson2:$googleHttpVersion", 52 | "com.google.api.grpc:proto-google-common-protos:2.0.1", 53 | "com.google.api:gax:1.60.1", 54 | "io.grpc:grpc-context:1.34.0", 55 | "com.google.protobuf:protobuf-java:$protobufVersion", 56 | "com.google.protobuf:protobuf-java-util:$protobufVersion", 57 | "org.hdrhistogram:HdrHistogram:2.1.12", 58 | "com.google.code.findbugs:jsr305:3.0.2" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/inventory/inventory.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 19 | 20 | 21 | 22 | 23 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
Store{{row.storeDescription}}SKU{{row.sku}}Product 17 |

{{row.productName}}

18 |
Available To Promise{{row.availableToPromise}}On Hand{{row.onHand}}Allocated{{row.allocated}}Reserved{{row.reserved}}Virtual Hold{{row.virtualHold}}
-------------------------------------------------------------------------------- /app/brewdis-ui/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "array-type": false, 5 | "arrow-parens": false, 6 | "deprecation": { 7 | "severity": "warning" 8 | }, 9 | "component-class-suffix": true, 10 | "contextual-lifecycle": true, 11 | "directive-class-suffix": true, 12 | "directive-selector": [ 13 | true, 14 | "attribute", 15 | "app", 16 | "camelCase" 17 | ], 18 | "component-selector": [ 19 | true, 20 | "element", 21 | "app", 22 | "kebab-case" 23 | ], 24 | "import-blacklist": [ 25 | true, 26 | "rxjs/Rx" 27 | ], 28 | "interface-name": false, 29 | "max-classes-per-file": false, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-consecutive-blank-lines": false, 47 | "no-console": [ 48 | true, 49 | "debug", 50 | "info", 51 | "time", 52 | "timeEnd", 53 | "trace" 54 | ], 55 | "no-empty": false, 56 | "no-inferrable-types": [ 57 | true, 58 | "ignore-params" 59 | ], 60 | "no-non-null-assertion": true, 61 | "no-redundant-jsdoc": true, 62 | "no-switch-case-fall-through": true, 63 | "no-var-requires": false, 64 | "object-literal-key-quotes": [ 65 | true, 66 | "as-needed" 67 | ], 68 | "object-literal-sort-keys": false, 69 | "ordered-imports": false, 70 | "quotemark": [ 71 | true, 72 | "single" 73 | ], 74 | "trailing-comma": false, 75 | "no-conflicting-lifecycle": true, 76 | "no-host-metadata-property": true, 77 | "no-input-rename": true, 78 | "no-inputs-metadata-property": true, 79 | "no-output-native": true, 80 | "no-output-on-prefix": true, 81 | "no-output-rename": true, 82 | "no-outputs-metadata-property": true, 83 | "template-banana-in-box": true, 84 | "template-no-negated-async": true, 85 | "use-lifecycle-interface": true, 86 | "use-pipe-transform-interface": true 87 | }, 88 | "rulesDirectory": [ 89 | "codelyzer" 90 | ] 91 | } -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/WebSocketPublisher.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import java.time.Duration; 4 | 5 | import org.springframework.beans.factory.DisposableBean; 6 | import org.springframework.beans.factory.InitializingBean; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.redis.connection.stream.MapRecord; 9 | import org.springframework.data.redis.connection.stream.StreamOffset; 10 | import org.springframework.data.redis.core.StringRedisTemplate; 11 | import org.springframework.data.redis.stream.StreamListener; 12 | import org.springframework.data.redis.stream.StreamMessageListenerContainer; 13 | import org.springframework.data.redis.stream.StreamMessageListenerContainer.StreamMessageListenerContainerOptions; 14 | import org.springframework.data.redis.stream.Subscription; 15 | import org.springframework.messaging.simp.SimpMessageSendingOperations; 16 | import org.springframework.stereotype.Component; 17 | 18 | @Component 19 | public class WebSocketPublisher implements InitializingBean, DisposableBean, StreamListener> { 20 | 21 | @Autowired 22 | private Config config; 23 | @Autowired 24 | private StringRedisTemplate template; 25 | @Autowired 26 | private SimpMessageSendingOperations sendingOps; 27 | private StreamMessageListenerContainer> container; 28 | private Subscription subscription; 29 | 30 | @Override 31 | public void afterPropertiesSet() throws Exception { 32 | this.container = StreamMessageListenerContainer.create(template.getConnectionFactory(), 33 | StreamMessageListenerContainerOptions.builder() 34 | .pollTimeout(Duration.ofMillis(config.getStreamPollTimeout())).build()); 35 | container.start(); 36 | this.subscription = container.receive(StreamOffset.latest(config.getInventory().getStream()), this); 37 | subscription.await(Duration.ofSeconds(2)); 38 | } 39 | 40 | @Override 41 | public void destroy() throws Exception { 42 | if (subscription != null) { 43 | subscription.cancel(); 44 | } 45 | if (container != null) { 46 | container.stop(); 47 | } 48 | } 49 | 50 | @Override 51 | public void onMessage(MapRecord message) { 52 | sendingOps.convertAndSend(config.getStomp().getInventoryTopic(), message.getValue()); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /.github/workflows/early-access.yml: -------------------------------------------------------------------------------- 1 | name: EarlyAccess 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | 7 | jobs: 8 | earlyaccess: 9 | name: EarlyAccess 10 | if: github.repository == 'redis-developer/brewdis' && startsWith(github.event.head_commit.message, 'Releasing version') != true 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 17 | 18 | - name: Set up Java 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | 23 | - uses: actions/cache@v2 24 | with: 25 | path: ~/.gradle/caches 26 | key: ${{ runner.os }}-gradle-cache-${{ hashFiles('**/*.gradle') }}-${{ hashFiles('**/gradle.properties') }} 27 | restore-keys: | 28 | ${{ runner.os }}-gradle- 29 | 30 | - uses: actions/cache@v2 31 | with: 32 | path: ~/.gradle/wrapper 33 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradlew') }} 34 | restore-keys: | 35 | ${{ runner.os }}-gradlew- 36 | 37 | - name: Build 38 | run: ./gradlew -Prelease=true build -S 39 | 40 | - name: Version 41 | id: vars 42 | run: echo ::set-output name=version::$(cat VERSION) 43 | 44 | - name: Assemble 45 | uses: jreleaser/release-action@v1 46 | with: 47 | arguments: assemble 48 | env: 49 | JRELEASER_PROJECT_VERSION: ${{ steps.vars.outputs.version }} 50 | JRELEASER_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 51 | 52 | - name: Release 53 | uses: jreleaser/release-action@v1 54 | with: 55 | arguments: full-release 56 | env: 57 | JRELEASER_PROJECT_VERSION: ${{ steps.vars.outputs.version }} 58 | JRELEASER_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 59 | JRELEASER_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 60 | JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.GPG_PUBLIC_KEY }} 61 | JRELEASER_GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} 62 | JRELEASER_DOCKER_DEFAULT_PASSWORD: ${{ secrets.JRELEASER_DOCKER_PASSWORD }} 63 | 64 | - name: JReleaser output 65 | if: always() 66 | uses: actions/upload-artifact@v2 67 | with: 68 | name: artifact 69 | path: | 70 | out/jreleaser/trace.log 71 | out/jreleaser/output.properties 72 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { AgmCoreModule } from '@agm/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { NgModule } from '@angular/core'; 4 | import { FlexLayoutModule } from '@angular/flex-layout'; 5 | import { HashLocationStrategy, LocationStrategy } from '@angular/common'; 6 | import { HttpClientModule } from '@angular/common/http'; 7 | import { AppRoutingModule } from './app-routing.module'; 8 | import { AppComponent } from './app.component'; 9 | import { ReactiveFormsModule, FormsModule } from '@angular/forms'; 10 | import { MatDialogModule } from '@angular/material/dialog'; 11 | import { MatPaginatorModule } from '@angular/material/paginator'; 12 | 13 | import { 14 | MatButtonModule, MatIconModule, MatCardModule, 15 | MatInputModule, MatAutocompleteModule, MatListModule, 16 | MatGridListModule, MatToolbarModule, MatSelectModule, 17 | MatTableModule, MatSortModule, MatButtonToggleModule, MatExpansionModule 18 | } from '@angular/material'; 19 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 20 | import { MatTooltipModule } from '@angular/material/tooltip'; 21 | import { MaterialModule } from './material.module'; 22 | import { InventoryComponent } from './inventory/inventory.component'; 23 | import { AvailabilityComponent } from './availability/availability.component'; 24 | import { CatalogComponent } from './catalog/catalog.component'; 25 | 26 | @NgModule({ 27 | declarations: [ 28 | AppComponent, 29 | CatalogComponent, 30 | InventoryComponent, 31 | AvailabilityComponent 32 | ], 33 | imports: [ 34 | AgmCoreModule.forRoot({ 35 | apiKey: 'AIzaSyCn5UCrMs-Lh6R_kBDkGxnw9GzTME273cQ' 36 | }), 37 | BrowserModule, 38 | BrowserAnimationsModule, 39 | MatTooltipModule, 40 | MaterialModule, 41 | AppRoutingModule, 42 | HttpClientModule, 43 | ReactiveFormsModule, 44 | FormsModule, 45 | FlexLayoutModule, 46 | MatButtonModule, 47 | MatIconModule, 48 | MatCardModule, 49 | MatInputModule, 50 | MatAutocompleteModule, 51 | MatListModule, 52 | MatGridListModule, 53 | MatToolbarModule, 54 | MatSelectModule, 55 | MatTableModule, 56 | MatSortModule, 57 | MatButtonToggleModule, 58 | MatDialogModule, 59 | MatPaginatorModule, 60 | MatExpansionModule 61 | ], 62 | providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }], 63 | bootstrap: [AppComponent] 64 | }) 65 | export class AppModule { } 66 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/search.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | import { environment } from '../environments/environment'; 5 | 6 | export interface Query { 7 | query: string; 8 | sortByField: string; 9 | sortByDirection: string; 10 | pageIndex: number; 11 | pageSize: number; 12 | } 13 | 14 | @Injectable({ 15 | providedIn: 'root' 16 | }) 17 | export class SearchService { 18 | 19 | API_URL = '/api/'; 20 | 21 | constructor(private http: HttpClient) { } 22 | 23 | styles(category: string): Observable { 24 | let params = new HttpParams(); 25 | if (category != null) { 26 | params = params.set('category', category); 27 | } 28 | return this.http.get(this.API_URL + 'styles', { params }); 29 | } 30 | 31 | categories(): Observable { 32 | return this.http.get(this.API_URL + 'categories'); 33 | } 34 | 35 | foods(): Observable { 36 | return this.http.get(this.API_URL + 'foods'); 37 | } 38 | 39 | products(query: Query, lng: any, lat: any): Observable { 40 | let params = new HttpParams(); 41 | params = params.set('longitude', lng); 42 | params = params.set('latitude', lat); 43 | return this.http.post(this.API_URL + 'products', query, { params }); 44 | } 45 | 46 | availability(sku: string, lng: any, lat: any) { 47 | let params = new HttpParams(); 48 | if (sku != null) { 49 | params = params.set('sku', sku); 50 | } 51 | params = params.set('longitude', lng); 52 | params = params.set('latitude', lat); 53 | return this.http.get(this.API_URL + 'availability', { params }); 54 | } 55 | 56 | inventory(store: string) { 57 | let params = new HttpParams(); 58 | if (store != null) { 59 | params = params.set('store', store); 60 | } 61 | return this.http.get(this.API_URL + 'inventory', { params }); 62 | } 63 | 64 | suggestBreweries(prefix: string): Observable { 65 | let params = new HttpParams(); 66 | if (prefix != null) { 67 | params = params.set('prefix', prefix); 68 | } 69 | return this.http.get(this.API_URL + 'breweries', { params }); 70 | } 71 | 72 | suggestFoods(prefix: string): Observable { 73 | let params = new HttpParams(); 74 | if (prefix != null) { 75 | params = params.set('prefix', prefix); 76 | } 77 | return this.http.get(this.API_URL + 'foods', { params }); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | import 'hammerjs/hammer'; 64 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: "Release version" 8 | required: true 9 | jobs: 10 | release: 11 | name: Release 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 17 | 18 | - name: Set up Java 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | 23 | - uses: actions/cache@v2 24 | with: 25 | path: ~/.gradle/caches 26 | key: ${{ runner.os }}-gradle-cache-${{ hashFiles('**/*.gradle') }}-${{ hashFiles('**/gradle.properties') }} 27 | restore-keys: | 28 | ${{ runner.os }}-gradle- 29 | 30 | - uses: actions/cache@v2 31 | with: 32 | path: ~/.gradle/wrapper 33 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradlew') }} 34 | restore-keys: | 35 | ${{ runner.os }}-gradlew- 36 | 37 | - name: Set release version 38 | run: | 39 | VERSION=${{ github.event.inputs.version }} 40 | echo $VERSION > VERSION 41 | sed -i -e "s/^\:project-version\:\ .*/:project-version: $VERSION/g" README.adoc 42 | git add VERSION 43 | git add README.adoc 44 | git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" 45 | git config --global user.name "GitHub Action" 46 | git commit -a -m "Releasing version $VERSION" 47 | git push origin master 48 | 49 | - name: Build 50 | env: 51 | GITHUB_USERNAME: jruaux 52 | GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }} 53 | GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} 54 | GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 55 | run: | 56 | ./gradlew -Prelease=true -Pfull-release=true build -S 57 | 58 | - name: Assemble 59 | uses: jreleaser/release-action@v1 60 | with: 61 | arguments: assemble 62 | env: 63 | JRELEASER_PROJECT_VERSION: ${{ github.event.inputs.version }} 64 | JRELEASER_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 65 | 66 | - name: Release 67 | uses: jreleaser/release-action@v1 68 | with: 69 | arguments: full-release 70 | env: 71 | JRELEASER_PROJECT_VERSION: ${{ github.event.inputs.version }} 72 | JRELEASER_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 73 | JRELEASER_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 74 | JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.GPG_PUBLIC_KEY }} 75 | JRELEASER_GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} 76 | JRELEASER_DOCKER_DEFAULT_PASSWORD: ${{ secrets.JRELEASER_DOCKER_PASSWORD }} 77 | JRELEASER_SLACK_WEBHOOK: ${{ secrets.JRELEASER_SLACK_WEBHOOK }} 78 | 79 | - name: JReleaser output 80 | if: always() 81 | uses: actions/upload-artifact@v2 82 | with: 83 | name: artifact 84 | path: | 85 | out/jreleaser/trace.log 86 | out/jreleaser/output.properties 87 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #logging.level.root=DEBUG 2 | spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.cloud.aws.autoconfigure.messaging.MessagingAutoConfiguration,org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration,org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration,org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration,org.springframework.cloud.aws.autoconfigure.context.ContextResourceLoaderAutoConfiguration,org.springframework.cloud.gcp.autoconfigure.core.GcpContextAutoConfiguration,org.springframework.cloud.gcp.autoconfigure.storage.GcpStorageAutoConfiguration 3 | availability-radius=25 mi 4 | key-separator=: 5 | inventory.index=inventory 6 | inventory.keyspace=inventory 7 | inventory.search-limit=50 8 | inventory.level-low=10 9 | inventory.level-medium=20 10 | inventory.update-stream=inventory-updates 11 | inventory.stream=inventory-stream 12 | inventory.cleanup.searchLimit=10000 13 | inventory.cleanup.ageThreshold=3600 14 | inventory.cleanup.streamTrimCount=1000 15 | inventory.cleanup.rate=10000 16 | inventory.generator.onHandMin=40 17 | inventory.generator.onHandMax=100 18 | inventory.generator.deltaMin=1 19 | inventory.generator.deltaMax=3 20 | inventory.generator.allocatedMin=1 21 | inventory.generator.allocatedMax=10 22 | inventory.generator.reservedMin=1 23 | inventory.generator.reservedMax=10 24 | inventory.generator.rate=300 25 | inventory.generator.requestDurationInSeconds=600 26 | inventory.generator.skusMax=13 27 | inventory.generator.storesMax=7 28 | inventory.generator.virtualHoldMax=10 29 | inventory.generator.virtualHoldMin=1 30 | inventory.restock.delayMin=5 31 | inventory.restock.delayMax=30 32 | inventory.restock.threshold=5 33 | inventory.restock.deltaMin=20 34 | inventory.restock.deltaMax=90 35 | product.index=products 36 | product.keyspace=product 37 | product.brewery.index=breweries 38 | product.brewery.fuzzy=true 39 | product.load.count=30000 40 | product.inventory-mapping.sku=sku 41 | product.inventory-mapping.name=productName 42 | product.inventory-mapping.abv=abv 43 | product.inventory-mapping.ibu=ibu 44 | product.inventory-mapping.labels.icon=icon 45 | product.food-pairings.limit=10000 46 | product.food-pairings.index=foodPairings 47 | product.food-pairings.fuzzy=false 48 | product.url=https://storage.googleapis.com/jrx/products_labels.json.gz 49 | stomp.host=localhost 50 | stomp.protocol=ws 51 | stomp.port=8080 52 | stomp.endpoint=/websocket 53 | stomp.destinationPrefix=/topic 54 | stomp.inventoryTopic=/topic/inventory 55 | store.count=3568 56 | store.index=stores 57 | store.inventory-mapping.store=store 58 | store.inventory-mapping.description=storeDescription 59 | store.inventory-mapping.inventoryAvailableToSell=inventoryAvailableToSell 60 | store.inventory-mapping.isDefault=defaultStore 61 | store.inventory-mapping.preferred=preferredStore 62 | store.inventory-mapping.location=location 63 | store.inventory-mapping.latitude=latitude 64 | store.inventory-mapping.longitude=longitude 65 | store.inventory-mapping.market=market 66 | store.inventory-mapping.rollupInventory=rollupInventory 67 | store.inventory-mapping.type=storeType 68 | store.keyspace=store 69 | store.url=https://storage.googleapis.com/jrx/stores.csv 70 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/inventory/inventory.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, ViewChild } from '@angular/core'; 2 | import { ActivatedRoute } from '@angular/router'; 3 | import { StompService, StompConfig } from '@stomp/ng2-stompjs'; 4 | import { HttpClient } from '@angular/common/http'; 5 | import { MatTable } from '@angular/material'; 6 | import { SearchService } from '../search.service'; 7 | import { MatSort } from '@angular/material/sort'; 8 | import { MatTableDataSource } from '@angular/material/table'; 9 | 10 | export interface InventoryData { 11 | store: string; 12 | sku: string; 13 | storeDescription: string; 14 | productName: string; 15 | availableToPromise: number; 16 | onHand: number; 17 | allocated: number; 18 | reserved: number; 19 | virtualHold: number; 20 | delta: number; 21 | time: string; 22 | level: string; 23 | } 24 | 25 | @Component({ 26 | selector: 'app-inventory', 27 | templateUrl: './inventory.component.html', 28 | styleUrls: ['./inventory.component.css'] 29 | }) 30 | export class InventoryComponent implements OnInit { 31 | 32 | API_URL = '/api/'; 33 | @ViewChild(MatTable, { static: true }) table: MatTable; 34 | @ViewChild(MatSort, { static: true }) sort: MatSort; 35 | 36 | private stompService: StompService; 37 | dataSource = new MatTableDataSource(); 38 | displayedColumns: string[] = ['store', 'sku', 'productName', 'availableToPromise', 'onHand', 'allocated', 'reserved', 'virtualHold']; 39 | 40 | constructor(private http: HttpClient, private route: ActivatedRoute, private searchService: SearchService) { } 41 | 42 | ngOnInit() { 43 | let store: string; 44 | this.route.paramMap.subscribe(params => { 45 | store = params.get('store'); 46 | }); 47 | this.dataSource.sort = this.sort; 48 | this.searchService.inventory(store).subscribe((inventory: InventoryData[]) => this.dataSource.data = inventory); 49 | this.http.get(this.API_URL + 'config/stomp').subscribe((stomp: any) => this.connectStompService(stomp)); 50 | } 51 | 52 | connectStompService(config: any) { 53 | const stompUrl = config.protocol + '://' + config.host + ':' + config.port + config.endpoint; 54 | const stompConfig: StompConfig = { 55 | url: stompUrl, 56 | headers: { 57 | login: '', 58 | passcode: '' 59 | }, 60 | heartbeat_in: 0, 61 | heartbeat_out: 20000, 62 | reconnect_delay: 5000, 63 | debug: false 64 | }; 65 | this.stompService = new StompService(stompConfig); 66 | this.stompService.subscribe(config.inventoryTopic).subscribe(update => this.updateRowData(JSON.parse(update.body))); 67 | } 68 | 69 | updateRowData(row) { 70 | this.dataSource.data = this.dataSource.data.filter((value: InventoryData, key) => { 71 | if (value.store === row.store && value.sku === row.sku) { 72 | value.availableToPromise = row.availableToPromise; 73 | value.onHand = row.onHand; 74 | value.allocated = row.allocated; 75 | value.reserved = row.reserved; 76 | value.virtualHold = row.virtualHold; 77 | value.time = row.time; 78 | value.delta = row.delta; 79 | value.level = row.level; 80 | } 81 | return true; 82 | }); 83 | this.table.renderRows(); 84 | } 85 | 86 | isRecent(row: InventoryData) { 87 | const duration = new Date().valueOf() - new Date(row.time).valueOf(); 88 | return duration < 1000; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /app/brewdis-ui/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "brewdis-ui": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": { 12 | 13 | }, 14 | "architect": { 15 | "build": { 16 | "builder": "@angular-devkit/build-angular:browser", 17 | "options": { 18 | "outputPath": "dist/brewdis-ui", 19 | "index": "src/index.html", 20 | "main": "src/main.ts", 21 | "polyfills": "src/polyfills.ts", 22 | "tsConfig": "tsconfig.app.json", 23 | "assets": [ 24 | "src/favicon.ico", 25 | "src/assets" 26 | ], 27 | "styles": [ 28 | "src/styles.css", 29 | "src/theme.scss" 30 | ], 31 | "scripts": [] 32 | }, 33 | "configurations": { 34 | "production": { 35 | "fileReplacements": [ 36 | { 37 | "replace": "src/environments/environment.ts", 38 | "with": "src/environments/environment.prod.ts" 39 | } 40 | ], 41 | "optimization": true, 42 | "outputHashing": "all", 43 | "sourceMap": false, 44 | "extractCss": true, 45 | "namedChunks": false, 46 | "aot": true, 47 | "extractLicenses": true, 48 | "vendorChunk": false, 49 | "buildOptimizer": true, 50 | "budgets": [ 51 | { 52 | "type": "initial", 53 | "maximumWarning": "2mb", 54 | "maximumError": "5mb" 55 | }, 56 | { 57 | "type": "anyComponentStyle", 58 | "maximumWarning": "6kb", 59 | "maximumError": "10kb" 60 | } 61 | ] 62 | } 63 | } 64 | }, 65 | "serve": { 66 | "builder": "@angular-devkit/build-angular:dev-server", 67 | "options": { 68 | "browserTarget": "brewdis-ui:build" 69 | }, 70 | "configurations": { 71 | "production": { 72 | "browserTarget": "brewdis-ui:build:production" 73 | } 74 | } 75 | }, 76 | "extract-i18n": { 77 | "builder": "@angular-devkit/build-angular:extract-i18n", 78 | "options": { 79 | "browserTarget": "brewdis-ui:build" 80 | } 81 | }, 82 | "test": { 83 | "builder": "@angular-devkit/build-angular:karma", 84 | "options": { 85 | "main": "src/test.ts", 86 | "polyfills": "src/polyfills.ts", 87 | "tsConfig": "tsconfig.spec.json", 88 | "karmaConfig": "karma.conf.js", 89 | "assets": [ 90 | "src/favicon.ico", 91 | "src/assets" 92 | ], 93 | "styles": [ 94 | "src/styles.css", 95 | "src/theme.scss" 96 | ], 97 | "scripts": [] 98 | } 99 | }, 100 | "lint": { 101 | "builder": "@angular-devkit/build-angular:tslint", 102 | "options": { 103 | "tsConfig": [ 104 | "tsconfig.app.json", 105 | "tsconfig.spec.json", 106 | "e2e/tsconfig.json" 107 | ], 108 | "exclude": [ 109 | "**/node_modules/**" 110 | ] 111 | } 112 | }, 113 | "e2e": { 114 | "builder": "@angular-devkit/build-angular:protractor", 115 | "options": { 116 | "protractorConfig": "e2e/protractor.conf.js", 117 | "devServerTarget": "brewdis-ui:serve" 118 | }, 119 | "configurations": { 120 | "production": { 121 | "devServerTarget": "brewdis-ui:serve:production" 122 | } 123 | } 124 | } 125 | } 126 | } 127 | }, 128 | "defaultProject": "brewdis-ui" 129 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Brewdis 2 | 3 | 4 | Real-time inventory demo based on data from [https://brewerydb.com](brewerydb.com). 5 | 6 | ## Tech Stack 7 | 8 | 9 | - Spring Boot 10 | - Gradle 6.8.3 11 | - Kordamp Gradle plugins 0.46.0. 12 | - Redis 13 | - Redis Search 14 | 15 | 16 | 17 | ## Architecture 18 | 19 | ![image](https://raw.githubusercontent.com/redis-developer/brewdis/master/app/architecture.svg) 20 | 21 | 22 | 23 | 24 | 25 | ## Run the demo 26 | 27 | ``` 28 | git clone https://github.com/redis-developer/brewdis.git 29 | cd brewdis 30 | docker-compose up 31 | ``` 32 | 33 | Access the demo at http://localhost 34 | 35 | ## Demo Steps 36 | 37 | 38 | 39 | ## Products 40 | 41 | Launch `redis-cli` 42 | 43 | ### Show number of documents inRedis Searchindex: 44 | 45 | ``` 46 | FT.INFO products 47 | ``` 48 | 49 | ### Run simple keyword search: 50 | 51 | ``` 52 | FT.SEARCH products chambly 53 | ``` 54 | 55 | TIP: `name`, `description`, `breweryName` are phonetic text fields so you will notice results containing words that sound similar. 56 | 57 | ### Run prefix search: 58 | 59 | ``` 60 | `FT.SEARCH products chamb*` 61 | ``` 62 | 63 | - Open http://localhost[] 64 | - Enter a simple keyword search, e.g. `chambly`. Note highlighted matches. 65 | - Expand the filter panel by clicking on the filter button (image:https://pic.onlinewebfonts.com/svg/img_3152.png[width=24]) 66 | - Enter some characters in the Brewery field to retrieve suggestions fromRedis Search(e.g. `Unib`) 67 | - Click the `Submit` button 68 | - Refine the search by adding a constraint on the alcohol content (ABV field): 69 | 70 | ``` 71 | `@abv:[7 9]` 72 | ``` 73 | - Change the sort-by field to `ABV` and click `Submit` 74 | 75 | 76 | ### Availability 77 | 78 | Click `Availability` on one of the search results. This takes you to the availability map for that product. 79 | . The map shows stores near you where the selected product is currently available. 80 | . Stores in `green` have more than 20 in stock, `amber`: 10 to 20, `red`: less than 10 81 | 82 | ### Inventory 83 | 84 | - Click on a store and then on the link that pops up 85 | - This takes you to the real-time inventory for that store 86 | - The *Available to Promise* field is updated in real-time based on current difference between supply (*On Hand*) and demand (*Reserved + Allocated + Virtual Hold*). 87 | 88 | 89 | ### Configuration 90 | 91 | The app server is built with Spring Boot which can be configured different ways: [Spring Boot Externalized Configuration](https://docs.spring.io/spring-boot/docs/2.2.x/reference/html/spring-boot-features.html#boot-features-external-config) 92 | 93 | Depending on the way you're running the demo you can either: 94 | 95 | - create a `application.properties` file based on the [one that ships with Brewdis](https://github.com/redis-developer/brewdis/blob/master/demo/brewdis-api/src/main/resources/application.properties) 96 | - specify JVM arguments like this: 97 | 98 | 99 | ``` 100 | java -jar brewdis.jar --spring.redis.host=localhost --spring.redis.port=6379 ... 101 | ``` 102 | 103 | - use environment variables: 104 | 105 | 106 | ``` 107 | export spring.redis.host=localhost 108 | export spring.redis.port=8080 109 | export ... 110 | java -jar brewdis.jar 111 | ``` 112 | 113 | Here are the most common configuration options for this demo: 114 | 115 | - `spring.redis.host`: Redis database hostname (default: `localhost`) 116 | - `spring.redis.port`: Redis database port (default: `6379`) 117 | - `stomp.host`: Websocket server hostname (default: `localhost`) 118 | - `stomp.port`: Websocket server port (default: `8080`) 119 | - `stomp.protocol`: Websocket protocol (default: `ws`). Use `wss` for secure websockets 120 | - `inventory.generator.rate`: duration in millis the generator should sleep between inventory updates (default: `100`) 121 | - `availability-radius`: radius to find in-store availability (default: `25 mi`) 122 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/Config.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | import java.io.Serializable; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | @Configuration 13 | @ConfigurationProperties(prefix = "") 14 | @EnableAutoConfiguration 15 | @Data 16 | public class Config { 17 | 18 | private String keySeparator; 19 | private long streamPollTimeout = 100; 20 | private StompConfig stomp = new StompConfig(); 21 | private String availabilityRadius; 22 | private ProductConfig product = new ProductConfig(); 23 | private StoreConfig store = new StoreConfig(); 24 | private InventoryConfig inventory = new InventoryConfig(); 25 | private SessionConfig session = new SessionConfig(); 26 | 27 | @Data 28 | public static class SessionConfig { 29 | private String cartAttribute = "cart"; 30 | private String coordsAttribute = "coords"; 31 | } 32 | 33 | @Data 34 | public static class StoreConfig { 35 | private String index; 36 | private String keyspace; 37 | private String url; 38 | private long count; 39 | private Map inventoryMapping = new HashMap<>(); 40 | } 41 | 42 | @Data 43 | public static class ProductConfig { 44 | private String index; 45 | private String keyspace; 46 | private String url; 47 | private Map inventoryMapping = new HashMap<>(); 48 | private ProductLoadConfig load = new ProductLoadConfig(); 49 | private FoodPairingsConfig foodPairings = new FoodPairingsConfig(); 50 | private BreweryConfig brewery = new BreweryConfig(); 51 | } 52 | 53 | @Data 54 | public static class BreweryConfig { 55 | private String index; 56 | private boolean fuzzy; 57 | } 58 | 59 | @Data 60 | public static class FoodPairingsConfig { 61 | private long limit; 62 | private String index; 63 | private boolean fuzzy; 64 | } 65 | 66 | @Data 67 | public static class ProductLoadConfig { 68 | private long count; 69 | } 70 | 71 | @Data 72 | public static class InventoryConfig { 73 | private String updateStream; 74 | private String stream; 75 | private String index; 76 | private String keyspace; 77 | private int searchLimit; 78 | private int levelLow; 79 | private int levelMedium; 80 | private InventoryGeneratorConfig generator = new InventoryGeneratorConfig(); 81 | private InventoryRestockConfig restock = new InventoryRestockConfig(); 82 | private InventoryCleanupConfig cleanup = new InventoryCleanupConfig(); 83 | 84 | public String level(int quantity) { 85 | if (quantity <= levelLow) { 86 | return "low"; 87 | } 88 | if (quantity <= levelMedium) { 89 | return "medium"; 90 | } 91 | return "high"; 92 | } 93 | } 94 | 95 | @Data 96 | public static class InventoryRestockConfig { 97 | private int delayMin; 98 | private int delayMax; 99 | private int threshold; 100 | private int deltaMin; 101 | private int deltaMax; 102 | } 103 | 104 | @Data 105 | public static class InventoryCleanupConfig { 106 | private int searchLimit; 107 | private long ageThreshold; 108 | private long streamTrimCount; 109 | } 110 | 111 | @Data 112 | public static class InventoryGeneratorConfig { 113 | private int onHandMin; 114 | private int onHandMax; 115 | private int deltaMin; 116 | private int deltaMax; 117 | private int allocatedMin; 118 | private int allocatedMax; 119 | private int reservedMin; 120 | private int reservedMax; 121 | private int virtualHoldMin; 122 | private int virtualHoldMax; 123 | private long requestDurationInSeconds; 124 | private long skusMax; 125 | private long storesMax; 126 | } 127 | 128 | @Data 129 | public static class StompConfig implements Serializable { 130 | private static final long serialVersionUID = -623741573410463326L; 131 | private String protocol; 132 | private String host; 133 | private int port; 134 | private String endpoint; 135 | private String destinationPrefix; 136 | private String inventoryTopic; 137 | } 138 | 139 | public String concat(String... keys) { 140 | return String.join(keySeparator, keys); 141 | } 142 | 143 | public String tag(String field, String value) { 144 | return "@" + field + ":{" + value + "}"; 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/InventorySupply.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import static com.redislabs.demo.brewdis.BrewdisField.AVAILABLE_TO_PROMISE; 4 | import static com.redislabs.demo.brewdis.BrewdisField.ON_HAND; 5 | import static com.redislabs.demo.brewdis.BrewdisField.PRODUCT_ID; 6 | import static com.redislabs.demo.brewdis.BrewdisField.STORE_ID; 7 | 8 | import java.time.Duration; 9 | import java.time.ZonedDateTime; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.PrimitiveIterator.OfInt; 13 | import java.util.Random; 14 | import java.util.concurrent.Executors; 15 | import java.util.concurrent.ScheduledExecutorService; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | import org.springframework.beans.factory.DisposableBean; 19 | import org.springframework.beans.factory.InitializingBean; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.data.redis.connection.stream.MapRecord; 22 | import org.springframework.data.redis.connection.stream.StreamOffset; 23 | import org.springframework.data.redis.core.StringRedisTemplate; 24 | import org.springframework.data.redis.stream.StreamListener; 25 | import org.springframework.data.redis.stream.StreamMessageListenerContainer; 26 | import org.springframework.data.redis.stream.StreamMessageListenerContainer.StreamMessageListenerContainerOptions; 27 | import org.springframework.data.redis.stream.Subscription; 28 | import org.springframework.stereotype.Component; 29 | 30 | import lombok.extern.slf4j.Slf4j; 31 | 32 | @Component 33 | @Slf4j 34 | public class InventorySupply 35 | implements InitializingBean, DisposableBean, StreamListener> { 36 | 37 | @Autowired 38 | private Config config; 39 | @Autowired 40 | private StringRedisTemplate template; 41 | private ScheduledExecutorService executor; 42 | private OfInt delays; 43 | private Subscription subscription; 44 | private OfInt restockOnHands; 45 | private StreamMessageListenerContainer> container; 46 | private Map scheduledRestocks = new HashMap<>(); 47 | 48 | @Override 49 | public void afterPropertiesSet() throws Exception { 50 | Random random = new Random(); 51 | this.delays = random.ints(config.getInventory().getRestock().getDelayMin(), 52 | config.getInventory().getRestock().getDelayMax()).iterator(); 53 | this.restockOnHands = random.ints(config.getInventory().getRestock().getDeltaMin(), 54 | config.getInventory().getRestock().getDeltaMax()).iterator(); 55 | this.container = StreamMessageListenerContainer.create(template.getConnectionFactory(), 56 | StreamMessageListenerContainerOptions.builder() 57 | .pollTimeout(Duration.ofMillis(config.getStreamPollTimeout())).build()); 58 | container.start(); 59 | this.subscription = container.receive(StreamOffset.latest(config.getInventory().getStream()), this); 60 | subscription.await(Duration.ofSeconds(2)); 61 | executor = Executors.newSingleThreadScheduledExecutor(); 62 | } 63 | 64 | @Override 65 | public void destroy() throws Exception { 66 | if (executor != null) { 67 | executor.shutdownNow(); 68 | } 69 | if (subscription != null) { 70 | subscription.cancel(); 71 | } 72 | if (container != null) { 73 | container.stop(); 74 | } 75 | } 76 | 77 | @Override 78 | public void onMessage(MapRecord message) { 79 | String store = message.getValue().get(STORE_ID); 80 | String sku = message.getValue().get(PRODUCT_ID); 81 | int available = Integer.parseInt(message.getValue().get(AVAILABLE_TO_PROMISE)); 82 | if (available < config.getInventory().getRestock().getThreshold()) { 83 | String id = config.concat(store, sku); 84 | if (scheduledRestocks.containsKey(id)) { 85 | return; 86 | } 87 | scheduledRestocks.put(id, ZonedDateTime.now()); 88 | int delay = delays.nextInt(); 89 | log.info("Scheduling restocking for {}:{} in {} seconds", store, sku, delay); 90 | executor.schedule(new Runnable() { 91 | 92 | @Override 93 | public void run() { 94 | int delta = restockOnHands.nextInt(); 95 | Map message = new HashMap<>(); 96 | message.put(STORE_ID, store); 97 | message.put(PRODUCT_ID, sku); 98 | message.put(ON_HAND, String.valueOf(delta)); 99 | template.opsForStream().add(config.getInventory().getUpdateStream(), message); 100 | scheduledRestocks.remove(id); 101 | } 102 | }, delay, TimeUnit.SECONDS); 103 | } 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/catalog.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormControl } from '@angular/forms'; 3 | import { Observable } from 'rxjs'; 4 | import { SearchService, Query } from '../search.service'; 5 | import { ActivatedRoute, Router } from '@angular/router'; 6 | import { 7 | debounceTime, filter, share 8 | } from 'rxjs/operators'; 9 | import { DialogComponent } from './dialog/dialog.component'; 10 | import { MatDialog } from '@angular/material/dialog'; 11 | import { PageEvent } from '@angular/material/paginator'; 12 | 13 | @Component({ 14 | selector: 'app-catalog', 15 | templateUrl: './catalog.component.html', 16 | styleUrls: ['./catalog.component.css'] 17 | }) 18 | export class CatalogComponent implements OnInit { 19 | API_URL = '/api/'; 20 | breweries: Observable; 21 | foods: Observable; 22 | sortByField = 'name'; 23 | sortByDirection = 'ASC'; 24 | showFilters = false; 25 | showSort = false; 26 | categoryField = new FormControl(); 27 | categories = []; 28 | styleField = new FormControl(); 29 | styles = []; 30 | breweryField = new FormControl(); 31 | abvField = new FormControl(); 32 | ibuField = new FormControl(); 33 | foodField = new FormControl(); 34 | labelField = new FormControl(); 35 | searchField = new FormControl(); 36 | showResults = false; 37 | result$: Observable = null; 38 | resultCount = 0; 39 | searchDuration = 0; 40 | lat = 34.0030; 41 | lng = -118.4298; 42 | pageIndex = 0; 43 | pageSize = 50; 44 | 45 | constructor(private searchService: SearchService, private route: ActivatedRoute, private router: Router, public dialog: MatDialog) { } 46 | 47 | openDescriptionDialog(product: any) { 48 | this.dialog.open(DialogComponent, { 49 | data: product 50 | }); 51 | } 52 | 53 | ngOnInit() { 54 | this.labelField.setValue('all'); 55 | this.searchField.setValue(''); 56 | this.categoryField.valueChanges.subscribe( 57 | (category: string) => this.searchService.styles(category).subscribe( 58 | data => this.styles = data 59 | ) 60 | ); 61 | this.categoryField.valueChanges.subscribe( 62 | (category: string) => this.addQueryCriteria('@category:{' + category + '}') 63 | ); 64 | this.styleField.valueChanges.subscribe( 65 | (style: string) => this.addQueryCriteria('@style:{' + style + '}') 66 | ); 67 | this.breweryField.valueChanges.pipe( 68 | debounceTime(300) 69 | ).subscribe(prefix => this.searchService.suggestBreweries(prefix).subscribe(data => this.breweries = data)); 70 | this.abvField.valueChanges.subscribe( 71 | (abv: string) => this.addQueryCriteria('@abv:[' + abv.replace('-', ' ') + ']') 72 | ); 73 | this.ibuField.valueChanges.subscribe( 74 | (ibu: string) => this.addQueryCriteria('@ibu:[' + ibu.replace('-', ' ') + ']') 75 | ); 76 | this.foodField.valueChanges.pipe( 77 | debounceTime(300) 78 | ).subscribe(prefix => this.searchService.suggestFoods(prefix).subscribe(data => this.foods = data)); 79 | this.labelField.valueChanges.pipe(filter((label: string) => label === 'required')).subscribe( 80 | (label: string) => this.addQueryCriteria('@label:{true}') 81 | ); 82 | this.searchService.categories().subscribe(data => this.categories = data); 83 | if (navigator.geolocation) { 84 | navigator.geolocation.getCurrentPosition((position) => { 85 | this.lat = position.coords.latitude; 86 | this.lng = position.coords.longitude; 87 | }); 88 | } else { 89 | alert('Geolocation is not supported by this browser.'); 90 | } 91 | } 92 | 93 | toggleFilters() { 94 | this.showFilters = !this.showFilters; 95 | } 96 | 97 | toggleSort() { 98 | this.showSort = !this.showSort; 99 | } 100 | 101 | addQueryCriteria(criteria: string) { 102 | const query = this.searchField.value ? this.searchField.value + ' ' : ''; 103 | this.searchField.setValue(query + criteria); 104 | } 105 | 106 | search(pageIndex: number, pageSize: number) { 107 | const queryObject: Query = { 108 | query: this.searchField.value, 109 | sortByField: this.sortByField, 110 | sortByDirection: this.sortByDirection, 111 | pageIndex, 112 | pageSize 113 | }; 114 | this.result$ = this.searchService.products(queryObject, this.lng, this.lat).pipe(share()); 115 | this.result$.subscribe(r => {this.resultCount = r.count; this.searchDuration = r.duration; }); 116 | this.showResults = true; 117 | this.pageIndex = pageIndex; 118 | this.pageSize = pageSize; 119 | } 120 | 121 | public handlePage(event: PageEvent) { 122 | this.pageIndex = event.pageIndex; 123 | this.pageSize = event.pageSize; 124 | this.search(event.pageIndex, event.pageSize); 125 | } 126 | 127 | displayBrewery(brewery: any) { 128 | if (brewery) { return brewery.name; } 129 | } 130 | 131 | displayFood(food: any) { 132 | if (food) { 133 | return food; 134 | } 135 | } 136 | 137 | brewerySelected(brewery: any) { 138 | this.addQueryCriteria('@brewery:{' + brewery.id + '}'); 139 | } 140 | 141 | foodSelected(food: any) { 142 | this.addQueryCriteria('@foodPairings:("' + food + '")'); 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/app/catalog/catalog.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 18 |
19 |
20 | 21 | Category 22 | 23 | {{category.name}} 24 | 25 | 26 | 27 | 28 | Style 29 | 30 | {{style.name}} 31 | 32 | 33 |
34 |
35 | 36 | ABV 37 | 38 | 0 - 3% 39 | 3 - 5% 40 | 5 - 7% 41 | 7 - 9% 42 | 9 - 11% 43 | 11 - 15% 44 | > 15% 45 | 46 | 47 | 48 | IBU 49 | 50 | 0 - 30 51 | 30 - 60 52 | 60 - 90 53 | 90 - 120 54 | > 120 55 | 56 | 57 |
58 |
59 | 60 | 62 | 64 | 65 | 66 | {{brewery.name}} 67 | 68 | 69 | 70 | 71 | 73 | 75 | 76 | {{food}} 77 | 78 | 79 | 80 |
81 |
82 | 83 | Sort by 84 | 85 | Beer Name 86 | ABV 87 | IBU 88 | 89 | 90 | 91 | 92 | Ascending 93 | Descending 94 | 95 | 96 |
97 |
98 |
99 | 100 |
101 | 102 |
103 | 105 | 106 |
107 |
108 |
109 |
{{searchDuration | number}} seconds
110 |
111 |
112 |
113 |
114 |
116 | 118 | 119 | 120 | 121 | 122 | {{product.abv ? product.abv : '?'}}% 123 | 124 | IBU: {{product.ibu ? product.ibu : '?'}} 125 | 126 | 129 | 130 | 131 | 133 | 134 | 135 |
136 |
137 |
138 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/redis.svg: -------------------------------------------------------------------------------- 1 | 2 | 16 | 18 | 19 | 21 | image/svg+xml 22 | 24 | 25 | 26 | 27 | 28 | 48 | 50 | 80 | 82 | 88 | 89 | 90 | 92 | 96 | 98 | 104 | 110 | 116 | 122 | 128 | 134 | 135 | 136 | 141 | 146 | 152 | 157 | 162 | 163 | 169 | 175 | 176 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/store-low.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 22 | image/svg+xml 23 | 25 | 26 | 27 | 28 | 29 | 31 | 61 | 63 | 71 | 72 | 73 | 98 | 103 | 108 | 111 | 115 | 117 | 123 | 129 | 135 | 141 | 147 | 153 | 154 | 155 | 160 | 165 | 171 | 176 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/store-medium.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 22 | image/svg+xml 23 | 25 | 26 | 27 | 28 | 29 | 31 | 61 | 63 | 71 | 72 | 73 | 98 | 103 | 108 | 111 | 115 | 117 | 123 | 129 | 135 | 141 | 147 | 153 | 154 | 155 | 160 | 165 | 171 | 176 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/store-high.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 22 | image/svg+xml 23 | 25 | 26 | 27 | 28 | 29 | 31 | 61 | 63 | 71 | 72 | 73 | 98 | 103 | 108 | 111 | 115 | 117 | 123 | 129 | 135 | 141 | 147 | 153 | 154 | 155 | 160 | 165 | 171 | 176 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /app/brewdis-ui/src/assets/brewdis.svg: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 22 | image/svg+xml 23 | 25 | 26 | 27 | 28 | 29 | 31 | 61 | 63 | 71 | 72 | 73 | 98 | 103 | 108 | 111 | 115 | 117 | 123 | 129 | 135 | 141 | 147 | 153 | 154 | 155 | 160 | 165 | 171 | 176 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/WebController.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.redislabs.demo.brewdis.Config.StompConfig; 5 | import com.redislabs.demo.brewdis.web.BrewerySuggestion; 6 | import com.redislabs.demo.brewdis.web.Category; 7 | import com.redislabs.demo.brewdis.web.Query; 8 | import com.redislabs.demo.brewdis.web.ResultsPage; 9 | import com.redislabs.demo.brewdis.web.Style; 10 | import com.redislabs.mesclun.RedisModulesCommands; 11 | import com.redislabs.mesclun.StatefulRedisModulesConnection; 12 | import com.redislabs.mesclun.search.Document; 13 | import com.redislabs.mesclun.search.Order; 14 | import com.redislabs.mesclun.search.SearchOptions; 15 | import com.redislabs.mesclun.search.SearchResults; 16 | import com.redislabs.mesclun.search.Suggestion; 17 | import com.redislabs.mesclun.search.SuggetOptions; 18 | import lombok.extern.slf4j.Slf4j; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.web.bind.annotation.CrossOrigin; 21 | import org.springframework.web.bind.annotation.GetMapping; 22 | import org.springframework.web.bind.annotation.PostMapping; 23 | import org.springframework.web.bind.annotation.RequestBody; 24 | import org.springframework.web.bind.annotation.RequestMapping; 25 | import org.springframework.web.bind.annotation.RequestParam; 26 | import org.springframework.web.bind.annotation.RestController; 27 | 28 | import javax.servlet.http.HttpSession; 29 | import java.util.Collections; 30 | import java.util.List; 31 | import java.util.Random; 32 | import java.util.stream.Collectors; 33 | import java.util.stream.Stream; 34 | 35 | import static com.redislabs.demo.brewdis.BrewdisField.*; 36 | 37 | @RestController 38 | @RequestMapping(path = "/api") 39 | @CrossOrigin 40 | @Slf4j 41 | class WebController { 42 | 43 | private final Random random = new Random(); 44 | @Autowired 45 | private Config config; 46 | @Autowired 47 | private StatefulRedisModulesConnection connection; 48 | @Autowired 49 | private DataLoader data; 50 | private ObjectMapper mapper = new ObjectMapper(); 51 | 52 | @GetMapping("/config/stomp") 53 | public StompConfig stompConfig() { 54 | return config.getStomp(); 55 | } 56 | 57 | @PostMapping("/products") 58 | public ResultsPage products(@RequestBody Query query, 59 | @RequestParam(name = "longitude", required = true) Double longitude, 60 | @RequestParam(name = "latitude", required = true) Double latitude, HttpSession session) { 61 | log.info("Searching for products around lon={} lat={}", longitude, latitude); 62 | SearchOptions.SearchOptionsBuilder options = SearchOptions.builder() 63 | .highlight(SearchOptions.Highlight.builder().field(PRODUCT_NAME).field(PRODUCT_DESCRIPTION) 64 | .field(CATEGORY_NAME).field(STYLE_NAME).field(BREWERY_NAME) 65 | .tags(SearchOptions.Tags.builder().open("").close("").build()).build()) 66 | .limit(SearchOptions.Limit.offset(query.getOffset()).num(query.getPageSize())); 67 | if (query.getSortByField() != null) { 68 | options.sortBy(SearchOptions.SortBy.field(query.getSortByField()).order(Order.valueOf(query.getSortByDirection()))); 69 | } 70 | String queryString = query.getQuery() == null || query.getQuery().length() == 0 ? "*" : query.getQuery(); 71 | long startTime = System.currentTimeMillis(); 72 | SearchResults searchResults = connection.sync().search(config.getProduct().getIndex(), queryString, options.build()); 73 | long endTime = System.currentTimeMillis(); 74 | ResultsPage results = new ResultsPage(); 75 | results.setCount(searchResults.getCount()); 76 | results.setResults(searchResults); 77 | results.setPageIndex(query.getPageIndex()); 78 | results.setPageSize(query.getPageSize()); 79 | results.setDuration(((float) (endTime - startTime)) / 1000); 80 | generateDemand(session, longitude, latitude, searchResults); 81 | return results; 82 | } 83 | 84 | private void generateDemand(HttpSession session, Double longitude, Double latitude, SearchResults searchResults) { 85 | List skus = searchResults.stream().limit(config.getInventory().getGenerator().getSkusMax()).map(r -> r.get(PRODUCT_ID)).collect(Collectors.toList()); 86 | if (skus.isEmpty()) { 87 | log.warn("No SKUs found to generate demand"); 88 | return; 89 | } 90 | List stores = connection.sync().search(config.getStore().getIndex(), geoCriteria(longitude, latitude)).stream().limit(config.getInventory().getGenerator().getStoresMax()).map(r -> r.get(STORE_ID)).collect(Collectors.toList()); 91 | if (stores.isEmpty()) { 92 | log.warn("No store found to generate demand"); 93 | return; 94 | } 95 | RedisModulesCommands sync = connection.sync(); 96 | sync.sadd("sessions", session.getId()); 97 | String storesKey = "session:stores:" + session.getId(); 98 | sync.sadd(storesKey, stores.toArray(new String[0])); 99 | sync.expire(storesKey, config.getInventory().getGenerator().getRequestDurationInSeconds()); 100 | String skusKey = "session:skus:" + session.getId(); 101 | sync.sadd(skusKey, skus.toArray(new String[0])); 102 | sync.expire(skusKey, config.getInventory().getGenerator().getRequestDurationInSeconds()); 103 | 104 | } 105 | 106 | @GetMapping("/styles") 107 | public List 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/InventoryManager.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import com.redislabs.mesclun.RedisModulesCommands; 4 | import com.redislabs.mesclun.StatefulRedisModulesConnection; 5 | import com.redislabs.mesclun.search.*; 6 | import io.lettuce.core.RedisCommandExecutionException; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.DisposableBean; 9 | import org.springframework.beans.factory.InitializingBean; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.data.redis.connection.stream.MapRecord; 12 | import org.springframework.data.redis.connection.stream.StreamOffset; 13 | import org.springframework.data.redis.core.StringRedisTemplate; 14 | import org.springframework.data.redis.stream.StreamListener; 15 | import org.springframework.data.redis.stream.StreamMessageListenerContainer; 16 | import org.springframework.data.redis.stream.StreamMessageListenerContainer.StreamMessageListenerContainerOptions; 17 | import org.springframework.data.redis.stream.Subscription; 18 | import org.springframework.scheduling.annotation.Scheduled; 19 | import org.springframework.stereotype.Component; 20 | 21 | import java.time.Duration; 22 | import java.time.ZonedDateTime; 23 | import java.time.format.DateTimeFormatter; 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | import java.util.PrimitiveIterator; 27 | import java.util.Random; 28 | 29 | import static com.redislabs.demo.brewdis.BrewdisField.*; 30 | 31 | @Component 32 | @Slf4j 33 | public class InventoryManager implements InitializingBean, DisposableBean, StreamListener> { 34 | 35 | @Autowired 36 | private Config config; 37 | @Autowired 38 | private StatefulRedisModulesConnection connection; 39 | @Autowired 40 | private StringRedisTemplate redis; 41 | private StreamMessageListenerContainer> container; 42 | private Subscription subscription; 43 | private PrimitiveIterator.OfInt onHand; 44 | private PrimitiveIterator.OfInt allocated; 45 | private PrimitiveIterator.OfInt reserved; 46 | private PrimitiveIterator.OfInt virtualHold; 47 | 48 | @SuppressWarnings("unchecked") 49 | @Override 50 | public void afterPropertiesSet() throws Exception { 51 | Random random = new Random(); 52 | Config.InventoryGeneratorConfig generator = config.getInventory().getGenerator(); 53 | this.onHand = random.ints(generator.getOnHandMin(), generator.getOnHandMax()).iterator(); 54 | this.allocated = random.ints(generator.getAllocatedMin(), generator.getAllocatedMax()).iterator(); 55 | this.reserved = random.ints(generator.getReservedMin(), generator.getReservedMax()).iterator(); 56 | this.virtualHold = random.ints(generator.getVirtualHoldMin(), generator.getVirtualHoldMax()).iterator(); 57 | RedisModulesCommands commands = connection.sync(); 58 | String index = config.getInventory().getIndex(); 59 | log.info("Dropping {} index", index); 60 | try { 61 | commands.dropIndex(index); 62 | } catch (RedisCommandExecutionException e) { 63 | if (!e.getMessage().equals("Unknown Index name")) { 64 | throw e; 65 | } 66 | } 67 | log.info("Creating {} index", index); 68 | commands.create(index, CreateOptions.builder().prefix(config.getInventory().getKeyspace() + config.getKeySeparator()).build(), Field.tag(STORE_ID).sortable(true).build(), 69 | Field.tag(PRODUCT_ID).sortable(true).build(), 70 | Field.geo(LOCATION).build(), 71 | Field.numeric(AVAILABLE_TO_PROMISE).sortable(true).build(), 72 | Field.numeric(ON_HAND).sortable(true).build(), 73 | Field.numeric(ALLOCATED).sortable(true).build(), 74 | Field.numeric(RESERVED).sortable(true).build(), 75 | Field.numeric(VIRTUAL_HOLD).sortable(true).build(), 76 | Field.numeric(EPOCH).sortable(true).build()); 77 | commands.del(config.getInventory().getUpdateStream()); 78 | this.container = StreamMessageListenerContainer.create(redis.getConnectionFactory(), StreamMessageListenerContainerOptions.builder().pollTimeout(Duration.ofMillis(config.getStreamPollTimeout())).build()); 79 | container.start(); 80 | this.subscription = container.receive(StreamOffset.fromStart(config.getInventory().getUpdateStream()), this); 81 | subscription.await(Duration.ofSeconds(2)); 82 | } 83 | 84 | @Override 85 | public void destroy() { 86 | if (subscription != null) { 87 | subscription.cancel(); 88 | } 89 | if (container != null) { 90 | container.stop(); 91 | } 92 | } 93 | 94 | @Override 95 | public void onMessage(MapRecord message) { 96 | String store = message.getValue().get(STORE_ID); 97 | String sku = message.getValue().get(PRODUCT_ID); 98 | String id = config.concat(store, sku); 99 | String docId = config.concat(config.getInventory().getKeyspace(), id); 100 | RedisModulesCommands commands = connection.sync(); 101 | if (commands.hgetall(docId).isEmpty()) { 102 | Map productDoc = commands.hgetall(config.concat(config.getProduct().getKeyspace(), sku)); 103 | if (productDoc.isEmpty()) { 104 | log.warn("Unknown product '{}'", sku); 105 | return; 106 | } 107 | Map storeDoc = commands.hgetall(config.concat(config.getStore().getKeyspace(), store)); 108 | if (storeDoc.isEmpty()) { 109 | log.warn("Unknown store '{}'", store); 110 | return; 111 | } 112 | Map inventory = new HashMap<>(); 113 | config.getProduct().getInventoryMapping().forEach((k, v) -> inventory.put(v, productDoc.get(k))); 114 | config.getStore().getInventoryMapping().forEach((k, v) -> inventory.put(v, storeDoc.get(k))); 115 | inventory.put(ON_HAND, String.valueOf(onHand.nextInt())); 116 | inventory.put(ALLOCATED, String.valueOf(allocated.nextInt())); 117 | inventory.put(RESERVED, String.valueOf(reserved.nextInt())); 118 | inventory.put(VIRTUAL_HOLD, String.valueOf(virtualHold.nextInt())); 119 | commands.hset(docId, inventory); 120 | } 121 | Map inventory = commands.hgetall(docId); 122 | inventory.put(STORE_ID, store); 123 | inventory.put(PRODUCT_ID, sku); 124 | if (message.getValue().containsKey(ON_HAND)) { 125 | int delta = getInt(message.getValue(), ON_HAND); 126 | log.info("Received restocking for {}:{} {}={}", store, sku, DELTA, delta); 127 | int previousOnHand = getInt(inventory, ON_HAND); 128 | int onHand = previousOnHand + delta; 129 | inventory.put(ON_HAND, String.valueOf(onHand)); 130 | } 131 | if (message.getValue().containsKey(ALLOCATED)) { 132 | int delta = getInt(message.getValue(), ALLOCATED); 133 | int previousAllocated = getInt(inventory, ALLOCATED); 134 | int allocated = previousAllocated + delta; 135 | inventory.put(ALLOCATED, String.valueOf(allocated)); 136 | } 137 | int availableToPromise = availableToPromise(inventory); 138 | if (availableToPromise < 0) { 139 | return; 140 | } 141 | int delta = 0; 142 | if (inventory.containsKey(AVAILABLE_TO_PROMISE)) { 143 | int previousAvailableToPromise = getInt(inventory, AVAILABLE_TO_PROMISE); 144 | delta = availableToPromise - previousAvailableToPromise; 145 | } 146 | inventory.put(DELTA, String.valueOf(delta)); 147 | inventory.put(AVAILABLE_TO_PROMISE, String.valueOf(availableToPromise)); 148 | ZonedDateTime time = ZonedDateTime.now(); 149 | inventory.put(TIME, time.format(DateTimeFormatter.ISO_INSTANT)); 150 | inventory.put(EPOCH, String.valueOf(time.toEpochSecond())); 151 | inventory.put(LEVEL, config.getInventory().level(availableToPromise)); 152 | redis.opsForStream().add(config.getInventory().getStream(), inventory); 153 | try { 154 | commands.hset(docId, inventory); 155 | } catch (RedisCommandExecutionException e) { 156 | log.error("Could not add document {}: {}", docId, inventory, e); 157 | } 158 | } 159 | 160 | private int availableToPromise(Map inventory) { 161 | int allocated = getInt(inventory, ALLOCATED); 162 | int reserved = getInt(inventory, RESERVED); 163 | int virtualHold = getInt(inventory, VIRTUAL_HOLD); 164 | int demand = allocated + reserved + virtualHold; 165 | int supply = getInt(inventory, ON_HAND); 166 | return supply - demand; 167 | } 168 | 169 | private int getInt(Map map, String field) { 170 | return Integer.parseInt(map.getOrDefault(field, "0")); 171 | } 172 | 173 | @Scheduled(fixedRateString = "${inventory.cleanup.rate}") 174 | public void cleanup() { 175 | ZonedDateTime time = ZonedDateTime.now().minus(Duration.ofSeconds(config.getInventory().getCleanup().getAgeThreshold())); 176 | String query = "@" + EPOCH + ":[0 " + time.toEpochSecond() + "]"; 177 | String index = config.getInventory().getIndex(); 178 | RedisModulesCommands commands = connection.sync(); 179 | SearchResults results = commands.search(index, query, SearchOptions.builder().noContent(true) 180 | .limit(SearchOptions.Limit.offset(0).num(config.getInventory().getCleanup().getSearchLimit())).build()); 181 | if (!results.isEmpty()) { 182 | log.info("Deleting {} docs", results.size()); 183 | commands.del(results.stream().map(Document::getId).toArray(String[]::new)); 184 | } 185 | redis.opsForStream().trim(config.getInventory().getUpdateStream(), 186 | config.getInventory().getCleanup().getStreamTrimCount()); 187 | redis.opsForStream().trim(config.getInventory().getStream(), 188 | config.getInventory().getCleanup().getStreamTrimCount()); 189 | } 190 | 191 | } 192 | -------------------------------------------------------------------------------- /app/brewdis-api/src/main/java/com/redislabs/demo/brewdis/DataLoader.java: -------------------------------------------------------------------------------- 1 | package com.redislabs.demo.brewdis; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.redislabs.demo.brewdis.web.BrewerySuggestion; 6 | import com.redislabs.demo.brewdis.web.Category; 7 | import com.redislabs.demo.brewdis.web.Style; 8 | import com.redislabs.mesclun.RedisModulesAsyncCommands; 9 | import com.redislabs.mesclun.RedisModulesCommands; 10 | import com.redislabs.mesclun.StatefulRedisModulesConnection; 11 | import com.redislabs.mesclun.search.AggregateOptions; 12 | import com.redislabs.mesclun.search.AggregateResults; 13 | import com.redislabs.mesclun.search.CreateOptions; 14 | import com.redislabs.mesclun.search.Field; 15 | import com.redislabs.mesclun.search.IndexInfo; 16 | import com.redislabs.mesclun.search.Order; 17 | import com.redislabs.mesclun.search.RediSearchCommands; 18 | import com.redislabs.mesclun.search.RediSearchUtils; 19 | import com.redislabs.mesclun.search.SugaddOptions; 20 | import com.redislabs.mesclun.search.aggregate.GroupBy; 21 | import com.redislabs.mesclun.search.aggregate.Limit; 22 | import com.redislabs.mesclun.search.aggregate.SortBy; 23 | import com.redislabs.mesclun.search.aggregate.reducers.CountDistinct; 24 | import com.redislabs.riot.ProcessorOptions; 25 | import com.redislabs.riot.RedisOptions; 26 | import com.redislabs.riot.file.FileImportCommand; 27 | import com.redislabs.riot.file.RiotFile; 28 | import com.redislabs.riot.redis.HsetCommand; 29 | import io.lettuce.core.LettuceFutures; 30 | import io.lettuce.core.RedisCommandExecutionException; 31 | import io.lettuce.core.RedisFuture; 32 | import lombok.Getter; 33 | import lombok.extern.slf4j.Slf4j; 34 | import org.apache.commons.pool2.impl.GenericObjectPool; 35 | import org.springframework.beans.factory.InitializingBean; 36 | import org.springframework.beans.factory.annotation.Autowired; 37 | import org.springframework.beans.factory.annotation.Value; 38 | import org.springframework.boot.autoconfigure.data.redis.RedisProperties; 39 | import org.springframework.core.io.Resource; 40 | import org.springframework.expression.Expression; 41 | import org.springframework.expression.spel.standard.SpelExpressionParser; 42 | import org.springframework.stereotype.Component; 43 | 44 | import java.io.BufferedReader; 45 | import java.io.InputStreamReader; 46 | import java.nio.charset.StandardCharsets; 47 | import java.util.ArrayList; 48 | import java.util.Arrays; 49 | import java.util.Collections; 50 | import java.util.Comparator; 51 | import java.util.HashMap; 52 | import java.util.LinkedHashMap; 53 | import java.util.List; 54 | import java.util.Map; 55 | import java.util.stream.Collectors; 56 | import java.util.stream.Stream; 57 | 58 | import static com.redislabs.demo.brewdis.BrewdisField.*; 59 | 60 | @Component 61 | @Slf4j 62 | public class DataLoader implements InitializingBean { 63 | 64 | @Value("classpath:english_stopwords.txt") 65 | private Resource stopwordsResource; 66 | @Autowired 67 | private StatefulRedisModulesConnection connection; 68 | @Autowired 69 | private GenericObjectPool> pool; 70 | @Autowired 71 | private Config config; 72 | @Autowired 73 | private RedisProperties redisProperties; 74 | @Getter 75 | private List categories; 76 | @Getter 77 | private Map> styles = new HashMap<>(); 78 | private List stopwords; 79 | 80 | @Override 81 | public void afterPropertiesSet() throws Exception { 82 | this.stopwords = new BufferedReader( 83 | new InputStreamReader(stopwordsResource.getInputStream(), StandardCharsets.UTF_8)).lines() 84 | .collect(Collectors.toList()); 85 | } 86 | 87 | public void execute() throws Exception { 88 | loadStores(); 89 | loadProducts(); 90 | loadBreweries(); 91 | loadCategoriesAndStyles(); 92 | loadFoodPairings(); 93 | } 94 | 95 | @SuppressWarnings("unchecked") 96 | private void loadStores() throws Exception { 97 | RediSearchCommands commands = connection.sync(); 98 | String index = config.getStore().getIndex(); 99 | try { 100 | IndexInfo info = RediSearchUtils.getInfo(commands.indexInfo(index)); 101 | if (info.getNumDocs() >= config.getStore().getCount()) { 102 | log.info("Found {} stores - skipping load", Math.round(info.getNumDocs())); 103 | return; 104 | } 105 | commands.dropIndex(index); 106 | } catch (RedisCommandExecutionException e) { 107 | if (!e.getMessage().equals("Unknown Index name")) { 108 | throw e; 109 | } 110 | } 111 | commands.create(index, CreateOptions.builder().prefix(config.getStore().getKeyspace() + config.getKeySeparator()).build(), Field.tag(STORE_ID).sortable(true).build(), Field.text("description").build(), 112 | Field.tag("market").sortable(true).build(), Field.tag("parent").sortable(true).build(), 113 | Field.text("address").build(), Field.text("city").sortable(true).build(), 114 | Field.tag("country").sortable(true).build(), Field.tag("inventoryAvailableToSell").sortable(true).build(), 115 | Field.tag("isDefault").sortable(true).build(), Field.tag("preferred").sortable(true).build(), 116 | Field.numeric("latitude").sortable(true).build(), Field.geo(LOCATION).build(), 117 | Field.numeric("longitude").sortable(true).build(), Field.tag("rollupInventory").sortable(true).build(), 118 | Field.tag("state").sortable(true).build(), Field.tag("type").sortable(true).build(), 119 | Field.tag("postalCode").sortable(true).build()); 120 | RiotFile file = new RiotFile(); 121 | configure(file.getRedisOptions()); 122 | FileImportCommand command = new FileImportCommand(); 123 | command.setApp(file); 124 | command.setFiles(Collections.singletonList(config.getStore().getUrl())); 125 | command.getOptions().setHeader(true); 126 | ProcessorOptions processorOptions = new ProcessorOptions(); 127 | SpelExpressionParser parser = new SpelExpressionParser(); 128 | Map fields = new LinkedHashMap<>(); 129 | fields.put(LOCATION, parser.parseExpression("#geo(longitude,latitude)")); 130 | processorOptions.setSpelFields(fields); 131 | command.setProcessorOptions(processorOptions); 132 | HsetCommand hset = new HsetCommand(); 133 | hset.setKeyspace(config.getStore().getKeyspace()); 134 | hset.setKeys(new String[]{STORE_ID}); 135 | command.setRedisCommands(Collections.singletonList(hset)); 136 | command.execute(); 137 | } 138 | 139 | @SuppressWarnings("unchecked") 140 | private void loadProducts() throws Exception { 141 | RediSearchCommands commands = connection.sync(); 142 | String index = config.getProduct().getIndex(); 143 | try { 144 | IndexInfo info = RediSearchUtils.getInfo(commands.indexInfo(index)); 145 | if (info.getNumDocs() >= config.getProduct().getLoad().getCount()) { 146 | log.info("Found {} products - skipping load", Math.round(info.getNumDocs())); 147 | return; 148 | } 149 | commands.dropIndex(index); 150 | } catch (RedisCommandExecutionException e) { 151 | if (!e.getMessage().equals("Unknown Index name")) { 152 | throw e; 153 | } 154 | } 155 | commands.create(index, CreateOptions.builder().prefix(config.getProduct().getKeyspace() + config.getKeySeparator()).build(), Field.tag(PRODUCT_ID).sortable(true).build(), 156 | Field.text(PRODUCT_NAME).sortable(true).build(), 157 | Field.text(PRODUCT_DESCRIPTION).matcher(Field.Text.PhoneticMatcher.English).build(), 158 | Field.tag(PRODUCT_LABEL).build(), 159 | Field.tag(CATEGORY_ID).sortable(true).build(), 160 | Field.text(CATEGORY_NAME).build(), 161 | Field.tag(STYLE_ID).sortable(true).build(), 162 | Field.text(STYLE_NAME).build(), 163 | Field.tag(BREWERY_ID).sortable(true).build(), 164 | Field.text(BREWERY_NAME).build(), 165 | Field.text(FOOD_PAIRINGS).sortable(true).build(), 166 | Field.tag("isOrganic").sortable(true).build(), 167 | Field.numeric("abv").sortable(true).build(), 168 | Field.numeric("ibu").sortable(true).build()); 169 | RiotFile file = new RiotFile(); 170 | configure(file.getRedisOptions()); 171 | FileImportCommand command = new FileImportCommand(); 172 | command.setApp(file); 173 | command.setFiles(Collections.singletonList(config.getProduct().getUrl())); 174 | ProcessorOptions processorOptions = new ProcessorOptions(); 175 | SpelExpressionParser parser = new SpelExpressionParser(); 176 | Map fields = new LinkedHashMap<>(); 177 | fields.put(PRODUCT_ID, parser.parseExpression("id")); 178 | fields.put(PRODUCT_LABEL, parser.parseExpression("containsKey('labels')")); 179 | fields.put(CATEGORY_ID, parser.parseExpression("style.category.id")); 180 | fields.put(CATEGORY_NAME, parser.parseExpression("style.category.name")); 181 | fields.put(STYLE_NAME, parser.parseExpression("style.shortName")); 182 | fields.put(STYLE_ID, parser.parseExpression("style.id")); 183 | fields.put(BREWERY_ID, parser.parseExpression("containsKey('breweries')?breweries[0].id:null")); 184 | fields.put(BREWERY_NAME, parser.parseExpression("containsKey('breweries')?breweries[0].nameShortDisplay:null")); 185 | fields.put(BREWERY_ICON, parser.parseExpression("containsKey('breweries')?breweries[0].containsKey('images')?breweries[0].get('images').get('icon'):null:null")); 186 | processorOptions.setSpelFields(fields); 187 | command.setProcessorOptions(processorOptions); 188 | HsetCommand hset = new HsetCommand(); 189 | hset.setKeyspace(config.getProduct().getKeyspace()); 190 | hset.setKeys(new String[]{PRODUCT_ID}); 191 | command.setRedisCommands(Collections.singletonList(hset)); 192 | command.execute(); 193 | } 194 | 195 | private void configure(RedisOptions redisOptions) { 196 | redisOptions.setHost(redisProperties.getHost()); 197 | redisOptions.setPort(redisProperties.getPort()); 198 | if (redisProperties.getClientName() != null) { 199 | redisOptions.setClientName(redisProperties.getClientName()); 200 | } 201 | redisOptions.setDatabase(redisProperties.getDatabase()); 202 | if (redisProperties.getPassword() != null) { 203 | redisOptions.setPassword(redisProperties.getPassword().toCharArray()); 204 | } 205 | redisOptions.setTls(redisProperties.isSsl()); 206 | } 207 | 208 | private void loadCategoriesAndStyles() { 209 | log.info("Loading categories"); 210 | RediSearchCommands commands = connection.sync(); 211 | String index = config.getProduct().getIndex(); 212 | AggregateResults results = commands.aggregate(index, "*", 213 | AggregateOptions.builder().load(CATEGORY_NAME) 214 | .operation(GroupBy.properties(CATEGORY_ID, CATEGORY_NAME) 215 | .reducer(CountDistinct.property(PRODUCT_ID).as(COUNT).build()).build()) 216 | .build()); 217 | this.categories = results.stream() 218 | .map(r -> Category.builder().id((String) r.get(CATEGORY_ID)).name((String) r.get(CATEGORY_NAME)).build()) 219 | .sorted(Comparator.comparing(Category::getName, Comparator.nullsLast(Comparator.naturalOrder()))) 220 | .collect(Collectors.toList()); 221 | log.info("Loading styles"); 222 | this.categories.forEach(category -> { 223 | AggregateResults styleResults = commands.aggregate(index, 224 | config.tag(CATEGORY_ID, category.getId()), 225 | AggregateOptions.builder().load(STYLE_NAME) 226 | .operation(GroupBy.properties(STYLE_ID, STYLE_NAME) 227 | .reducer(CountDistinct.property(PRODUCT_ID).as(COUNT).build()).build()) 228 | .build()); 229 | List