<commit_before>import { IS_NODE, extend } from 'core/util';
import * as mat4 from 'core/util/mat4';
import Canvas from 'core/Canvas';
import Browser from 'core/Browser';

const shaders = {
    'vertexShader': `
        attribute vec3 a_position;

        attribute vec2 a_texCoord;

        uniform mat4 u_matrix;

        varying vec2 v_texCoord;

        void main() {
            gl_Position = u_matrix * vec4(a_position, 1.0);

            v_texCoord = a_texCoord;
        }
    `,
    // fragment shader, can be replaced by layer.options.fragmentShader
    'fragmentShader': `
        precision mediump float;

        uniform sampler2D u_image;

        uniform float u_opacity;

        varying vec2 v_texCoord;

        void main() {

            gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;

        }
    `
};

/**
 * A mixin providing image support in WebGL env
 * @mixin ImageGLRenderable
 * @protected
 */
const ImageGLRenderable = Base => {
    const renderable = class extends Base {

        /**
         * Draw an image at x, y at map's gl zoom
         * @param {Image|Canvas} image
         * @param {Number} x - x at map's gl zoom
         * @param {Number} y - y at map's gl zoom
         * @param {Number} w - width at map's gl zoom
         * @param {Number} h - height at map's gl zoom
         * @param {Number} opacity
         */
        drawGLImage(image, x, y, w, h, opacity) {
            const gl = this.gl;
            this.loadTexture(image);

            gl.uniformMatrix4fv(this.program['u_matrix'], false, this.getProjViewMatrix());
            gl.uniform1f(this.program['u_opacity'], opacity);
            const x1 = x;
            const x2 = x + w;
            const y1 = y;
            const y2 = y + h;
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                x1, y1, 0.0,  //0
                x2, y1, 0.0, //1
                x1, y2, 0.0, //2
                x1, y2, 0.0,  //2
                x2, y1, 0.0, //1
                x2, y2, 0.0 //3
            ]), gl.DYNAMIC_DRAW);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
        }

        /**
         * Draw the tile image as tins
         * @param {HtmlElement} image
         * @param {Array} vertices  - tin vertices
         * @param {Array} texCoords - texture coords
         * @param {Array} indices   - element indexes
         * @param {number} opacity
         */
        drawTinImage(image, vertices, texCoords, indices, opacity) {
            const gl = this.gl;
            this.loadTexture(image);
            gl.uniformMatrix4fv(this.program['u_matrix'], false, this.getProjViewMatrix());
            gl.uniform1f(this.program['u_opacity'], opacity);

            //bufferdata vertices
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.DYNAMIC_DRAW);

            //bufferdata tex coords
            gl.bindBuffer(gl.ARRAY_BUFFER, this.texBuffer);
            this.enableVertexAttrib(['a_texCoord', 2]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.DYNAMIC_DRAW);

            //bufferdata indices
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.DYNAMIC_DRAW);
            //draw
            gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
        }

        /**
         * Return map's projection view matrix
         * @returns {Float32Array}
         */
        getProjViewMatrix() {
            return this.copy16(this.getMap().projViewMatrix);
        }

        /**
         * Prepare GL canvas and context
         */
        prepareGLCanvas() {
            const map = this.getMap();
            this.glCanvas = Canvas.createCanvas(this.canvas.width, this.canvas.height, map.glCanvasClass);
            const gl = this.gl = this._createGLContext(this.glCanvas, this.layer.options['glOptions']);
            gl.clearColor(0.0, 0.0, 0.0, 0.0);

            gl.disable(gl.DEPTH_TEST);
            gl.disable(gl.STENCIL_TEST);

            gl.enable(gl.BLEND);
            gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

            this.program = this.createProgram(shaders['vertexShader'], this.layer.options['fragmentShader'] || shaders['fragmentShader'], ['u_matrix', 'u_image', 'u_opacity']);
            this.useProgram(this.program);

            // input texture vec data
            this.texBuffer = this.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, this.texBuffer);
            this.enableVertexAttrib(['a_texCoord', 2]);
            gl.bufferData(gl.ARRAY_BUFFER, this.copy12([
                0.0, 0.0,
                1.0, 0.0,
                0.0, 1.0,
                0.0, 1.0,
                1.0, 0.0,
                1.0, 1.0]), gl.STATIC_DRAW);

            this.enableSampler('u_image');

            // Enable texture unit 0
            gl.activeTexture(gl['TEXTURE0']);

            gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);

            this.posBuffer = this.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);

            // Enable indices buffer
            this.indicesBuffer = this.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indicesBuffer);
        }

        /**
         * Resize GL canvas with renderer's 2D canvas
         */
        resizeGLCanvas() {
            if (!this.glCanvas) {
                return;
            }
            if (this.glCanvas.width !== this.canvas.width || this.glCanvas.height !== this.canvas.height) {
                this.glCanvas.width = this.canvas.width;
                this.glCanvas.height = this.canvas.height;
                this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
            }
        }

        /**
         * Clear gl canvas
         */
        clearGLCanvas() {
            if (this.gl) {
                this.gl.clear(this.gl.COLOR_BUFFER_BIT);
            }
        }

        _createTexture(image) {
            const gl = this.gl;
            const texture = this.getTexture() || gl.createTexture();   // Create a texture object
            // Bind the texture object to the target
            gl.bindTexture(gl.TEXTURE_2D, texture);
            // from mapbox-gl-js
            // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

            gl.generateMipmap(gl.TEXTURE_2D);
            return texture;
        }

        /**
         * Get a texture from cache or create one if cache is empty
         * @returns {WebGLTexture}
         */
        getTexture() {
            if (!this._textures) {
                this._textures = [];
            }
            const textures = this._textures;
            return textures && textures.length > 0 ? textures.pop() : null;
        }

        /**
         * Save a texture to the cache
         * @param {WebGLTexture} texture
         */
        saveTexture(texture) {
            this._textures.push(texture);
        }

        /**
         * Load image into a text and bind it with WebGLContext
         * @param {Image|Canvas} image
         * @returns {WebGLTexture}
         */
        loadTexture(image) {
            const gl = this.gl;
            let texture = image.texture;   // Create a texture object
            if (!texture) {
                texture = this._createTexture(image);
                image.texture = texture;
            }
            gl.bindTexture(gl.TEXTURE_2D, texture);
            return texture;
        }

        /**
         * remove all the resources and remove gl canvas
         */
        removeGLCanvas() {
            // release resources
            const gl = this.gl;
            if (!gl) {
                return;
            }
            if (this._buffers) {
                this._buffers.forEach(function (b) {
                    gl.deleteBuffer(b);
                });
                delete this._buffers;
            }
            if (this._textures) {
                this._textures.forEach(t => gl.deleteTexture(t));
                delete this._textures;
            }
            delete this.posBuffer;
            const program = gl.program;
            gl.deleteProgram(program);
            gl.deleteShader(program.fragmentShader);
            gl.deleteShader(program.vertexShader);
            delete this.gl;
            delete this.glCanvas;
        }

        //----------------------- webgl utils unlike to change ---------------------------------

        /**
         * Create a WebGL buffer
         * @returns {WebGLBuffer}
         */
        createBuffer() {
            const gl = this.gl;
            // Create the buffer object
            const buffer = gl.createBuffer();
            if (!buffer) {
                throw new Error('Failed to create the buffer object');
            }
            if (!this._buffers) {
                this._buffers = [];
            }
            this._buffers.push(buffer);
            return buffer;
        }

        /**
         * Enable vertex attributes
         * @param {Array} attributes [[name, stride, type], [name, stride, type]...]
         * @example
         * rendererr.enableVertexAttrib([
         *  ['a_position', 3, 'FLOAT'],
         *  ['a_normal', 3, 'FLOAT']
         * ]);
         */
        enableVertexAttrib(attributes) {
            const gl = this.gl;
            if (Array.isArray(attributes[0])) {
                const verticesTexCoords = new Float32Array([0.0, 0.0, 0.0]);
                const FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;
                let STRIDE = 0;
                for (let i = 0; i < attributes.length; i++) {
                    STRIDE += (attributes[i][1] || 0);
                }
                let offset = 0;
                for (let i = 0; i < attributes.length; i++) {
                    const attr = gl.getAttribLocation(gl.program, attributes[i][0]);
                    if (attr < 0) {
                        throw new Error('Failed to get the storage location of ' + attributes[i][0]);
                    }
                    gl.vertexAttribPointer(attr, attributes[i][1], gl[attributes[i][2] || 'FLOAT'], false, FSIZE * STRIDE, FSIZE * offset);
                    offset += (attributes[i][1] || 0);
                    gl.enableVertexAttribArray(attr);
                }
            } else {
                const attr = gl.getAttribLocation(gl.program, attributes[0]);
                gl.vertexAttribPointer(attr, attributes[1], gl[attributes[2] || 'FLOAT'], false, 0, 0);
                gl.enableVertexAttribArray(attr);
            }
        }

        /**
         * Create the linked program object
         * @param {String} vshader a vertex shader program (string)
         * @param {String} fshader a fragment shader program (string)
         * @return {WebGLProgram} created program object, or null if the creation has failed
         */
        createProgram(vshader, fshader, uniforms) {
            const gl = this.gl;
            // Create shader object
            const vertexShader = this._compileShader(gl, gl.VERTEX_SHADER, vshader);
            const fragmentShader = this._compileShader(gl, gl.FRAGMENT_SHADER, fshader);
            if (!vertexShader || !fragmentShader) {
                return null;
            }

            // Create a program object
            const program = gl.createProgram();
            if (!program) {
                return null;
            }

            // Attach the shader objects
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);

            // Link the program object
            gl.linkProgram(program);
            gl.vertexShader = vertexShader;
            gl.fragmentShader = fragmentShader;
            // Check the result of linking
            const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
            if (!linked) {
                const error = gl.getProgramInfoLog(program);
                gl.deleteProgram(program);
                gl.deleteShader(fragmentShader);
                gl.deleteShader(vertexShader);
                throw new Error('Failed to link program: ' + error);
            }

            this._initUniforms(program, uniforms);

            return program;
        }

        /**
         * use the given program
         * @param {WebGLProgram} program
         */
        useProgram(program) {
            const gl = this.gl;
            gl.useProgram(program);
            gl.program = program;
            return this;
        }

        /**
         * Enable a sampler, and set texture
         * @param {WebGLSampler} sampler
         * @param {ptr} texture id
         */
        enableSampler(sampler, texIdx) {
            const gl = this.gl;
            const uSampler = this._getUniform(gl.program, sampler);
            if (!texIdx) {
                texIdx = 0;
            }
            // Set the texture unit to the sampler
            gl.uniform1i(uSampler, texIdx);
            return uSampler;
        }

        _createGLContext(canvas, options) {
            const attributes = {
                'alpha': true,
                'preserveDrawingBuffer' : true,
                'antialias' : false
            };
            const names = ['webgl', 'experimental-webgl'];
            let context = null;
            /* eslint-disable no-empty */
            for (let i = 0; i < names.length; ++i) {
                try {
                    context = canvas.getContext(names[i], options || attributes);
                } catch (e) {}
                if (context) {
                    break;
                }
            }
            return context;
            /* eslint-enable no-empty */
        }

        /**
         * Create a shader object
         * @param gl GL context
         * @param type the type of the shader object to be created
         * @param source shader program (string)
         * @return created shader object, or null if the creation has failed.
         */
        _compileShader(gl, type, source) {
            // Create shader object
            const shader = gl.createShader(type);
            if (shader == null) {
                throw new Error('unable to create shader');
            }

            // Set the shader program
            gl.shaderSource(shader, source);
            // Compile the shader
            gl.compileShader(shader);

            // Check the result of compilation
            const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
            if (!compiled) {
                const error = gl.getShaderInfoLog(shader);

                gl.deleteShader(shader);
                throw new Error('Failed to compile shader: ' + error);
            }

            return shader;
        }

        _initUniforms(program, uniforms) {
            for (let i = 0; i < uniforms.length; i++) {
                let name = uniforms[i];
                let uniform = uniforms[i];
                const b = name.indexOf('[');
                if (b >= 0) {
                    name = name.substring(0, b);
                    if (!IS_NODE) {
                        // In browser, remove [0] from uniforma declaration
                        uniform = uniform.substring(0, b);
                    }
                }
                program[name] = this._getUniform(program, uniform);
            }
        }

        _getUniform(program, uniformName) {
            const gl = this.gl;
            const uniform = gl.getUniformLocation(program, uniformName);
            if (!uniform) {
                throw new Error('Failed to get the storage location of ' + uniformName);
            }
            return uniform;
        }
    };

    extend(renderable.prototype, {
        copy12: function () {
            const m = Browser.ie9 ? null : new Float32Array(12);
            return function (arr) {
                return mat4.copy(m, arr);
            };
        }(),

        copy16: function () {
            const m = Browser.ie9 ? null : new Float32Array(16);
            return function (arr) {
                return mat4.copy(m, arr);
            };
        }()
    });

    return renderable;
};

export default ImageGLRenderable;

<commit_msg>not to generate texture mipmap<commit_after>import { IS_NODE, extend } from 'core/util';
import * as mat4 from 'core/util/mat4';
import Canvas from 'core/Canvas';
import Browser from 'core/Browser';

const shaders = {
    'vertexShader': `
        attribute vec3 a_position;

        attribute vec2 a_texCoord;

        uniform mat4 u_matrix;

        varying vec2 v_texCoord;

        void main() {
            gl_Position = u_matrix * vec4(a_position, 1.0);

            v_texCoord = a_texCoord;
        }
    `,
    // fragment shader, can be replaced by layer.options.fragmentShader
    'fragmentShader': `
        precision mediump float;

        uniform sampler2D u_image;

        uniform float u_opacity;

        varying vec2 v_texCoord;

        void main() {

            gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;

        }
    `
};

/**
 * A mixin providing image support in WebGL env
 * @mixin ImageGLRenderable
 * @protected
 */
const ImageGLRenderable = Base => {
    const renderable = class extends Base {

        /**
         * Draw an image at x, y at map's gl zoom
         * @param {Image|Canvas} image
         * @param {Number} x - x at map's gl zoom
         * @param {Number} y - y at map's gl zoom
         * @param {Number} w - width at map's gl zoom
         * @param {Number} h - height at map's gl zoom
         * @param {Number} opacity
         */
        drawGLImage(image, x, y, w, h, opacity) {
            const gl = this.gl;
            this.loadTexture(image);

            gl.uniformMatrix4fv(this.program['u_matrix'], false, this.getProjViewMatrix());
            gl.uniform1f(this.program['u_opacity'], opacity);
            const x1 = x;
            const x2 = x + w;
            const y1 = y;
            const y2 = y + h;
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                x1, y1, 0.0,  //0
                x2, y1, 0.0, //1
                x1, y2, 0.0, //2
                x1, y2, 0.0,  //2
                x2, y1, 0.0, //1
                x2, y2, 0.0 //3
            ]), gl.DYNAMIC_DRAW);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
        }

        /**
         * Draw the tile image as tins
         * @param {HtmlElement} image
         * @param {Array} vertices  - tin vertices
         * @param {Array} texCoords - texture coords
         * @param {Array} indices   - element indexes
         * @param {number} opacity
         */
        drawTinImage(image, vertices, texCoords, indices, opacity) {
            const gl = this.gl;
            this.loadTexture(image);
            gl.uniformMatrix4fv(this.program['u_matrix'], false, this.getProjViewMatrix());
            gl.uniform1f(this.program['u_opacity'], opacity);

            //bufferdata vertices
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.DYNAMIC_DRAW);

            //bufferdata tex coords
            gl.bindBuffer(gl.ARRAY_BUFFER, this.texBuffer);
            this.enableVertexAttrib(['a_texCoord', 2]);
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.DYNAMIC_DRAW);

            //bufferdata indices
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.DYNAMIC_DRAW);
            //draw
            gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
        }

        /**
         * Return map's projection view matrix
         * @returns {Float32Array}
         */
        getProjViewMatrix() {
            return this.copy16(this.getMap().projViewMatrix);
        }

        /**
         * Prepare GL canvas and context
         */
        prepareGLCanvas() {
            const map = this.getMap();
            this.glCanvas = Canvas.createCanvas(this.canvas.width, this.canvas.height, map.glCanvasClass);
            const gl = this.gl = this._createGLContext(this.glCanvas, this.layer.options['glOptions']);
            gl.clearColor(0.0, 0.0, 0.0, 0.0);

            gl.disable(gl.DEPTH_TEST);
            gl.disable(gl.STENCIL_TEST);

            gl.enable(gl.BLEND);
            gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

            this.program = this.createProgram(shaders['vertexShader'], this.layer.options['fragmentShader'] || shaders['fragmentShader'], ['u_matrix', 'u_image', 'u_opacity']);
            this.useProgram(this.program);

            // input texture vec data
            this.texBuffer = this.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, this.texBuffer);
            this.enableVertexAttrib(['a_texCoord', 2]);
            gl.bufferData(gl.ARRAY_BUFFER, this.copy12([
                0.0, 0.0,
                1.0, 0.0,
                0.0, 1.0,
                0.0, 1.0,
                1.0, 0.0,
                1.0, 1.0]), gl.STATIC_DRAW);

            this.enableSampler('u_image');

            // Enable texture unit 0
            gl.activeTexture(gl['TEXTURE0']);

            gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);

            this.posBuffer = this.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, this.posBuffer);
            this.enableVertexAttrib(['a_position', 3]);

            // Enable indices buffer
            this.indicesBuffer = this.createBuffer();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indicesBuffer);
        }

        /**
         * Resize GL canvas with renderer's 2D canvas
         */
        resizeGLCanvas() {
            if (!this.glCanvas) {
                return;
            }
            if (this.glCanvas.width !== this.canvas.width || this.glCanvas.height !== this.canvas.height) {
                this.glCanvas.width = this.canvas.width;
                this.glCanvas.height = this.canvas.height;
                this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
            }
        }

        /**
         * Clear gl canvas
         */
        clearGLCanvas() {
            if (this.gl) {
                this.gl.clear(this.gl.COLOR_BUFFER_BIT);
            }
        }

        _createTexture(image) {
            const gl = this.gl;
            const texture = this.getTexture() || gl.createTexture();   // Create a texture object
            // Bind the texture object to the target
            gl.bindTexture(gl.TEXTURE_2D, texture);
            // from mapbox-gl-js
            // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

            // gl.generateMipmap(gl.TEXTURE_2D);
            return texture;
        }

        /**
         * Get a texture from cache or create one if cache is empty
         * @returns {WebGLTexture}
         */
        getTexture() {
            if (!this._textures) {
                this._textures = [];
            }
            const textures = this._textures;
            return textures && textures.length > 0 ? textures.pop() : null;
        }

        /**
         * Save a texture to the cache
         * @param {WebGLTexture} texture
         */
        saveTexture(texture) {
            this._textures.push(texture);
        }

        /**
         * Load image into a text and bind it with WebGLContext
         * @param {Image|Canvas} image
         * @returns {WebGLTexture}
         */
        loadTexture(image) {
            const gl = this.gl;
            let texture = image.texture;   // Create a texture object
            if (!texture) {
                texture = this._createTexture(image);
                image.texture = texture;
            }
            gl.bindTexture(gl.TEXTURE_2D, texture);
            return texture;
        }

        /**
         * remove all the resources and remove gl canvas
         */
        removeGLCanvas() {
            // release resources
            const gl = this.gl;
            if (!gl) {
                return;
            }
            if (this._buffers) {
                this._buffers.forEach(function (b) {
                    gl.deleteBuffer(b);
                });
                delete this._buffers;
            }
            if (this._textures) {
                this._textures.forEach(t => gl.deleteTexture(t));
                delete this._textures;
            }
            delete this.posBuffer;
            const program = gl.program;
            gl.deleteProgram(program);
            gl.deleteShader(program.fragmentShader);
            gl.deleteShader(program.vertexShader);
            delete this.gl;
            delete this.glCanvas;
        }

        //----------------------- webgl utils unlike to change ---------------------------------

        /**
         * Create a WebGL buffer
         * @returns {WebGLBuffer}
         */
        createBuffer() {
            const gl = this.gl;
            // Create the buffer object
            const buffer = gl.createBuffer();
            if (!buffer) {
                throw new Error('Failed to create the buffer object');
            }
            if (!this._buffers) {
                this._buffers = [];
            }
            this._buffers.push(buffer);
            return buffer;
        }

        /**
         * Enable vertex attributes
         * @param {Array} attributes [[name, stride, type], [name, stride, type]...]
         * @example
         * rendererr.enableVertexAttrib([
         *  ['a_position', 3, 'FLOAT'],
         *  ['a_normal', 3, 'FLOAT']
         * ]);
         */
        enableVertexAttrib(attributes) {
            const gl = this.gl;
            if (Array.isArray(attributes[0])) {
                const verticesTexCoords = new Float32Array([0.0, 0.0, 0.0]);
                const FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;
                let STRIDE = 0;
                for (let i = 0; i < attributes.length; i++) {
                    STRIDE += (attributes[i][1] || 0);
                }
                let offset = 0;
                for (let i = 0; i < attributes.length; i++) {
                    const attr = gl.getAttribLocation(gl.program, attributes[i][0]);
                    if (attr < 0) {
                        throw new Error('Failed to get the storage location of ' + attributes[i][0]);
                    }
                    gl.vertexAttribPointer(attr, attributes[i][1], gl[attributes[i][2] || 'FLOAT'], false, FSIZE * STRIDE, FSIZE * offset);
                    offset += (attributes[i][1] || 0);
                    gl.enableVertexAttribArray(attr);
                }
            } else {
                const attr = gl.getAttribLocation(gl.program, attributes[0]);
                gl.vertexAttribPointer(attr, attributes[1], gl[attributes[2] || 'FLOAT'], false, 0, 0);
                gl.enableVertexAttribArray(attr);
            }
        }

        /**
         * Create the linked program object
         * @param {String} vshader a vertex shader program (string)
         * @param {String} fshader a fragment shader program (string)
         * @return {WebGLProgram} created program object, or null if the creation has failed
         */
        createProgram(vshader, fshader, uniforms) {
            const gl = this.gl;
            // Create shader object
            const vertexShader = this._compileShader(gl, gl.VERTEX_SHADER, vshader);
            const fragmentShader = this._compileShader(gl, gl.FRAGMENT_SHADER, fshader);
            if (!vertexShader || !fragmentShader) {
                return null;
            }

            // Create a program object
            const program = gl.createProgram();
            if (!program) {
                return null;
            }

            // Attach the shader objects
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);

            // Link the program object
            gl.linkProgram(program);
            gl.vertexShader = vertexShader;
            gl.fragmentShader = fragmentShader;
            // Check the result of linking
            const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
            if (!linked) {
                const error = gl.getProgramInfoLog(program);
                gl.deleteProgram(program);
                gl.deleteShader(fragmentShader);
                gl.deleteShader(vertexShader);
                throw new Error('Failed to link program: ' + error);
            }

            this._initUniforms(program, uniforms);

            return program;
        }

        /**
         * use the given program
         * @param {WebGLProgram} program
         */
        useProgram(program) {
            const gl = this.gl;
            gl.useProgram(program);
            gl.program = program;
            return this;
        }

        /**
         * Enable a sampler, and set texture
         * @param {WebGLSampler} sampler
         * @param {ptr} texture id
         */
        enableSampler(sampler, texIdx) {
            const gl = this.gl;
            const uSampler = this._getUniform(gl.program, sampler);
            if (!texIdx) {
                texIdx = 0;
            }
            // Set the texture unit to the sampler
            gl.uniform1i(uSampler, texIdx);
            return uSampler;
        }

        _createGLContext(canvas, options) {
            const attributes = {
                'alpha': true,
                'preserveDrawingBuffer' : true,
                'antialias' : false
            };
            const names = ['webgl', 'experimental-webgl'];
            let context = null;
            /* eslint-disable no-empty */
            for (let i = 0; i < names.length; ++i) {
                try {
                    context = canvas.getContext(names[i], options || attributes);
                } catch (e) {}
                if (context) {
                    break;
                }
            }
            return context;
            /* eslint-enable no-empty */
        }

        /**
         * Create a shader object
         * @param gl GL context
         * @param type the type of the shader object to be created
         * @param source shader program (string)
         * @return created shader object, or null if the creation has failed.
         */
        _compileShader(gl, type, source) {
            // Create shader object
            const shader = gl.createShader(type);
            if (shader == null) {
                throw new Error('unable to create shader');
            }

            // Set the shader program
            gl.shaderSource(shader, source);
            // Compile the shader
            gl.compileShader(shader);

            // Check the result of compilation
            const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
            if (!compiled) {
                const error = gl.getShaderInfoLog(shader);

                gl.deleteShader(shader);
                throw new Error('Failed to compile shader: ' + error);
            }

            return shader;
        }

        _initUniforms(program, uniforms) {
            for (let i = 0; i < uniforms.length; i++) {
                let name = uniforms[i];
                let uniform = uniforms[i];
                const b = name.indexOf('[');
                if (b >= 0) {
                    name = name.substring(0, b);
                    if (!IS_NODE) {
                        // In browser, remove [0] from uniforma declaration
                        uniform = uniform.substring(0, b);
                    }
                }
                program[name] = this._getUniform(program, uniform);
            }
        }

        _getUniform(program, uniformName) {
            const gl = this.gl;
            const uniform = gl.getUniformLocation(program, uniformName);
            if (!uniform) {
                throw new Error('Failed to get the storage location of ' + uniformName);
            }
            return uniform;
        }
    };

    extend(renderable.prototype, {
        copy12: function () {
            const m = Browser.ie9 ? null : new Float32Array(12);
            return function (arr) {
                return mat4.copy(m, arr);
            };
        }(),

        copy16: function () {
            const m = Browser.ie9 ? null : new Float32Array(16);
            return function (arr) {
                return mat4.copy(m, arr);
            };
        }()
    });

    return renderable;
};

export default ImageGLRenderable;

<|endoftext|>


<commit_before>/* jshint camelcase: false */

var bsgridster = function(gridsterBoxes) {

	'use strict';

	gridsterBoxes = _.sortBy(gridsterBoxes, function(box) {
		return box.col;
	});

	function makeBox(width, height, isRow) {
		var boxElem = document.createElement('div');
		var widthClass = 'col-md-' + width.toString();

		boxElem.className = widthClass + ' graybox';

		if (isRow) {
			boxElem.className += '';
		}

		boxElem.style.minHeight = (height * 50).toString() + 'px';

		return boxElem;
	}

	function getChildren(parent) {
		return _.chain(gridsterBoxes)
			.filter(function(child) {
				return child.col >= parent.col &&
					(child.size_x + child.col - 1) <= (parent.size_x + parent.col - 1) &&
					child.row === (parent.row + parent.size_y); // is a child and not a grandchild
			})
			.sortBy(function(child) {
				return child.row;
			})
			.value();
	}

	function makeContainer(box, widthOverride) {
		var ratio = 12 / box.size_x; // bootstrap to gridster ratio

		var parentBoxContainer = makeBox(box.row===1 ? box.size_x : widthOverride, 0, true); // this contains the box box and it's children
		var parentBox = makeBox(box.size_x * ratio, box.size_y);

		parentBoxContainer.appendChild(parentBox);
		this.appendChild(parentBoxContainer);

		_.each(box.children, function(child) {
			if(child.children.length > 0) {
				makeContainer.call(parentBoxContainer, child, (child.size_x/this.size_x)*12);
			} else {
				var childBox = makeBox(child.size_x * ratio, child.size_y);
				parentBoxContainer.appendChild(childBox);
			}
		}, box);
	}

	function html() {
		var containerElem = document.createElement('div');

		_.each(gridsterBoxes, function(box) {
			box.children = getChildren(box);
		});

		var firstRowBoxes = _.filter(gridsterBoxes, function(box) {
			return box.row === 1;
		});

		_.each(firstRowBoxes, makeContainer, containerElem);

		console.log(firstRowBoxes);
		return containerElem;
	}

	return {
		getHtml: html
	};
};
<commit_msg>fixed x-y and offset positioning with media queries<commit_after>/*
	gridsterBoxes: an array of serialized gridster boxes
	unitHeight: height of a single gridster box in pixes
*/

var bsgridster = function(gridsterBoxes, unitHeight) {
	'use strict';

	if (!unitHeight) {
		unitHeight = 50;
	}

	document.querySelector('style').textContent +=
    '@media (min-width: 992px) { .row {height:'+unitHeight.toString()+'px;}}';

	gridsterBoxes = _.sortBy(gridsterBoxes, function(box) {
		return box.col;
	});

	function makeBox(width, height, offset) {
		var boxElem = document.createElement('div');
		boxElem.className = 'graybox';

		boxElem.className += ' col-md-' + width.toString();

		if(offset>0) {
			boxElem.className += ' col-md-offset-' + offset.toString();
		}

		boxElem.style.minHeight = (height * unitHeight).toString() + 'px';

		return boxElem;
	}

	function makeRow() {
		var rowElem = document.createElement('div');
		rowElem.className = 'row col-md-12 fifty';
		return rowElem;
	}

	function html() {
		var containerElem = document.createElement('div');
		var rows = [];

		var groupedBoxes = _.groupBy(gridsterBoxes, function(box) {
			return box.row;
		});

		var maxRow = (_.max(gridsterBoxes, function(box) {
			return box.row;
		})).row;

		_.times(maxRow, function(n) {
			rows.push({row: n, elem: makeRow()});
		});

		_.each(groupedBoxes, function (boxes, row) {
			var rowElem = rows[row-1].elem;

			_.each(boxes, function (box, index, boxesInRow) {
				var immediateLeftBox = boxesInRow[index-1];
				var offset = 0;

				if(immediateLeftBox) {
					offset = box.col - (immediateLeftBox.col+immediateLeftBox.size_x);
				} else {
					offset = box.col-1;
				}

				var boxElem = makeBox(box.size_x, box.size_y, offset);
				rowElem.appendChild(boxElem);
			});
		});

		_.each(rows, function(row) {
			containerElem.appendChild(row.elem);
		});

		return containerElem;
	}

	return {
		getHtml: html
	};
};
<|endoftext|>


<commit_before>import entities.Entity as Entity;
import entities.EntityPool as EntityPool;

import src.conf.minionConfig as minionConfig;
import src.views.elements.MinionView as MinionView;

var BG_WIDTH = G_BG_WIDTH;
var BG_HEIGHT = G_BG_HEIGHT;
var MINION_WIDTH = minionConfig.viewBounds.w;
var MINION_HEIGHT = minionConfig.viewBounds.h;
var MINION_OFFSET_X = 2.5 * MINION_WIDTH;
var MINION_OFFSET_Y = 350;
var MINION_COUNT = 3;
var MINION_JUMP_VY = -0.8;

var gameView;
var abs = Math.abs;
var min = Math.min;
var max = Math.max;

var Minion = Class(Entity, function() {
	var sup = Entity.prototype;
	this.name = "Minion";
	this.viewClass = MinionView;

	this.reset = function(x, y, config) {
		this.id = config.id;
		this.offsetX = x;
		this.setState(STATES.FALLING);

		sup.reset.call(this, x, y, config);
	};

	this.resetView = function(config) {
		sup.resetView.call(this, config);
		this.view.reset(this);
	};

	this.update = function(dt) {
		sup.update.call(this, dt);

		if (this.y > this.yPrev) {
			this.setState(STATES.FALLING);
		}

		gameView.platforms.onAllCollisions(this, this.onPlatformCollide, this);

		var offX = this.pool.getMinionOffsetX(this.poolIndex);
		if (this.offsetX !== offX) {
			var dx = (offX - this.offsetX) / 30;
			this.offsetX += dx;
			this.x += dx;
		}

		if (this.y > BG_HEIGHT) {
			this.setState(STATES.DEAD);
		}
	};

	this.updateView = function(dt) {
		var s = this.view.style;
		var b = this.viewBounds;
		s.x = this.x + b.x - this.pool.screenX;
		s.y = this.y + b.y;
	};

	this.onPlatformCollide = function(platform) {
		var x = this.x;
		var y = this.y;
		this.resolveCollidingStateWith(platform);
		if (this.y < y) {
			this.setState(STATES.RUNNING);
		}
	};

	this.setState = function(state) {
		this.state = state;
		state.onStateSet(this);
	};

	this.isAlive = function() {
		return this.state !== STATES.DEAD;
	};
});

var STATES = exports.STATES = {
	FALLING: {
		onStateSet: function(minion) {},
		onSwipe: function(minion, swipeType) {}
	},
	JUMPING: {
		onStateSet: function(minion) {
			minion.vy += MINION_JUMP_VY;
		},
		onSwipe: function(minion, swipeType) {}
	},
	RUNNING: {
		onStateSet: function(minion) {
			minion.vy = 0;
		},
		onSwipe: function(minion, swipeType) {
			if (swipeType === "up") {
				minion.setState(STATES.JUMPING);
			}
		}
	},
	DEAD: {
		onStateSet: function(minion) {
			minion.release();
		},
		onSwipe: function(minion, swipeType) {}
	}
};

exports = Class(EntityPool, function() {
	var sup = EntityPool.prototype;
	var zIndex = 0;

	this.init = function(opts) {
		gameView = opts.gameView;
		zIndex = opts.zIndex;
		opts.ctor = Minion;
		sup.init.call(this, opts);
	};

	this.reset = function() {
		sup.reset.call(this);

		this.screenX = 0;

		for (var i = 0; i < MINION_COUNT; i++) {
			var x = this.getMinionOffsetX(i);
			var y = MINION_OFFSET_Y;
			var config = merge({ zIndex: zIndex }, minionConfig);
			config = merge(config, minionConfig.types[i]);
			var minion = this.obtain(x, y, config);
		}
	};

	this.update = function(dt) {
		sup.update.call(this, dt);

		this.screenX += dt * minionConfig.vx;
	};

	this.onSwipe = function(swipeType) {
		this.forEachActiveEntity(function(minion, i) {
			minion.state.onSwipe(minion, swipeType);
		}, this);
	};

	this.getLeadMinion = function(alive) {
		var lead = null;
		var xMax = 0;
		this.forEachActiveEntity(function(minion, i) {
			if (minion.x >= xMax && (!alive || minion.isAlive())) {
				lead = minion;
				xMax = minion.x;
			}
		}, this);
		return lead;
	};

	this.getLastMinion = function(alive) {
		var last = null;
		var xMin = 0;
		this.forEachActiveEntity(function(minion, i) {
			if (!last || minion.x <= xMin) {
				if (!alive || minion.isAlive()) {
					last = minion;
					xMin = minion.x;
				}
			}
		}, this);
		return last;
	};

	this.getMinionOffsetX = function(i) {
		return MINION_OFFSET_X * (MINION_COUNT - i) / MINION_COUNT - MINION_WIDTH;
	};
});
<commit_msg>jump delays for later dudes<commit_after>import entities.Entity as Entity;
import entities.EntityPool as EntityPool;

import src.conf.minionConfig as minionConfig;
import src.views.elements.MinionView as MinionView;

var BG_WIDTH = G_BG_WIDTH;
var BG_HEIGHT = G_BG_HEIGHT;
var MINION_WIDTH = minionConfig.viewBounds.w;
var MINION_HEIGHT = minionConfig.viewBounds.h;
var MINION_OFFSET_X = 2.5 * MINION_WIDTH;
var MINION_OFFSET_Y = 350;
var MINION_COUNT = 3;
var MINION_JUMP_VY = -0.8;

var gameView;
var abs = Math.abs;
var min = Math.min;
var max = Math.max;

var Minion = Class(Entity, function() {
	var sup = Entity.prototype;
	this.name = "Minion";
	this.viewClass = MinionView;

	this.reset = function(x, y, config) {
		this.id = config.id;
		this.offsetX = x;
		this.setState(STATES.FALLING);

		sup.reset.call(this, x, y, config);
	};

	this.resetView = function(config) {
		sup.resetView.call(this, config);
		this.view.reset(this);
	};

	this.update = function(dt) {
		sup.update.call(this, dt);

		if (this.y > this.yPrev) {
			this.setState(STATES.FALLING);
		}

		gameView.platforms.onAllCollisions(this, this.onPlatformCollide, this);

		var offX = this.pool.getMinionOffsetX(this.poolIndex);
		if (this.offsetX !== offX) {
			var dx = (offX - this.offsetX) / 30;
			this.offsetX += dx;
			this.x += dx;
		}

		if (this.y > BG_HEIGHT) {
			this.setState(STATES.DEAD);
		}
	};

	this.updateView = function(dt) {
		var s = this.view.style;
		var b = this.viewBounds;
		s.x = this.x + b.x - this.pool.screenX;
		s.y = this.y + b.y;
	};

	this.onPlatformCollide = function(platform) {
		var x = this.x;
		var y = this.y;
		this.resolveCollidingStateWith(platform);
		if (this.y < y) {
			this.setState(STATES.RUNNING);
		}
	};

	this.setState = function(state) {
		this.state = state;
		state.onStateSet(this);
	};

	this.isAlive = function() {
		return this.state !== STATES.DEAD;
	};
});

var STATES = exports.STATES = {
	FALLING: {
		onStateSet: function(minion) {},
		onSwipe: function(minion, swipeType) {}
	},
	JUMPING: {
		onStateSet: function(minion) {
			minion.vy += MINION_JUMP_VY;
		},
		onSwipe: function(minion, swipeType) {}
	},
	RUNNING: {
		onStateSet: function(minion) {
			minion.vy = 0;
		},
		onSwipe: function(minion, swipeType) {
			if (swipeType === "up") {
				minion.setState(STATES.JUMPING);
			}
		}
	},
	DEAD: {
		onStateSet: function(minion) {
			minion.release();
		},
		onSwipe: function(minion, swipeType) {}
	}
};

exports = Class(EntityPool, function() {
	var sup = EntityPool.prototype;
	var zIndex = 0;

	this.init = function(opts) {
		gameView = opts.gameView;
		zIndex = opts.zIndex;
		opts.ctor = Minion;
		sup.init.call(this, opts);
	};

	this.reset = function() {
		sup.reset.call(this);

		this.screenX = 0;

		for (var i = 0; i < MINION_COUNT; i++) {
			var x = this.getMinionOffsetX(i);
			var y = MINION_OFFSET_Y;
			var config = merge({ zIndex: zIndex }, minionConfig);
			config = merge(config, minionConfig.types[i]);
			var minion = this.obtain(x, y, config);
		}
	};

	this.update = function(dt) {
		sup.update.call(this, dt);

		this.screenX += dt * minionConfig.vx;
	};

	this.onSwipe = function(swipeType) {
		this.forEachActiveEntity(function(minion, i) {
			var dist = minion.poolIndex * MINION_OFFSET_X / MINION_COUNT;
			var delay = dist / minion.vx;
			setTimeout(function() {
				minion.state.onSwipe(minion, swipeType);
			}, delay);
		}, this);
	};

	this.getLeadMinion = function(alive) {
		var lead = null;
		var xMax = 0;
		this.forEachActiveEntity(function(minion, i) {
			if (minion.x >= xMax && (!alive || minion.isAlive())) {
				lead = minion;
				xMax = minion.x;
			}
		}, this);
		return lead;
	};

	this.getLastMinion = function(alive) {
		var last = null;
		var xMin = 0;
		this.forEachActiveEntity(function(minion, i) {
			if (!last || minion.x <= xMin) {
				if (!alive || minion.isAlive()) {
					last = minion;
					xMin = minion.x;
				}
			}
		}, this);
		return last;
	};

	this.getMinionOffsetX = function(i) {
		return MINION_OFFSET_X * (MINION_COUNT - i) / MINION_COUNT - MINION_WIDTH;
	};
});
<|endoftext|>


<commit_before>'use strict'
var DLModels = require('bateeq-models');
var map = DLModels.map;
var ObjectId = require('mongodb').ObjectId;
var sqlConnect = require('./sqlConnect');
var BaseManager = require('module-toolkit').BaseManager;
var MongoClient = require('mongodb').MongoClient,
    test = require('assert');
var ItemManager = require('../../src/managers/master/item-manager');
var BankManager = require('../../src/managers/master/bank-manager');
var CardTypeManager = require('../../src/managers/master/card-type-manager');
var StoreManager = require('../../src/managers/master/store-manager');
var SalesManager = require('../../src/managers/sales/sales-manager');

module.exports = class SalesDataEtl extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.ItemManager = new ItemManager(db, user);
        this.BankManager = new BankManager(db, user);
        this.CardTypeManager = new CardTypeManager(db, user);
        this.StoreManager = new StoreManager(db, user);
        this.SalesManager = new SalesManager(db, user);

        this.collectionItem = this.ItemManager.collection;
        this.collectionBank = this.BankManager.collection;
        this.collectionStore = this.StoreManager.collection;
        this.collectionCardType = this.CardTypeManager.collection;
        this.collectionSalesManager = this.SalesManager.collection;
        this.collection = this.db.collection("sales-docs.temp");
        this.collectionLog = this.db.collection("migration.log");

    }

    CheckData() {
        return new Promise((resolve, reject) => {
            this.collectionSalesManager.find({}).toArray(function (err, sales) {
                return (sales);

            });

        });
    }

    getDataSales() {
        return new Promise((resolve, reject) => {
            sqlConnect.getConnect()
                .then((request) => {
                    var self = this;

                    var CountRows = "select count(*) as MaxLength from (select ROW_NUMBER() OVER(ORDER BY branch, nomor) AS number,branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin,sum(qty)as totalProduct, max(TOTAL) as subTotal,max(TOTAL) as grandTotal,0 as discount,'' as reference , max(voucher) as voucher, max(cash) as cash, max(debit) as debit,max(credit) as credit from penjualan group by branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin)a WHERE branch= 'SLO.02' OR branch='SLO.03'";

                    // var CountRows = "select count(*) as MaxLength from (select ROW_NUMBER() OVER(ORDER BY branch, nomor) AS number,branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin,sum(qty)as totalProduct, max(TOTAL) as subTotal,max(TOTAL) as grandTotal,0 as discount,'' as reference , max(voucher) as voucher, max(cash) as cash, max(debit) as debit,max(credit) as credit from penjualan group by branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin)a where nomor like '%201305%' and branch ='SLO.01'";

                    request.query(CountRows, function (err, salesResult) {
                        // var a = [];
                        if (err) {
                            console.log(err);
                            reject(err);
                        }
                        else {
                            var _start = new Date().getTime();
                            var date = new Date();

                            self.collectionLog.insert({ "migration": "sql to sales-docs.temp ", "_createdDate": date, "_start": date });
                            var MaxLength = salesResult[0].MaxLength;
                            // var testPage = 5;
                            // self.collection.find({});

                            var dataRows = MaxLength;

                            var numberOfPage = Math.ceil(MaxLength / dataRows);

                            var process = [];
                            for (var i = 1; i <= numberOfPage; i++) {
                                process.push(self.migrateDataSales(request, i, dataRows))
                            }

                            Promise.all(process).then(results => {

                                var end = new Date();
                                var _end = new Date().getTime();
                                var time = _end - _start;
                                var log = {
                                    "migration": "sql to sales-docs.temp ",
                                    "_createdDate": date,
                                    "_start": date,
                                    "_end": end,
                                    "Execution time": time + ' ms',
                                };
                                self.collectionLog.updateOne({ "_start": date }, log);
                                resolve(results);

                            }).catch(error => {
                                console.log(error);
                                reject(error);
                            });
                        }
                    })
                });
        });
    }

    getDataMongo(code) {
        return new Promise((resolve, reject) => {
            this.collectionSalesManager.find({ "code": code }).toArray(function (err, sales) {
                resolve(sales);
            });

        });
    }

    getStore(branch) {
        return new Promise((resolve, reject) => {

            this.collectionStore.find({ "code": branch }).toArray(function (err, store) {
                resolve(store[0]);
            });

        });
    }

    getBanks(kartu) {
        return new Promise((resolve, reject) => {
            this.collectionBank.find({ "code": "BA-" + kartu }).toArray(function (err, Banks) {
                resolve(Banks[0]);
            });

        });
    }

    getCards(CardType) {
        return new Promise((resolve, reject) => {

            this.collectionCardType.find({ "name": CardType }).toArray(function (err, card) {

                resolve(card[0]);
            });

        });
    }

    migrateDataSales(request, pageNumber, dataRows) {
        var self = this;
        return new Promise((resolve, reject) => {

            var query = "exec pagination_sales_test " + pageNumber + "," + dataRows + " ";

            request.query(query, function (err, salesData) {
                if (!err) {
                    var tasks = [];
                    for (var sales of salesData) {
                        tasks.push(self.CreateData(request, sales));
                    }

                    Promise.all(tasks)
                        .then((task) => {
                            // self.collection.insertMany(task);
                            console.log(task);
                            resolve(task);
                        })
                        .catch(error => {

                            console.log("Error : " + error);
                            reject(error);
                        });
                } else {
                    reject(err);
                }
            });
        });
    }

    CreateData(request, sales) {
        return new Promise((resolve, reject) => {

            var paymentType = "Cash";
            if ((sales.payment.trim() == "DEBIT CARD") || (sales.payment.trim() == "CREDIT CARD")) {
                paymentType = "Card";
            }
            else if ((sales.payment.trim() == "PARTIAL DEBIT CARD") || (sales.payment.trim() == "PARTIAL CREDIT CARD")) {
                paymentType = "Partial";
            } else {
                paymentType = "Cash";
            };

            var cardTemp = "";
            if ((sales.payment.trim() == "DEBIT CARD") || (sales.payment.trim() == "PARTIAL DEBIT CARD")) {
                cardTemp = "Debit";
            } else if ((sales.payment.trim() == "CREDIT CARD") || (sales.payment.trim() == "PARTIAL CREDIT CARD")) {
                cardTemp = "Credit";
            } else {
                cardTemp = "";
            };

            var CardType = "";
            if ((sales.no_krt[0] == 5) && ((sales.no_krt[1] == 1) || (sales.no_krt[1] == 2) || (sales.no_krt[1] == 3) || (sales.no_krt[1] == 4) || (sales.no_krt[1] == 5))) {

                CardType = "Mastercard";
            } else if ((sales.no_krt[0] == 2) && ((sales.no_krt[1] == 2) || (sales.no_krt[1] == 3) || (sales.no_krt[1] == 4) || (sales.no_krt[1] == 5) || (sales.no_krt[1] == 6) || (sales.no_krt[1] == 7))) {
                CardType = "Mastercard";

            } else if (sales.no_krt[0] == 4) {
                CardType = "Visa";

            } else {
                CardType = "";
            };

            var BankName = "-"
            if ((sales.kartu.trim() == "") && (sales.payment.toLowerCase() != "cash")) {
                BankName = "-";
            } else {
                BankName = sales.kartu.trim();
            }

            var _id = new ObjectId();

            var _stamp = new ObjectId();

            // var kartu = sales.kartu.trim();
            // if (kartu.indexOf("/") != -1) {
            //     kartu = kartu.substring(0, kartu.indexOf("/"));
            // } else {
            //     kartu = sales.kartu.trim();
            // }

            var store = this.getStore(sales.branch);
            var items = this.getItems(request, sales.branch, sales.nomor, sales.pos.trim());
            var banks = this.getBanks(sales.kartu);
            // var banks = this.getBanks(kartu);
            var cards = this.getCards(CardType);
            var cardBanks = this.getBanks("-");

            Promise.all([store, items, banks, cards, cardBanks]).then(data => {

                var salesArr = [];
                var salesData = {
                    "_id": _id,
                    "_stamp": _stamp,
                    "_type": "sales-doc",
                    "_version": "1.0.0",
                    "_active": true,
                    "_deleted": false,
                    "_createdBy": sales.userin.trim(),
                    "_createdDate": sales.tglin,
                    // "_createdDate": new Date(),
                    "_createAgent": "manager",
                    "_updatedBy": "router",
                    "_updatedDate": new Date(),
                    "_updateAgent": "manager",
                    "code": sales.nomor,
                    "date": sales.tanggal,
                    "totalProduct": sales.totalProduct,
                    "subTotal": sales.subTotal,
                    "discount": sales.discount,
                    "grandTotal": parseInt(sales.grandTotal),
                    "reference": sales.reference,
                    "shift": parseInt(sales.shift),
                    "pos": sales.pos.trim(),

                    "storeId": data[0]._id,
                    "store": data[0],
                    "items": data[1],

                    "salesDetail":
                    {
                        "_stamp": new ObjectId(),
                        "_type": "sales-type",
                        "_version": "1.0.0",
                        "_active": true,
                        "deleted": false,
                        "_createdBy": "router",
                        "_createdDate": new Date(),
                        "_createAgent": "manager",
                        "_updatedBy": "router",
                        "_updatedDate": new Date(),
                        "_updateAgent": "manager",
                        "paymentType": paymentType,
                        "voucherId": {},
                        "voucher": {
                            "value": parseInt(sales.voucher),
                        },
                        "bankId": (paymentType == "Cash") ? {} : ((data[2]) ? data[2]._id : {}), //query penjualan.kartu
                        "bank": (paymentType == "Cash") ? {} : ((data[2]) ? data[2] : {}),
                        "cardTypeId": (cardTemp == "Debit") ? {} : ((data[3]) ? data[3]._id : {}),
                        "cardType": (cardTemp == "Debit") ? {} : ((data[3]) ? data[3] : {}),

                        // "cardTypeId": (_card) ? _card._id : {},
                        // "cardType": (_card) ? _card : {},

                        "bankCardId": (paymentType == "Cash") ? {} : ((data[4]) ? data[4]._id : {}),
                        "bankCard": (paymentType == "Cash") ? {} : ((data[4]) ? data[4] : {}),
                        "card": cardTemp,
                        "cardNumber": sales.no_krt.trim(),
                        "cardName": "",
                        "cashAmount": parseInt(sales.cash),
                        "cardAmount": parseInt(sales.debit) + parseInt(sales.credit),
                    },
                    "remark": "",
                    "isReturn": false,
                    "isVoid": false,
                }
                salesArr.push(salesData);
                resolve(this.collection.insertMany(salesArr));
            })

        })
    }

    getStore(branch) {
        return new Promise((resolve, reject) => {

            this.collectionStore.find({ "code": branch }).toArray(function (err, store) {
                resolve(store[0]);
            });

        });
    }

    getBanks(kartu) {
        return new Promise((resolve, reject) => {
            this.collectionBank.find({ "code": "BA-" + kartu }).toArray(function (err, Banks) {
                resolve(Banks[0]);
            });

        });
    }

    getCards(CardType) {
        return new Promise((resolve, reject) => {

            this.collectionCardType.find({ "name": CardType }).toArray(function (err, card) {

                resolve(card[0]);
            });

        });
    }

    getItems(request, branch, nomor, pos) {
        var self = this;
        return new Promise((resolve, reject) => {
            var queryfilter = 'select * from penjualan where nomor= \'' + nomor + '\' and branch= \'' + branch + '\' and pos=\'' + pos + '\'';
            // var queryfilter = 'select * from penjualan where nomor= \'' + nomor + '\' and branch= \'' + branch + '\'';
            request.query(queryfilter, function (err, sales) {
                if (err) {
                    console.log(err);
                    reject(err);
                }
                else {
                    var barcodes = [];
                    for (var i = 0; i < sales.length; i++) {
                        barcodes.push(sales[i].barcode);
                    }

                    self.getItemsMongo(barcodes)
                        .then(listItem => {
                            var itemDetails = [];
                            for (var i = 0; i < sales.length; i++) {
                                for (var j = 0; j < listItem.length; j++) {
                                    if (sales[i].barcode == listItem[j].code) {
                                        var itemDetail = {
                                            "_stamp": listItem[j]._stamp,
                                            "_type": "sales-item",
                                            "_version": "1.0.0",
                                            "_active": true,
                                            "_deleted": false,
                                            "_createdBy": "router",
                                            "_createdDate": new Date(),
                                            "_createAgent": "manager",
                                            "_updatedBy": "router",
                                            "_updatedDate": new Date(),
                                            "_updateAgent": "manager",
                                            "itemId": listItem[j]._id,
                                            "item": listItem[j],
                                            "promoId": "",
                                            "promo": {},
                                            "size": "",
                                            "quantity": sales[i].qty,
                                            "price": sales[i].harga,
                                            "discount1": sales[i].disc,
                                            "discount2": sales[i].disc1,
                                            "discountNominal": 0,
                                            "margin": 0,
                                            "specialDiscount": 0,
                                            "total": sales[i].subtotal,
                                            "isReturn": false,
                                            "returnItems": [],
                                        };
                                        itemDetails.push(itemDetail);
                                        break;
                                    }
                                }
                            }
                            resolve(itemDetails);
                        }).catch(error => {
                            reject(error);
                        });
                }
            });
        })
    };

    getItemsMongo(barcodes) {
        return new Promise((resolve, reject) => {
            this.collectionItem.find({ "code": { "$in": barcodes } }).toArray(function (err, items) {
                if (err)
                    reject(err);
                else
                    resolve(items);
            });
        });
    }

}
<commit_msg>etl<commit_after>'use strict'
var DLModels = require('bateeq-models');
var map = DLModels.map;
var ObjectId = require('mongodb').ObjectId;
var sqlConnect = require('./sqlConnect');
var BaseManager = require('module-toolkit').BaseManager;
var MongoClient = require('mongodb').MongoClient,
    test = require('assert');
var ItemManager = require('../../src/managers/master/item-manager');
var BankManager = require('../../src/managers/master/bank-manager');
var CardTypeManager = require('../../src/managers/master/card-type-manager');
var StoreManager = require('../../src/managers/master/store-manager');
var SalesManager = require('../../src/managers/sales/sales-manager');

module.exports = class SalesDataEtl extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.ItemManager = new ItemManager(db, user);
        this.BankManager = new BankManager(db, user);
        this.CardTypeManager = new CardTypeManager(db, user);
        this.StoreManager = new StoreManager(db, user);
        // this.SalesManager = new SalesManager(db, user);

        this.collectionItem = this.ItemManager.collection;
        this.collectionBank = this.BankManager.collection;
        this.collectionStore = this.StoreManager.collection;
        this.collectionCardType = this.CardTypeManager.collection;
        // this.collectionSalesManager = this.SalesManager.collection;
        this.collection = this.db.collection("sales-docs.temp");
        this.collectionLog = this.db.collection("migration.log");

    }

    CheckData() {
        return new Promise((resolve, reject) => {
            this.collectionSalesManager.find({}).toArray(function (err, sales) {
                return (sales);

            });

        });
    }

    getDataSales() {
        return new Promise((resolve, reject) => {
            sqlConnect.getConnect()
                .then((request) => {
                    var self = this;

                    var CountRows = "select count(*) as MaxLength from (select ROW_NUMBER() OVER(ORDER BY branch, nomor) AS number,branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin,sum(qty)as totalProduct, max(TOTAL) as subTotal,max(TOTAL) as grandTotal,0 as discount,'' as reference , max(voucher) as voucher, max(cash) as cash, max(debit) as debit,max(credit) as credit from penjualan group by branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin)a where (nomor ='201612.00144' and branch ='SLO.01') OR branch='SLO.02' OR branch='SLO.03'";

                    // var CountRows = "select count(*) as MaxLength from (select ROW_NUMBER() OVER(ORDER BY branch, nomor) AS number,branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin,sum(qty)as totalProduct, max(TOTAL) as subTotal,max(TOTAL) as grandTotal,0 as discount,'' as reference , max(voucher) as voucher, max(cash) as cash, max(debit) as debit,max(credit) as credit from penjualan group by branch,nomor,tanggal,shift,pos,kartu,no_krt,payment,userin,tglin)a where nomor like '%201305%' and branch ='SLO.01'";

                    request.query(CountRows, function (err, salesResult) {
                        // var a = [];
                        if (err) {
                            console.log(err);
                            reject(err);
                        }
                        else {
                            var _start = new Date().getTime();
                            var date = new Date();

                            self.collectionLog.insert({ "migration": "sql to sales-docs.temp ", "_createdDate": date, "_start": date });
                            var MaxLength = salesResult[0].MaxLength;
                            // var testPage = 5;
                            // self.collection.find({});

                            var dataRows = MaxLength;

                            var numberOfPage = Math.ceil(MaxLength / dataRows);

                            var process = [];
                            for (var i = 1; i <= numberOfPage; i++) {
                                process.push(self.migrateDataSales(request, i, dataRows))
                            }

                            Promise.all(process).then(results => {

                                var end = new Date();
                                var _end = new Date().getTime();
                                var time = _end - _start;
                                var log = {
                                    "migration": "sql to sales-docs.temp ",
                                    "_createdDate": date,
                                    "_start": date,
                                    "_end": end,
                                    "Execution time": time + ' ms',
                                };
                                self.collectionLog.updateOne({ "_start": date }, log);
                                resolve(results);
                            }).catch(error => {
                                console.log(error);
                                reject(error);
                            });
                        }
                    })
                });
        });
    }

    getDataMongo(code) {
        return new Promise((resolve, reject) => {
            this.collectionSalesManager.find({ "code": code }).toArray(function (err, sales) {
                resolve(sales);
            });

        });
    }

    getStore(branch) {
        return new Promise((resolve, reject) => {

            this.collectionStore.find({ "code": branch }).toArray(function (err, store) {
                resolve(store[0]);
            });

        });
    }

    getBanks(kartu) {
        return new Promise((resolve, reject) => {
            this.collectionBank.find({ "code": "BA-" + kartu }).toArray(function (err, Banks) {
                resolve(Banks[0]);
            });

        });
    }

    getCards(CardType) {
        return new Promise((resolve, reject) => {

            this.collectionCardType.find({ "name": CardType }).toArray(function (err, card) {

                resolve(card[0]);
            });

        });
    }

    migrateDataSales(request, pageNumber, dataRows) {
        var self = this;
        return new Promise((resolve, reject) => {

            var query = "exec pagination_sales_test " + pageNumber + "," + dataRows + " ";

            request.query(query, function (err, salesData) {
                if (!err) {
                    var tasks = [];
                    for (var sales of salesData) {
                        tasks.push(self.CreateData(request, sales));
                    }

                    Promise.all(tasks)
                        .then((task) => {
                            // self.collection.insertMany(task);
                            console.log(task);
                            resolve(task);
                        })
                        .catch(error => {

                            console.log("Error : " + error);
                            reject(error);
                        });
                } else {
                    reject(err);
                }
            });
        });
    }

    CreateData(request, sales) {
        return new Promise((resolve, reject) => {

            var paymentType = "Cash";
            if ((sales.payment.trim() == "DEBIT CARD") || (sales.payment.trim() == "CREDIT CARD")) {
                paymentType = "Card";
            }
            else if ((sales.payment.trim() == "PARTIAL DEBIT CARD") || (sales.payment.trim() == "PARTIAL CREDIT CARD")) {
                paymentType = "Partial";
            } else {
                paymentType = "Cash";
            };

            var cardTemp = "";
            if ((sales.payment.trim() == "DEBIT CARD") || (sales.payment.trim() == "PARTIAL DEBIT CARD")) {
                cardTemp = "Debit";
            } else if ((sales.payment.trim() == "CREDIT CARD") || (sales.payment.trim() == "PARTIAL CREDIT CARD")) {
                cardTemp = "Credit";
            } else {
                cardTemp = "";
            };

            var CardType = "";
            if ((sales.no_krt[0] == 5) && ((sales.no_krt[1] == 1) || (sales.no_krt[1] == 2) || (sales.no_krt[1] == 3) || (sales.no_krt[1] == 4) || (sales.no_krt[1] == 5))) {

                CardType = "Mastercard";
            } else if ((sales.no_krt[0] == 2) && ((sales.no_krt[1] == 2) || (sales.no_krt[1] == 3) || (sales.no_krt[1] == 4) || (sales.no_krt[1] == 5) || (sales.no_krt[1] == 6) || (sales.no_krt[1] == 7))) {
                CardType = "Mastercard";

            } else if (sales.no_krt[0] == 4) {
                CardType = "Visa";

            } else {
                CardType = "";
            };

            var BankName = "-"
            if ((sales.kartu.trim() == "") && (sales.payment.toLowerCase() != "cash")) {
                BankName = "-";
            } else {
                BankName = sales.kartu.trim();
            }

            var _id = new ObjectId();

            var _stamp = new ObjectId();

            // var kartu = sales.kartu.trim();
            // if (kartu.indexOf("/") != -1) {
            //     kartu = kartu.substring(0, kartu.indexOf("/"));
            // } else {
            //     kartu = sales.kartu.trim();
            // }

            var store = this.getStore(sales.branch);
            var items = this.getItems(request, sales.branch, sales.nomor, sales.pos.trim());
            var banks = this.getBanks(sales.kartu);
            // var banks = this.getBanks(kartu);
            var cards = this.getCards(CardType);
            var cardBanks = this.getBanks("-");

            Promise.all([store, items, banks, cards, cardBanks]).then(data => {

                var salesArr = [];
                var salesData = {
                    "_id": _id,
                    "_stamp": _stamp,
                    "_type": "sales-doc",
                    "_version": "1.0.0",
                    "_active": true,
                    "_deleted": false,
                    "_createdBy": sales.userin.trim(),
                    "_createdDate": sales.tglin,
                    // "_createdDate": new Date(),
                    "_createAgent": "manager",
                    "_updatedBy": "router",
                    "_updatedDate": new Date(),
                    "_updateAgent": "manager",
                    "code": sales.nomor,
                    "date": sales.tanggal,
                    "totalProduct": sales.totalProduct,
                    "subTotal": sales.subTotal,
                    "discount": sales.discount,
                    "grandTotal": parseInt(sales.grandTotal),
                    "reference": sales.reference,
                    "shift": parseInt(sales.shift),
                    "pos": sales.pos.trim(),

                    "storeId": data[0]._id,
                    "store": data[0],
                    "items": data[1],

                    "salesDetail":
                    {
                        "_stamp": new ObjectId(),
                        "_type": "sales-type",
                        "_version": "1.0.0",
                        "_active": true,
                        "deleted": false,
                        "_createdBy": "router",
                        "_createdDate": new Date(),
                        "_createAgent": "manager",
                        "_updatedBy": "router",
                        "_updatedDate": new Date(),
                        "_updateAgent": "manager",
                        "paymentType": paymentType,
                        "voucherId": {},
                        "voucher": {
                            "value": parseInt(sales.voucher),
                        },
                        "bankId": (paymentType == "Cash") ? {} : ((data[2]) ? data[2]._id : {}), //query penjualan.kartu
                        "bank": (paymentType == "Cash") ? {} : ((data[2]) ? data[2] : {}),
                        "cardTypeId": (cardTemp == "Debit") ? {} : ((data[3]) ? data[3]._id : {}),
                        "cardType": (cardTemp == "Debit") ? {} : ((data[3]) ? data[3] : {}),

                        // "cardTypeId": (_card) ? _card._id : {},
                        // "cardType": (_card) ? _card : {},

                        "bankCardId": (paymentType == "Cash") ? {} : ((data[4]) ? data[4]._id : {}),
                        "bankCard": (paymentType == "Cash") ? {} : ((data[4]) ? data[4] : {}),
                        "card": cardTemp,
                        "cardNumber": sales.no_krt.trim(),
                        "cardName": "",
                        "cashAmount": parseInt(sales.cash),
                        "cardAmount": parseInt(sales.debit) + parseInt(sales.credit),
                    },
                    "remark": "",
                    "isReturn": false,
                    "isVoid": false,
                }
                salesArr.push(salesData);
                resolve(this.collection.insertMany(salesArr));
            })

        })
    }

    getStore(branch) {
        return new Promise((resolve, reject) => {

            this.collectionStore.find({ "code": branch }).toArray(function (err, store) {
                resolve(store[0]);
            });

        });
    }

    getBanks(kartu) {
        return new Promise((resolve, reject) => {
            this.collectionBank.find({ "code": "BA-" + kartu }).toArray(function (err, Banks) {
                resolve(Banks[0]);
            });

        });
    }

    getCards(CardType) {
        return new Promise((resolve, reject) => {

            this.collectionCardType.find({ "name": CardType }).toArray(function (err, card) {

                resolve(card[0]);
            });

        });
    }

    getItems(request, branch, nomor, pos) {
        var self = this;
        return new Promise((resolve, reject) => {
            var queryfilter = 'select * from penjualan where nomor= \'' + nomor + '\' and branch= \'' + branch + '\' and pos=\'' + pos + '\'';
            // var queryfilter = 'select * from penjualan where nomor= \'' + nomor + '\' and branch= \'' + branch + '\'';
            request.query(queryfilter, function (err, sales) {
                if (err) {
                    console.log(err);
                    reject(err);
                }
                else {
                    var barcodes = [];
                    for (var i = 0; i < sales.length; i++) {
                        barcodes.push(sales[i].barcode);
                    }

                    self.getItemsMongo(barcodes)
                        .then(listItem => {
                            var itemDetails = [];
                            for (var i = 0; i < sales.length; i++) {
                                for (var j = 0; j < listItem.length; j++) {
                                    if (sales[i].barcode == listItem[j].code) {
                                        var itemDetail = {
                                            "_stamp": listItem[j]._stamp,
                                            "_type": "sales-item",
                                            "_version": "1.0.0",
                                            "_active": true,
                                            "_deleted": false,
                                            "_createdBy": "router",
                                            "_createdDate": new Date(),
                                            "_createAgent": "manager",
                                            "_updatedBy": "router",
                                            "_updatedDate": new Date(),
                                            "_updateAgent": "manager",
                                            "itemId": listItem[j]._id,
                                            "item": listItem[j],
                                            "promoId": "",
                                            "promo": {},
                                            "size": "",
                                            "quantity": sales[i].qty,
                                            "price": sales[i].harga,
                                            "discount1": sales[i].disc,
                                            "discount2": sales[i].disc1,
                                            "discountNominal": 0,
                                            "margin": 0,
                                            "specialDiscount": 0,
                                            "total": sales[i].subtotal,
                                            "isReturn": false,
                                            "returnItems": [],
                                        };
                                        itemDetails.push(itemDetail);
                                        break;
                                    }
                                }
                            }
                            resolve(itemDetails);
                        }).catch(error => {
                            reject(error);
                        });
                }
            });
        })
    };

    getItemsMongo(barcodes) {
        return new Promise((resolve, reject) => {
            this.collectionItem.find({ "code": { "$in": barcodes } }).toArray(function (err, items) {
                if (err)
                    reject(err);
                else
                    resolve(items);
            });
        });
    }

}
<|endoftext|>


<commit_before>//FIRE AND FORGET
var http = require('http');
var url = require('url');

var init = function (emitter) {
    "use strict";
    return function(callback){
    emitter.on("NEWSTATE", function (data) {
        //Just act on delivered
        if (data.state === "Delivered") {
            do_callback(data);
        }
    });
    callback && callback(null);
};
};

function do_callback(data) {
    "use strict";
    if (data.callback) {
        var options = url.parse(data.callback);
        options.headers['content-type'] = 'application/json';
        options.method = 'POST';
        var cb_req = http.request(options);  //FIRE AND FORGET
        var str_data = JSON.stringify(data);
        cb_req.on('error', function foo(err) {
            console.log('callback err::' + err);
        });
        cb_req.write(str_data);
        cb_req.end();
    }
}

exports.init = init;<commit_msg>init header // object literal<commit_after>//FIRE AND FORGET
var http = require('http');
var url = require('url');

var init = function (emitter) {
    "use strict";
    return function(callback){
    emitter.on("NEWSTATE", function (data) {
        //Just act on delivered
        if (data.state === "Delivered") {
            do_callback(data);
        }
    });
    callback && callback(null);
};
};

function do_callback(data) {
    "use strict";
    if (data.callback) {
        var options = url.parse(data.callback);
        options.headers = {'content-type':'application/json'};
        options.method = 'POST';
        var cb_req = http.request(options);  //FIRE AND FORGET
        var str_data = JSON.stringify(data);
        cb_req.on('error', function foo(err) {
            console.log('callback err::' + err);
        });
        cb_req.write(str_data);
        cb_req.end();
    }
}

exports.init = init;<|endoftext|>


<commit_before>// @flow
import { readFileSync } from 'fs'
import { resolve } from 'path'

import type { Program, Statement } from '../types'
import { parse } from '../index'

const resolveImportPath = (path: string) => (
	resolve(path.endsWith('.ari') ? path : `${path}.ari`)
)

export default function link(program: Program): Statement[] {
	const imports: Set<string> = new Set()
	const linkBody = (body: Statement[]) => {
		const statements = []

		for (const statement of body) {
			if (statement.type === 'Import') {
				const resolvedPath = resolveImportPath(statement.path)

				if (!imports.has(resolvedPath)) {
					const importedProgram = parse(String(readFileSync(resolvedPath)))

					imports.add(resolvedPath)
					statements.push(...linkBody(importedProgram.body))
				}
			} else {
				statements.push(statement)
			}
		}

		return statements
	}

	return linkBody(program.body)
}
<commit_msg>refactor linker.js and add filename to parse call in `link`<commit_after>// @flow
import { readFileSync } from 'fs'
import { resolve, dirname } from 'path'

import type { Program, Statement } from '../types'
import { parse } from '../index'

export default function link(
	program: Program,
	imports: Set<string> = new Set(),
): Statement[] {
	const statements = []

	for (const statement of program.body) {
		if (statement.type === 'Import') {
			const filename = resolve(dirname(program.filename), statement.path)

			if (!imports.has(filename)) {
				const file = String(readFileSync(filename))
				const importedProgram = parse(file, { filename })

				imports.add(filename)
				statements.push(...link(importedProgram))
			}
		} else {
			statements.push(statement)
		}
	}

	return statements
}
<|endoftext|>


<commit_before>
import Aggregate from './aggregate'
import { isEqual } from 'lodash'

/**
 * @class CountExpression
 */
export default class Count extends Aggregate {

  /**
   *
   * @param {Array} columns
   * @constructor
   */
  constructor(columns = ['*']) {
    super('count', null)

    this.columns = columns
    this.isDistinct = false
  }

  /**
   *
   * @param {Boolean} flag
   * @returns {Count}
   */
  distinct(flag = true) {
    this.isDistinct = flag
    return this
  }

  /**
   *
   * @param {Compiler}
   * @returns {String}
   */
  compile(compiler) {
    var columns = compiler.columnize(this.columns)
    var distinct = this.isDistinct ? 'distinct ' : ''

    return compiler.alias(`count(${distinct}${columns})`, this.alias)
  }

  /**
   *
   * @param {Any} expr
   * @returns {Boolean}
   */
  isEqual(expr) {
    // TODO compare also the columns
    return expr instanceof Count && expr.alias === this.alias
  }

}
<commit_msg>Delete Count expression<commit_after><|endoftext|>


<commit_before>/* globals openRoom */

/**
 * Help requests need two additional room types
 * @see packages/rocketchat-lib/startup/defaultRoomTypes.js
 */

/**
 * A request is a channel which has a dedicated aim: resolve an issue which
 * is asked by the one who started the request (the owner)
 * Expertise shall join the room (automagically) and help to get it resolved
 */
RocketChat.roomTypes.add('r', 6, { //5 is livechat
	template: 'requests',
	icon: 'icon-help',
	route: {
		name: 'request',
		path: '/request/:name',
		action(params) {
			return openRoom('r', params.name);
		}
	},

	findRoom(identifier) {
		const query = {
			t: 'r',
			name: identifier
		};
		return ChatRoom.findOne(query);
	},

	roomName(roomData) {
		return roomData.name;
	},

	condition() {
		return RocketChat.authz.hasAtLeastOnePermission(['view-c-room', 'view-joined-room']); //todo: own permission
	},

	showJoinLink(roomId) {
		return !!ChatRoom.findOne({ _id: roomId, t: 'r' });
	}
});

/**
 *	An expert group is a private group of people who know something
 *	An expert group is being added to a request-channel on creation based on naming conventions
 */
RocketChat.roomTypes.add('e', 15, { //20 = private messages
	template: 'expertise',
	icon: 'icon-lightbulb',
	route: {
		name: 'expertise',
		path: '/expertise/:name',
		action(params) {
			return openRoom('e', params.name);
		}
	},

	findRoom(identifier) {
		const query = {
			t: 'e',
			name: identifier
		};
		return ChatRoom.findOne(query);
	},

	roomName(roomData) {
		return roomData.name;
	},

	condition() {
		return RocketChat.authz.hasAllPermission('view-p-room'); //todo: Own authorization
	}
});
<commit_msg>Provide labels for custom room types (as required per 0.57)<commit_after>/* globals openRoom */

/**
 * Help requests need two additional room types
 * @see packages/rocketchat-lib/startup/defaultRoomTypes.js
 */

/**
 * A request is a channel which has a dedicated aim: resolve an issue which
 * is asked by the one who started the request (the owner)
 * Expertise shall join the room (automagically) and help to get it resolved
 */
RocketChat.roomTypes.add('r', 6, { //5 is livechat
	template: 'requests',
	icon: 'icon-help',
	label: 'Requests',
	route: {
		name: 'request',
		path: '/request/:name',
		action(params) {
			return openRoom('r', params.name);
		}
	},

	findRoom(identifier) {
		const query = {
			t: 'r',
			name: identifier
		};
		return ChatRoom.findOne(query);
	},

	roomName(roomData) {
		return roomData.name;
	},

	condition() {
		return RocketChat.authz.hasAtLeastOnePermission(['view-c-room', 'view-joined-room']); //todo: own permission
	},

	showJoinLink(roomId) {
		return !!ChatRoom.findOne({ _id: roomId, t: 'r' });
	}
});

/**
 *	An expert group is a private group of people who know something
 *	An expert group is being added to a request-channel on creation based on naming conventions
 */
RocketChat.roomTypes.add('e', 15, { //20 = private messages
	template: 'expertise',
	icon: 'icon-lightbulb',
	label: 'Expertises',
	route: {
		name: 'expertise',
		path: '/expertise/:name',
		action(params) {
			return openRoom('e', params.name);
		}
	},

	findRoom(identifier) {
		const query = {
			t: 'e',
			name: identifier
		};
		return ChatRoom.findOne(query);
	},

	roomName(roomData) {
		return roomData.name;
	},

	condition() {
		return RocketChat.authz.hasAllPermission('view-p-room'); //todo: Own authorization
	}
});
<|endoftext|>


<commit_before>let currentBrowser;

module.exports = {
  tags: ['component', 'image'],
  'Bolt Image image is showed': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-image-showed';

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-image-05-image/02-components-image-05-image.html`,
      )
      .waitForElementVisible('.c-bolt-image__image', 1000)
      .saveScreenshot(
        `screenshots/bolt-image/${testName}--${currentBrowser}.png`,
      )
      .end();
  },

  'Bolt Image zoom': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-image-zoom';

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-image-30-image-zoom-variation/02-components-image-30-image-zoom-variation.html`,
      )
      .waitForElementVisible('bolt-device-viewer', 1000)
      .moveToElement('bolt-image-zoom', 50, 50)
      .assert.cssClassPresent('bolt-image-zoom', 'is-mouse-entering')
      .saveScreenshot(
        `screenshots/bolt-image/${testName}--${currentBrowser}.png`,
      )
      .end();
  },
};
<commit_msg>test(@bolt/components-image): update bolt-image size logic<commit_after>let currentBrowser;

module.exports = {
  tags: ['component', 'image'],
  'Bolt Image image is showed': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-image-showed';
    let bodyWidth = 0;

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-image-05-image/02-components-image-05-image.html`,
      )
      .waitForElementVisible('body', 1000)
      .getElementSize('body', function(result) {
        bodyWidth = result.value.width;
      })
      .getElementSize('.c-bolt-image__image', function(result) {
        const imageHeight = Math.round(bodyWidth / 1.3333333333);
        this.assert.equal(typeof result, 'object');
        this.assert.equal(result.status, 0);
        this.assert.equal(result.value.width, bodyWidth);
        this.assert.equal(result.value.height, imageHeight);
      })
      .saveScreenshot(
        `screenshots/bolt-image/${testName}--${currentBrowser}.png`,
      )
      .end();
  },

  'Bolt Image zoom': function(browser) {
    const { testingUrl } = browser.globals;
    console.log(`global browser url: ${testingUrl}`);
    currentBrowser = '--' + browser.currentEnv || 'chrome';
    let testName = 'bolt-image-zoom';

    browser
      .url(
        `${testingUrl}/pattern-lab/patterns/02-components-image-30-image-zoom-variation/02-components-image-30-image-zoom-variation.html`,
      )
      .waitForElementVisible('bolt-device-viewer', 1000)
      .moveToElement('bolt-image-zoom', 50, 50)
      .assert.cssClassPresent('bolt-image-zoom', 'is-mouse-entering')
      .saveScreenshot(
        `screenshots/bolt-image/${testName}--${currentBrowser}.png`,
      )
      .end();
  },
};
<|endoftext|>