<commit_before>define(['marionette',

        'models/dewar',
        'models/shipment',
        'collections/shipments',
        'modules/shipment/views/shipments',
        'modules/shipment/views/shipment',
        'modules/shipment/views/shipmentadd',

        'models/container',
        'collections/containers',
        'modules/shipment/views/container',
        'modules/shipment/views/containerplate',
        'modules/shipment/views/containeradd',
        'modules/shipment/views/containers',
        'modules/imaging/views/queuecontainer',

        'modules/shipment/models/containerregistry',
        'modules/shipment/collections/containerregistry',
        'modules/shipment/views/containerregistry',
        'modules/shipment/views/registeredcontainer',

        'modules/shipment/models/dewarregistry',
        'modules/shipment/collections/dewarregistry',
        'modules/shipment/views/dewarreg',
        'modules/shipment/views/regdewar',
        'modules/shipment/views/regdewaradd',

        'modules/shipment/views/dispatch',
        'modules/shipment/views/transfer',

        'collections/dewars',
        'modules/shipment/views/dewaroverview',
        'modules/shipment/views/manifest',

        'modules/shipment/views/createawb',

        'models/proplookup',

], function(Marionette,
    Dewar, Shipment, Shipments,
    ShipmentsView, ShipmentView, ShipmentAddView,
    Container, Containers, ContainerView, ContainerPlateView, ContainerAddView, ContainersView, QueueContainerView,
    ContainerRegistry, ContainersRegistry, ContainerRegistryView, RegisteredContainer,
    RegisteredDewar, DewarRegistry, DewarRegView, RegDewarView, RegDewarAddView,
    DispatchView, TransferView, Dewars, DewarOverview, ManifestView, CreateAWBView,
    ProposalLookup) {

    var bc = { title: 'Shipments', url: '/shipments' }

  var controller = {
    list: function(page) {
      console.log('ship list')
      app.loading()
      var shipments = new Shipments()

      shipments.state.currentPage = page ? parseInt(page) : 1
      shipments.fetch().done(function() {
        app.bc.reset([bc])
        app.content.show(new ShipmentsView({ collection: shipments }))
      })
    },

    view: function(sid) {
        var lookup = new ProposalLookup({ field: 'SHIPPINGID', value: sid })
        lookup.find({
            success: function() {
                app.log('ship view', sid)
                var shipment = new Shipment({ SHIPPINGID: sid })
                  shipment.fetch({
                      success: function() {
                          app.bc.reset([bc, { title: shipment.get('SHIPPINGNAME') }])
                          app.content.show(new ShipmentView({ model: shipment }))
                      },
                      error: function() {
                          app.bc.reset([bc])
                          app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
                      },
                  })
            },

            error: function() {
                app.bc.reset([bc, { title: 'No such shipment' }])
                app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
            }
        })
    },

    add: function() {
      app.log('ship add view')
      app.bc.reset([bc, { title: 'Add New Shipment' }])
      app.content.show(new ShipmentAddView())
    },

    create_awb: function(sid) {
        var shipment = new Shipment({ SHIPPINGID: sid })
        shipment.fetch({
            success: function() {
                app.bc.reset([bc, { title: shipment.get('SHIPPINGNAME') }, { title: 'Create Airway Bill' }])
                app.content.show(new CreateAWBView({ shipment: shipment }))
            },
            error: function() {
                app.bc.reset([bc])
                app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
            },
        })
    },

    container_list: function(s, ty, page) {
      console.log('cont list')
      app.loading()
      app.bc.reset([bc, { title: 'Containers' }])

      page = page ? parseInt(page) : 1
      var containers = new Containers(null, { state: { currentPage: page }, queryParams: { s: s, ty: ty } })
      containers.fetch().done(function() {
          app.content.show(new ContainersView({ collection: containers, params: { s: s, ty: ty } }))
      })
    },

    view_container: function(cid, iid, sid) {
        var lookup = new ProposalLookup({ field: 'CONTAINERID', value: cid })
        lookup.find({
            success: function() {
                app.log('cont view', cid, iid, sid)
                var container = new Container({ CONTAINERID: cid })
                container.fetch({
                    success: function() {
                        app.bc.reset([bc, { title: container.get('SHIPMENT'), url: '/shipments/sid/'+container.get('SHIPPINGID') }, { title: 'Containers' }, { title: container.get('NAME') }])
                        var is_plate = !(['Puck', 'PCRStrip', null].indexOf(container.get('CONTAINERTYPE')) > -1)
                        console.log('is plate', is_plate)
                        if (is_plate) app.content.show(new ContainerPlateView({ model: container, params: { iid: iid, sid: sid } }))
                          else app.content.show(new ContainerView({ model: container }))
                    },
                    error: function() {
                        app.bc.reset([bc, { title: 'No such container' }])
                        app.message({ title: 'No such container', message: 'The specified container could not be found'})
                    },
                })
            },

            error: function() {
                app.bc.reset([bc, { title: 'No such container' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            }
        })
    },

    add_container: function(did, visit) {
      app.log('cont view')

      var dewar = new Dewar({ DEWARID: did})
        dewar.fetch({
            success: function() {
                app.bc.reset([bc, { title: dewar.get('SHIPPINGNAME'), url: '/shipments/sid/'+dewar.get('SHIPPINGID') }, { title: 'Containers' }, { title: 'Add Container' }])
                app.content.show(new ContainerAddView({ dewar: dewar, visit: visit }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    queue_container: function(cid) {
        var container = new Container({ CONTAINERID: cid })
        container.fetch({
            success: function() {
                app.bc.reset([bc, { title: container.get('SHIPMENT'), url: '/shipments/sid/'+container.get('SHIPPINGID') }, { title: 'Containers' }, { title: container.get('NAME') }, { title: 'Queue Samples' }])
                app.content.show(new QueueContainerView({ model: container }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            },
        })
    },

    add_container_visit: function(visit) {
        Backbone.ajax({
            url: app.apiurl+'/shipment/dewars/default',
            data: { visit: visit },

            success: function(did) {
                controller.add_container(did, visit)
                app.navigate('/containers/add/did/'+did)
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'Error', message: 'The default dewar for this visit could not be created' })
            },
        })
    },

    container_registry: function(ty, s, page) {
      app.loading()
      var containers = new ContainersRegistry()

      page = page ? parseInt(page) : 1

      containers.state.currentPage = page
      containers.queryParams.all = 1
      containers.fetch().done(function() {
        app.bc.reset([bc, { title: 'Registered Containers', url: '/dewars' }])
        app.content.show(new ContainerRegistryView({ collection: containers, params: { s: s, ty: ty } }))
      })
    },

    view_rcontainer: function(crid) {
        var container = new ContainerRegistry({ CONTAINERREGISTRYID: crid })
        container.fetch({
            data: {
                all: 1
            },
            success: function() {
                app.bc.reset([bc, { title: container.get('BARCODE') }])
                app.content.show(new RegisteredContainer({ model: container }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            },
        })
    },

    dewar_list: function(s, page) {
      console.log('dew list')
      app.loading()
      var dewars = new DewarRegistry()

      dewars.state.currentPage = page ? parseInt(page) : 1
      dewars.fetch().done(function() {
        app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }])
        app.content.show(new DewarRegView({ collection: dewars, params: { s: s } }))
      })
    },

    view_dewar: function(fc) {
      app.log('cont view')
      var dewar = new RegisteredDewar({ FACILITYCODE: fc })
        dewar.fetch({
            success: function() {
                dewar.fetched = true
                app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }, { title: dewar.get('FACILITYCODE') }])
                app.content.show(new RegDewarView({ model: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    add_dewar: function() {
      app.log('dew add view')
      app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }, { title: 'Add New Dewar' }])
      app.content.show(new RegDewarAddView())
    },

    dispatch_dewar: function(did) {
        var dewar = new Dewar({ DEWARID: did })
        dewar.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Dispatch Dewar' }, { title: dewar.get('CODE') }])
                app.content.show(new DispatchView({ dewar: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    transfer_dewar: function(did) {
        var dewar = new Dewar({ DEWARID: did })
        dewar.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Transfer Dewar' }, { title: dewar.get('CODE') }])
                app.content.show(new TransferView({ dewar: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    dewar_overview: function(s, page) {
        page = page ? parseInt(page) : 1

        var dewars = new Dewars(null, { state: { currentPage: page }, queryParams: { s: s, all: 1, ty: app.type } })
        dewars.setSorting('FIRSTEXPERIMENTST', 1)
        dewars.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Dewar Overview' }])
                app.content.show(new DewarOverview({ collection: dewars, params: { s: s } }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No dewars', message: 'Couldnt fetch dewar list'})
            },
        })
    },

    manifest: function() {
        app.bc.reset([bc, { title: 'Manifest' }])
        app.content.show(new ManifestView())
    }

  }

  app.addInitializer(function() {
    app.on('shipments:show', function() {
      app.navigate('shipments')
      controller.list()
    })

    app.on('shipment:show', function(sid) {
      app.navigate('shipments/sid/'+sid)
      controller.view(sid)
    })

    app.on('container:show', function(cid, iid, sid) {
      app.navigate('containers/cid/'+cid+(iid?'/iid/'+iid:'')+(sid?'/sid/'+sid:''))
      controller.view_container(cid, iid, sid)
    })

    app.on('rdewar:show', function(fc) {
      app.navigate('dewars/fc/'+fc)
      controller.view_dewar(fc)
    })

    app.on('rcontainer:show', function(crid) {
      app.navigate('containers/registry/'+crid)
      controller.view_rcontainer(crid)
    })
  })

  return controller
})<commit_msg>add more lookups<commit_after>define(['marionette',

        'models/dewar',
        'models/shipment',
        'collections/shipments',
        'modules/shipment/views/shipments',
        'modules/shipment/views/shipment',
        'modules/shipment/views/shipmentadd',

        'models/container',
        'collections/containers',
        'modules/shipment/views/container',
        'modules/shipment/views/containerplate',
        'modules/shipment/views/containeradd',
        'modules/shipment/views/containers',
        'modules/imaging/views/queuecontainer',

        'modules/shipment/models/containerregistry',
        'modules/shipment/collections/containerregistry',
        'modules/shipment/views/containerregistry',
        'modules/shipment/views/registeredcontainer',

        'modules/shipment/models/dewarregistry',
        'modules/shipment/collections/dewarregistry',
        'modules/shipment/views/dewarreg',
        'modules/shipment/views/regdewar',
        'modules/shipment/views/regdewaradd',

        'modules/shipment/views/dispatch',
        'modules/shipment/views/transfer',

        'collections/dewars',
        'modules/shipment/views/dewaroverview',
        'modules/shipment/views/manifest',

        'modules/shipment/views/createawb',

        'models/proplookup',

], function(Marionette,
    Dewar, Shipment, Shipments,
    ShipmentsView, ShipmentView, ShipmentAddView,
    Container, Containers, ContainerView, ContainerPlateView, ContainerAddView, ContainersView, QueueContainerView,
    ContainerRegistry, ContainersRegistry, ContainerRegistryView, RegisteredContainer,
    RegisteredDewar, DewarRegistry, DewarRegView, RegDewarView, RegDewarAddView,
    DispatchView, TransferView, Dewars, DewarOverview, ManifestView, CreateAWBView,
    ProposalLookup) {

    var bc = { title: 'Shipments', url: '/shipments' }

  var controller = {
    list: function(page) {
      console.log('ship list')
      app.loading()
      var shipments = new Shipments()

      shipments.state.currentPage = page ? parseInt(page) : 1
      shipments.fetch().done(function() {
        app.bc.reset([bc])
        app.content.show(new ShipmentsView({ collection: shipments }))
      })
    },

    view: function(sid) {
        var lookup = new ProposalLookup({ field: 'SHIPPINGID', value: sid })
        lookup.find({
            success: function() {
                app.log('ship view', sid)
                var shipment = new Shipment({ SHIPPINGID: sid })
                  shipment.fetch({
                      success: function() {
                          app.bc.reset([bc, { title: shipment.get('SHIPPINGNAME') }])
                          app.content.show(new ShipmentView({ model: shipment }))
                      },
                      error: function() {
                          app.bc.reset([bc])
                          app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
                      },
                  })
            },

            error: function() {
                app.bc.reset([bc, { title: 'No such shipment' }])
                app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
            }
        })
    },

    add: function() {
      app.log('ship add view')
      app.bc.reset([bc, { title: 'Add New Shipment' }])
      app.content.show(new ShipmentAddView())
    },

    create_awb: function(sid) {
        var shipment = new Shipment({ SHIPPINGID: sid })
        shipment.fetch({
            success: function() {
                app.bc.reset([bc, { title: shipment.get('SHIPPINGNAME') }, { title: 'Create Airway Bill' }])
                app.content.show(new CreateAWBView({ shipment: shipment }))
            },
            error: function() {
                app.bc.reset([bc])
                app.message({ title: 'No such shipment', message: 'The specified shipment could not be found'})
            },
        })
    },

    container_list: function(s, ty, page) {
      console.log('cont list')
      app.loading()
      app.bc.reset([bc, { title: 'Containers' }])

      page = page ? parseInt(page) : 1
      var containers = new Containers(null, { state: { currentPage: page }, queryParams: { s: s, ty: ty } })
      containers.fetch().done(function() {
          app.content.show(new ContainersView({ collection: containers, params: { s: s, ty: ty } }))
      })
    },

    view_container: function(cid, iid, sid) {
        var lookup = new ProposalLookup({ field: 'CONTAINERID', value: cid })
        lookup.find({
            success: function() {
                app.log('cont view', cid, iid, sid)
                var container = new Container({ CONTAINERID: cid })
                container.fetch({
                    success: function() {
                        app.bc.reset([bc, { title: container.get('SHIPMENT'), url: '/shipments/sid/'+container.get('SHIPPINGID') }, { title: 'Containers' }, { title: container.get('NAME') }])
                        var is_plate = !(['Puck', 'PCRStrip', null].indexOf(container.get('CONTAINERTYPE')) > -1)
                        console.log('is plate', is_plate)
                        if (is_plate) app.content.show(new ContainerPlateView({ model: container, params: { iid: iid, sid: sid } }))
                          else app.content.show(new ContainerView({ model: container }))
                    },
                    error: function() {
                        app.bc.reset([bc, { title: 'No such container' }])
                        app.message({ title: 'No such container', message: 'The specified container could not be found'})
                    },
                })
            },

            error: function() {
                app.bc.reset([bc, { title: 'No such container' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            }
        })
    },

    add_container: function(did, visit) {
      var lookup = new ProposalLookup({ field: 'DEWARID', value: did })
        lookup.find({
            success: function() {
                app.log('cont view')

                var dewar = new Dewar({ DEWARID: did})
                  dewar.fetch({
                      success: function() {
                          app.bc.reset([bc, { title: dewar.get('SHIPPINGNAME'), url: '/shipments/sid/'+dewar.get('SHIPPINGID') }, { title: 'Containers' }, { title: 'Add Container' }])
                          app.content.show(new ContainerAddView({ dewar: dewar, visit: visit }))
                      },
                      error: function() {
                          app.bc.reset([bc, { title: 'Error' }])
                          app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
                      },
                  })
            },

            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },

        })
    },

    queue_container: function(cid) {
        var lookup = new ProposalLookup({ field: 'CONTAINERID', value: cid })
        lookup.find({
            success: function() {
                var container = new Container({ CONTAINERID: cid })
                container.fetch({
                    success: function() {
                        app.bc.reset([bc, { title: container.get('SHIPMENT'), url: '/shipments/sid/'+container.get('SHIPPINGID') }, { title: 'Containers' }, { title: container.get('NAME') }, { title: 'Queue Samples' }])
                        app.content.show(new QueueContainerView({ model: container }))
                    },
                    error: function() {
                        app.bc.reset([bc, { title: 'Error' }])
                        app.message({ title: 'No such container', message: 'The specified container could not be found'})
                    },
                })
            },

            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            },

        })
    },

    add_container_visit: function(visit) {
        Backbone.ajax({
            url: app.apiurl+'/shipment/dewars/default',
            data: { visit: visit },

            success: function(did) {
                controller.add_container(did, visit)
                app.navigate('/containers/add/did/'+did)
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'Error', message: 'The default dewar for this visit could not be created' })
            },
        })
    },

    container_registry: function(ty, s, page) {
      app.loading()
      var containers = new ContainersRegistry()

      page = page ? parseInt(page) : 1

      containers.state.currentPage = page
      containers.queryParams.all = 1
      containers.fetch().done(function() {
        app.bc.reset([bc, { title: 'Registered Containers', url: '/dewars' }])
        app.content.show(new ContainerRegistryView({ collection: containers, params: { s: s, ty: ty } }))
      })
    },

    view_rcontainer: function(crid) {
        var container = new ContainerRegistry({ CONTAINERREGISTRYID: crid })
        container.fetch({
            data: {
                all: 1
            },
            success: function() {
                app.bc.reset([bc, { title: container.get('BARCODE') }])
                app.content.show(new RegisteredContainer({ model: container }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such container', message: 'The specified container could not be found'})
            },
        })
    },

    dewar_list: function(s, page) {
      console.log('dew list')
      app.loading()
      var dewars = new DewarRegistry()

      dewars.state.currentPage = page ? parseInt(page) : 1
      dewars.fetch().done(function() {
        app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }])
        app.content.show(new DewarRegView({ collection: dewars, params: { s: s } }))
      })
    },

    view_dewar: function(fc) {
      app.log('cont view')
      var dewar = new RegisteredDewar({ FACILITYCODE: fc })
        dewar.fetch({
            success: function() {
                dewar.fetched = true
                app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }, { title: dewar.get('FACILITYCODE') }])
                app.content.show(new RegDewarView({ model: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    add_dewar: function() {
      app.log('dew add view')
      app.bc.reset([bc, { title: 'Registered Dewars', url: '/dewars' }, { title: 'Add New Dewar' }])
      app.content.show(new RegDewarAddView())
    },

    dispatch_dewar: function(did) {
        var dewar = new Dewar({ DEWARID: did })
        dewar.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Dispatch Dewar' }, { title: dewar.get('CODE') }])
                app.content.show(new DispatchView({ dewar: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    transfer_dewar: function(did) {
        var dewar = new Dewar({ DEWARID: did })
        dewar.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Transfer Dewar' }, { title: dewar.get('CODE') }])
                app.content.show(new TransferView({ dewar: dewar }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No such dewar', message: 'The specified dewar could not be found'})
            },
        })
    },

    dewar_overview: function(s, page) {
        page = page ? parseInt(page) : 1

        var dewars = new Dewars(null, { state: { currentPage: page }, queryParams: { s: s, all: 1, ty: app.type } })
        dewars.setSorting('FIRSTEXPERIMENTST', 1)
        dewars.fetch({
            success: function() {
                app.bc.reset([bc, { title: 'Dewar Overview' }])
                app.content.show(new DewarOverview({ collection: dewars, params: { s: s } }))
            },
            error: function() {
                app.bc.reset([bc, { title: 'Error' }])
                app.message({ title: 'No dewars', message: 'Couldnt fetch dewar list'})
            },
        })
    },

    manifest: function() {
        app.bc.reset([bc, { title: 'Manifest' }])
        app.content.show(new ManifestView())
    }

  }

  app.addInitializer(function() {
    app.on('shipments:show', function() {
      app.navigate('shipments')
      controller.list()
    })

    app.on('shipment:show', function(sid) {
      app.navigate('shipments/sid/'+sid)
      controller.view(sid)
    })

    app.on('container:show', function(cid, iid, sid) {
      app.navigate('containers/cid/'+cid+(iid?'/iid/'+iid:'')+(sid?'/sid/'+sid:''))
      controller.view_container(cid, iid, sid)
    })

    app.on('rdewar:show', function(fc) {
      app.navigate('dewars/fc/'+fc)
      controller.view_dewar(fc)
    })

    app.on('rcontainer:show', function(crid) {
      app.navigate('containers/registry/'+crid)
      controller.view_rcontainer(crid)
    })
  })

  return controller
})<|endoftext|>


<commit_before>import "@blueprintjs/core/lib/css/blueprint.css"
import { DateInput, TimePrecision } from "@blueprintjs/datetime"
import "@blueprintjs/datetime/lib/css/blueprint-datetime.css"
import moment from "moment"
import PropTypes from "prop-types"
import React, { useRef } from "react"
import CALENDAR_ICON from "resources/calendar.png"
import Settings from "settings"
import "./BlueprintOverrides.css"

const CalendarIcon = inputRef => (
  <img
    src={CALENDAR_ICON}
    alt=""
    title="Pick a date"
    height={24}
    style={{ verticalAlign: "middle" }}
    onClick={() => {
      if (inputRef && inputRef.focus) {
        inputRef.focus()
      }
    }}
  />
)

const CustomDateInput = ({
  id,
  disabled,
  showIcon,
  withTime,
  value,
  onChange,
  onBlur
}) => {
  const inputRef = useRef()
  const rightElement = showIcon && CalendarIcon(inputRef.current)
  const width = 8 + (showIcon ? 3 : 0) + (withTime ? 3 : 0)
  const style = { width: `${width}em`, fontSize: "1.1em" }
  const dateFormats = withTime
    ? Settings.dateFormats.forms.input.withTime
    : Settings.dateFormats.forms.input.date
  const inputFormat = dateFormats[0]
  const timePickerProps = !withTime
    ? {}
    : {
      precision: TimePrecision.MINUTE,
      selectAllOnFocus: true
      // FIXME: clicking a time arrow immediately closes the dialog;
      // see https://github.com/palantir/blueprint/issues/3474
      // showArrowButtons: true
    }
  return (
    <DateInput
      inputProps={{
        id,
        style,
        onBlur,
        inputRef: ref => (inputRef.current = ref)
      }}
      rightElement={rightElement}
      value={value && moment(value).toDate()}
      onChange={onChange}
      formatDate={date => moment(date).format(inputFormat)}
      parseDate={str => moment(str, dateFormats, true).toDate()}
      placeholder={inputFormat}
      maxDate={moment().add(20, "years").endOf("year").toDate()}
      canClearSelection={false}
      showActionsBar
      closeOnSelection={!withTime}
      timePickerProps={timePickerProps}
      popoverProps={{ usePortal: false }}
      disabled={disabled}
    />
  )
}
CustomDateInput.propTypes = {
  id: PropTypes.string,
  disabled: PropTypes.bool,
  showIcon: PropTypes.bool,
  withTime: PropTypes.bool,
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Date)
  ]),
  onChange: PropTypes.func,
  onBlur: PropTypes.func
}
CustomDateInput.defaultProps = {
  disabled: false,
  showIcon: true,
  withTime: false
}

export default CustomDateInput
<commit_msg>NCI-Agency/anet#3428: Avoid invalid dates<commit_after>import "@blueprintjs/core/lib/css/blueprint.css"
import { DateInput, TimePrecision } from "@blueprintjs/datetime"
import "@blueprintjs/datetime/lib/css/blueprint-datetime.css"
import moment from "moment"
import PropTypes from "prop-types"
import React, { useRef } from "react"
import CALENDAR_ICON from "resources/calendar.png"
import Settings from "settings"
import "./BlueprintOverrides.css"

const CalendarIcon = inputRef => (
  <img
    src={CALENDAR_ICON}
    alt=""
    title="Pick a date"
    height={24}
    style={{ verticalAlign: "middle" }}
    onClick={() => {
      if (inputRef && inputRef.focus) {
        inputRef.focus()
      }
    }}
  />
)

const CustomDateInput = ({
  id,
  disabled,
  showIcon,
  withTime,
  value,
  onChange,
  onBlur
}) => {
  const inputRef = useRef()
  const rightElement = showIcon && CalendarIcon(inputRef.current)
  const width = 8 + (showIcon ? 3 : 0) + (withTime ? 3 : 0)
  const style = { width: `${width}em`, fontSize: "1.1em" }
  const dateFormats = withTime
    ? Settings.dateFormats.forms.input.withTime
    : Settings.dateFormats.forms.input.date
  const inputFormat = dateFormats[0]
  const timePickerProps = !withTime
    ? {}
    : {
      precision: TimePrecision.MINUTE,
      selectAllOnFocus: true
      // FIXME: clicking a time arrow immediately closes the dialog;
      // see https://github.com/palantir/blueprint/issues/3474
      // showArrowButtons: true
    }
  return (
    <DateInput
      inputProps={{
        id,
        style,
        onBlur,
        inputRef: ref => (inputRef.current = ref)
      }}
      rightElement={rightElement}
      value={value && moment(value).toDate()}
      onChange={onChange}
      formatDate={date => {
        const dt = moment(date)
        return dt.isValid() ? dt.format(inputFormat) : ""
      }}
      parseDate={str => {
        const dt = moment(str, dateFormats, true)
        return dt.isValid() ? dt.toDate() : false
      }}
      placeholder={inputFormat}
      maxDate={moment().add(20, "years").endOf("year").toDate()}
      canClearSelection={false}
      showActionsBar
      closeOnSelection={!withTime}
      timePickerProps={timePickerProps}
      popoverProps={{ usePortal: false }}
      disabled={disabled}
    />
  )
}
CustomDateInput.propTypes = {
  id: PropTypes.string,
  disabled: PropTypes.bool,
  showIcon: PropTypes.bool,
  withTime: PropTypes.bool,
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Date)
  ]),
  onChange: PropTypes.func,
  onBlur: PropTypes.func
}
CustomDateInput.defaultProps = {
  disabled: false,
  showIcon: true,
  withTime: false
}

export default CustomDateInput
<|endoftext|>


<commit_before>import DocumentStore from '../stores/DocumentStore';

var DocumentActions = {

  fetchDocuments(request) {
    var documents = [];
    console.log('action', 'fetchDocument : ' + request);
    DocumentStore.StoreDocuments(documents);
  },

  fetchContent(documentId) {
    var content = {}
    console.log('action', 'fetchContent : ' + documentId);
    DocumentStore.StoreContent(content);
  }

}

export default DocumentActions;
<commit_msg>put ajax call in actions<commit_after>import DocumentStore from '../stores/DocumentStore';
import $ from 'jquery';

var DocumentActions = {

  fetchDocuments(request) {
    console.log('action', 'fetchDocument : ' + request);
    $.ajax({
      url: '/request/?req=' + request,
      dataType: 'json',
      type: 'GET',
      success: function(data) {
        DocumentStore.StoreDocuments(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('/request', status, err.toString());
      }.bind(this)
    });
  },

  fetchContent(documentId) {
    var content = {}
    console.log('action', 'fetchContent : ' + documentId);
    DocumentStore.StoreContent(content);
  }

};

export default DocumentActions;
<|endoftext|>


<commit_before><commit_msg>restored<commit_after><|endoftext|>


<commit_before>"use strict";

import * as kbpgp from "kbpgp"
const Constants = kbpgp.const;

import { assert, Buffer, check } from "verifyme_utility"
import * as sig from "../../node_modules/kbpgp/lib/openpgp/packet/signature"

import BlindingContext from "./../blinding/blinding_context"

/**
 * A kind of key signature packet where the signer
 * does not know whose key is signed.
 */
export default class BlindSignaturePacket extends sig.Signature
{
  /**
   * Creates a new signature packet.
   *
   * To avoid that the signer later finds a relationship between the
   * signature request and the published signature the signature creation
   * time is randomized.
   *
   * @param {KeyManager} target_key
   *    The key to sign stored in a {KeyManger}.
   * @param {KeyManager} sig_key
   *    The signers public key stored in a {KeyManger}.
   * @param {BlindingContext} context
   *    An algorithm based signing context to encode the prepared
   *    raw signature data.
   */
  constructor(target_key, sig_key, context)
  {
    assert(check.isKeyManager(target_key));
    assert(check.isKeyManager(sig_key));
    assert(context instanceof BlindingContext);

    const hashed_subpackets = [
      new sig.CreationTime(BlindSignaturePacket.calculateRandomCreationDate(target_key))
    ];

    const unhashed_subpackets = [
      new sig.Issuer(sig_key.get_pgp_key_id())
    ];

    const ctor_args = {
      hashed_subpackets: hashed_subpackets,
      key: sig_key.get_primary_keypair(),
      key_id: sig_key.get_pgp_key_id(),
      unhashed_subpackets: unhashed_subpackets,
      type: Constants.openpgp.sig_types.persona,
      version: Constants.openpgp.versions.signature.V4
    };

    super(ctor_args);

    this.tag = kbpgp.const.openpgp.packet_tags.signature;
    this.target_key = target_key;
    this.primary = target_key.pgp.key(target_key.pgp.primary);

    this.prepareRawSignature(context);
  }

  /**
   * Calculates a random creation time between the given keys creation und expire date.
   * If no expire date exists, the maximum possible date value is used.
   *
   * @param {KeyManager} target_key
   *    The key we use as to identify the lifespan.
   * @returns {number}
   *    A random integer number somewhere in the given keys lifespan.
   */
  static calculateRandomCreationDate(target_key)
  {
    assert(check.isKeyManager(target_key));

    const lifespan = target_key.primary.lifespan;
    let key_expire = lifespan.expire_in;

    // if no expire date is available use maximum possible date in the future (8640000000000000)
    //    - 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC.
    //      http://es5.github.io/#x15.9.1.1

    // pgp defines Time files as four-octet fields containing the number of seconds elapsed since 1/1/1970
    // so we have to use a smaller number (2^32 - 1)
    //    - https://tools.ietf.org/html/rfc4880#section-3.5
    if (null === key_expire || 0 >= key_expire) {
      key_expire = Math.pow(2, 32) - 1;
    }

    return Math.floor(lifespan.generated + Math.random() * (key_expire - lifespan.generated));
  }

  /**
   * Prepares the raw signature data.
   *
   * This data is unsigned and encoded for the blind sign process
   * where the given blinding context is used. To finalize the
   * signature data the related blind signature algorithm must be used.
   *
   * @param {BlindingContext} context
   *    This context should be created from the signers public key and
   *    is used to encode the data in preparation of the signing algorithm.
   */
  prepareRawSignature(context)
  {
    assert(context instanceof BlindingContext);

    const signData = this.generateSignaturePayload();

    this.raw_signature = context.encodeSignaturePayload(signData, this.hasher);
    this.signed_hash_value_hash = this.raw_signature.toBuffer().slice(0, 2);
  }

  /**
   * Generates the unsigned key signature payload.
   *
   *  # RFC 4880 - 5.2.3.  Version 4 Signature Packet Format
   *  # RFC 4880 - 5.2.4.  Computing Signatures
   *
   * @returns {Buffer}
   *    The raw unsinged signature data.
   */
  generateSignaturePayload()
  {
    const key_material_packet = this.target_key.pgp.key(this.target_key.pgp.primary);
    const pubKeyData = key_material_packet.to_signature_payload();

    const user_id_packet = this.target_key.get_userids_mark_primary()[0];
    const userIdData = user_id_packet.to_signature_payload();

    return Buffer.concat([
      pubKeyData, userIdData, this.generateSignatureData()
    ]);
  }

  /**
   * Generates the complete public signature packet information.
   * These information are part of the final signature hash but
   * they become also part of the unhashed part of the final signature
   * packet.
   *
   *  @see generateSignatureBody()
   *  @see generateSignatureTrailer()
   *
   * @returns {Buffer}
   *    Public signature packet information.
   */
  generateSignatureData()
  {
    const sigBody = this.generateSignatureBody();
    const sigTrailer = this.generateSignatureTrailer(sigBody.length);

    return Buffer.concat([sigBody, sigTrailer]);
  }

  /**
   * Signature trailer of six octets.
   *
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - version of signature packet (1 octet)
   *  - 0xFF (1 octet)
   *  - length of hashed data without trailer (4 octet big-endian)
   *
   * @param {number} hash_data_length
   *    The total length of the signature data.
   * @returns {Buffer}
   *    The signature trailer.
   */
  generateSignatureTrailer(hash_data_length)
  {
    assert(check.isInteger(hash_data_length));

    return Buffer.concat([
      new Buffer([
        this.version,
        0xff
      ]),
      kbpgp.util.uint_to_buffer(32, hash_data_length)
    ]);
  }

  /**
   * Prepares the part of the signature body that gets hashed.
   *
   * # RFC 4880 - 5.2.3.  Version 4 Signature Packet Format
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - version of signature packet (1 octet)
   *  - signature type (1 octet)
   *  - public key algorithm (1 octet)
   *  - hash algorithm (1 octet)
   *  - total length of hashed subpackets (2 octet)
   *  - hashed subpackets data (zero or more packets)
   *
   * @returns {Buffer}
   *    Part of the signature body to hash.
   */
  generateSignatureBody()
  {
    const hashedSubpkts = this.hashed_subpackets
      .map(subpacket => subpacket.to_buffer())
      .reduce((lhs, rhs) => Buffer.concat([lhs, rhs]));

    return Buffer.concat([
      new Buffer([
        this.version,
        this.type,
        this.key.type,
        this.hasher.type
      ]),
      kbpgp.util.uint_to_buffer(16, hashedSubpkts.length),
      hashedSubpkts
    ]);
  }

  /**
   * Generates the complete signed signature packet payload.
   *
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - signature body to hash (@see generateSignatureBody())
   *  - length of unhashed subpackets (2 octet)
   *  - unhashed subpackets (zero or more)
   *  - left 16 bits of the signed hash value (2 octet)
   *  - signed hash (one or more MPI)
   *
   * @returns {Buffer}
   *    The signed signature packet payload.
   *
   * #
   * # keep naming to overwrite Signature.write_unframed()
   * #
   */
  write_unframed()
  {
    const unhashed_packet_data = this.unhashed_subpackets.reduce(
      (prevValue, subpacket) => { return Buffer.concat([prevValue, subpacket.to_buffer()])},
      new Buffer({})
    );

    return Buffer.concat([
      this.generateSignatureBody(),
      kbpgp.util.uint_to_buffer(16, unhashed_packet_data.length),
      unhashed_packet_data,
      this.signed_hash_value_hash,
      this.sig
    ]);
  }
}
<commit_msg>Client BlindSignature: fixes expire date calculation<commit_after>"use strict";

import * as kbpgp from "kbpgp"
const Constants = kbpgp.const;

import { assert, Buffer, check } from "verifyme_utility"
import * as sig from "../../node_modules/kbpgp/lib/openpgp/packet/signature"

import BlindingContext from "./../blinding/blinding_context"

/**
 * A kind of key signature packet where the signer
 * does not know whose key is signed.
 */
export default class BlindSignaturePacket extends sig.Signature
{
  /**
   * Creates a new signature packet.
   *
   * To avoid that the signer later finds a relationship between the
   * signature request and the published signature the signature creation
   * time is randomized.
   *
   * @param {KeyManager} target_key
   *    The key to sign stored in a {KeyManger}.
   * @param {KeyManager} sig_key
   *    The signers public key stored in a {KeyManger}.
   * @param {BlindingContext} context
   *    An algorithm based signing context to encode the prepared
   *    raw signature data.
   */
  constructor(target_key, sig_key, context)
  {
    assert(check.isKeyManager(target_key));
    assert(check.isKeyManager(sig_key));
    assert(context instanceof BlindingContext);

    const hashed_subpackets = [
      new sig.CreationTime(BlindSignaturePacket.calculateRandomCreationDate(target_key))
    ];

    const unhashed_subpackets = [
      new sig.Issuer(sig_key.get_pgp_key_id())
    ];

    const ctor_args = {
      hashed_subpackets: hashed_subpackets,
      key: sig_key.get_primary_keypair(),
      key_id: sig_key.get_pgp_key_id(),
      unhashed_subpackets: unhashed_subpackets,
      type: Constants.openpgp.sig_types.persona,
      version: Constants.openpgp.versions.signature.V4
    };

    super(ctor_args);

    this.tag = kbpgp.const.openpgp.packet_tags.signature;
    this.target_key = target_key;
    this.primary = target_key.pgp.key(target_key.pgp.primary);

    this.prepareRawSignature(context);
  }

  /**
   * Calculates a random creation time between the given keys creation und expire date.
   * If no expire date exists, the maximum possible date value is used.
   *
   * @param {KeyManager} target_key
   *    The key we use as to identify the lifespan.
   * @returns {number}
   *    A random integer number somewhere in the given keys lifespan.
   */
  static calculateRandomCreationDate(target_key)
  {
    assert(check.isKeyManager(target_key));

    const lifespan = target_key.primary.lifespan;
    let key_expire = lifespan.expire_in;

    // if no expire date is available use maximum possible date in the future (8640000000000000)
    //    - 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC.
    //      http://es5.github.io/#x15.9.1.1

    // pgp defines Time files as four-octet fields containing the number of seconds elapsed since 1/1/1970
    // so we have to use a smaller number (2^32 - 1)
    //    - https://tools.ietf.org/html/rfc4880#section-3.5
    if (null === key_expire || 0 >= key_expire) {
      key_expire = Math.pow(2, 32) - lifespan.generated - 1;
    }

    return Math.floor(lifespan.generated + Math.random() * key_expire);
  }

  /**
   * Prepares the raw signature data.
   *
   * This data is unsigned and encoded for the blind sign process
   * where the given blinding context is used. To finalize the
   * signature data the related blind signature algorithm must be used.
   *
   * @param {BlindingContext} context
   *    This context should be created from the signers public key and
   *    is used to encode the data in preparation of the signing algorithm.
   */
  prepareRawSignature(context)
  {
    assert(context instanceof BlindingContext);

    const signData = this.generateSignaturePayload();

    this.raw_signature = context.encodeSignaturePayload(signData, this.hasher);
    this.signed_hash_value_hash = this.raw_signature.toBuffer().slice(0, 2);
  }

  /**
   * Generates the unsigned key signature payload.
   *
   *  # RFC 4880 - 5.2.3.  Version 4 Signature Packet Format
   *  # RFC 4880 - 5.2.4.  Computing Signatures
   *
   * @returns {Buffer}
   *    The raw unsinged signature data.
   */
  generateSignaturePayload()
  {
    const key_material_packet = this.target_key.pgp.key(this.target_key.pgp.primary);
    const pubKeyData = key_material_packet.to_signature_payload();

    const user_id_packet = this.target_key.get_userids_mark_primary()[0];
    const userIdData = user_id_packet.to_signature_payload();

    return Buffer.concat([
      pubKeyData, userIdData, this.generateSignatureData()
    ]);
  }

  /**
   * Generates the complete public signature packet information.
   * These information are part of the final signature hash but
   * they become also part of the unhashed part of the final signature
   * packet.
   *
   *  @see generateSignatureBody()
   *  @see generateSignatureTrailer()
   *
   * @returns {Buffer}
   *    Public signature packet information.
   */
  generateSignatureData()
  {
    const sigBody = this.generateSignatureBody();
    const sigTrailer = this.generateSignatureTrailer(sigBody.length);

    return Buffer.concat([sigBody, sigTrailer]);
  }

  /**
   * Signature trailer of six octets.
   *
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - version of signature packet (1 octet)
   *  - 0xFF (1 octet)
   *  - length of hashed data without trailer (4 octet big-endian)
   *
   * @param {number} hash_data_length
   *    The total length of the signature data.
   * @returns {Buffer}
   *    The signature trailer.
   */
  generateSignatureTrailer(hash_data_length)
  {
    assert(check.isInteger(hash_data_length));

    return Buffer.concat([
      new Buffer([
        this.version,
        0xff
      ]),
      kbpgp.util.uint_to_buffer(32, hash_data_length)
    ]);
  }

  /**
   * Prepares the part of the signature body that gets hashed.
   *
   * # RFC 4880 - 5.2.3.  Version 4 Signature Packet Format
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - version of signature packet (1 octet)
   *  - signature type (1 octet)
   *  - public key algorithm (1 octet)
   *  - hash algorithm (1 octet)
   *  - total length of hashed subpackets (2 octet)
   *  - hashed subpackets data (zero or more packets)
   *
   * @returns {Buffer}
   *    Part of the signature body to hash.
   */
  generateSignatureBody()
  {
    const hashedSubpkts = this.hashed_subpackets
      .map(subpacket => subpacket.to_buffer())
      .reduce((lhs, rhs) => Buffer.concat([lhs, rhs]));

    return Buffer.concat([
      new Buffer([
        this.version,
        this.type,
        this.key.type,
        this.hasher.type
      ]),
      kbpgp.util.uint_to_buffer(16, hashedSubpkts.length),
      hashedSubpkts
    ]);
  }

  /**
   * Generates the complete signed signature packet payload.
   *
   * # RFC 4880 - 5.2.4.  Computing Signatures
   *
   *  - signature body to hash (@see generateSignatureBody())
   *  - length of unhashed subpackets (2 octet)
   *  - unhashed subpackets (zero or more)
   *  - left 16 bits of the signed hash value (2 octet)
   *  - signed hash (one or more MPI)
   *
   * @returns {Buffer}
   *    The signed signature packet payload.
   *
   * #
   * # keep naming to overwrite Signature.write_unframed()
   * #
   */
  write_unframed()
  {
    const unhashed_packet_data = this.unhashed_subpackets.reduce(
      (prevValue, subpacket) => { return Buffer.concat([prevValue, subpacket.to_buffer()])},
      new Buffer({})
    );

    return Buffer.concat([
      this.generateSignatureBody(),
      kbpgp.util.uint_to_buffer(16, unhashed_packet_data.length),
      unhashed_packet_data,
      this.signed_hash_value_hash,
      this.sig
    ]);
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 *  client
 **/

/**
 *  client.common
 **/

/**
 *  client.common.auth
 **/

/**
 *  client.common.auth.register
 **/

/*global $, _, nodeca, window*/

/**
 *  client.common.auth.register.check_nick($elem, event)
 *
 *  send nick value on server
 *  and show error if nick exists
 **/
module.exports = function ($elem, event) {
  var nick = $elem.val();

  nodeca.server.users.auth.register.check_nick({nick: nick}, function(err, request){
    var $controll_group = $elem.parents('.control-group:first');
    var message;

    if (err) {
      if (err.statusCode === 409) {
        $controll_group.addClass('error');

        message = err.message['nick'];
        $elem.parent().find('.help-block').text(message);
        return;
      }
      message = nodeca.runtime.t('common.notice.internal_server_error');
      nodeca.client.common.notice('error', message);
      return;
    }

    if ($controll_group.hasClass('error')) {
      $controll_group.removeClass('error');

      message = nodeca.runtime.t('users.auth.reg_form.nick_help');
      $elem.parent().find('.help-block').text(message);
    }
  });
  return false;
};
<commit_msg>Fixed internal serrver error in nick checking<commit_after>'use strict';

/**
 *  client
 **/

/**
 *  client.common
 **/

/**
 *  client.common.auth
 **/

/**
 *  client.common.auth.register
 **/

/*global $, _, nodeca, window*/

/**
 *  client.common.auth.register.check_nick($elem, event)
 *
 *  send nick value on server
 *  and show error if nick exists
 **/
module.exports = function ($elem, event) {
  var nick = $elem.val();

  nodeca.server.users.auth.register.check_nick({nick: nick}, function(err, request){
    var $controll_group = $elem.parents('.control-group:first');
    var message;

    if (err) {
      if (err.statusCode === 409) {
        $controll_group.addClass('error');

        message = err.message['nick'];
        $elem.parent().find('.help-block').text(message);
        return;
      }
      message = nodeca.runtime.t('common.error.server_internal');
      nodeca.client.common.notice('error', message);
      return;
    }

    if ($controll_group.hasClass('error')) {
      $controll_group.removeClass('error');

      message = nodeca.runtime.t('users.auth.reg_form.nick_help');
      $elem.parent().find('.help-block').text(message);
    }
  });
  return false;
};
<|endoftext|>


<commit_before>/*globals fdom:true */
/*jslint indent:2,sloppy:true */

fdom.apis.set("core", {
  'createChannel': {type: "method", value: [], ret: {
    channel: "proxy",
    identifier: "string"
  }},
  'bindChannel': {type: "method", value: ["string"], ret: "proxy"},
  'getId': {type: "method", value: [], ret: ["array", "string"]}
});

fdom.apis.set("core.view", {
  'open': {type: "method", value: ["string", {
    'file': "string",
    'code': "string"
  }]},
  'show': {type: "method", value: []},
  'close': {type: "method", value: []},
  'postMessage': {type: "method", value: ["object"]},

  'message': {type: "event", value: "object"},
  'onClose': {type: "event", value: []}
});

fdom.apis.set("core.storage", {
  'keys': {type: "method", value: [], ret: ["array", "string"]},
  'get': {type: "method", value: ["string"], ret: "string"},
  'set': {type: "method", value: ["string", "string"], ret: "string"},
  'remove': {type: "method", value: ["string"], ret: "string"},
  'clear': {type: "method", value: []}
});

fdom.apis.set("core.socket", {
  'create': {type: "method", value: ["string", "object"], ret: {
    socketId: "number"
  }},
  'connect': {
    type: "method",
    value: ["number", "string", "number"],
    ret: "number"
  },
  'onData': {type: "event", value: {"socketId": "number", "data": "buffer"}},
  'write': {type: "method", value: ["number", "buffer"], ret: "number"},
  'disconnect': {type: "method", value: ["number"]},
  'destroy': {type: "method", value: ["number"]},
  'listen': {
    type: "method",
    value: ["number", "string", "number"],
    ret: "number"
  },
  'onConnection': {type: "event", value: {
    'serverSocketId': "number",
    'clientSocketId': "number"
  }},
  'onDisconnect': {type: "event", value: {
    "socketId": "number",
    "error": "string"
  }},
  'getInfo': {type: "method", value: ["number"], ret: {
    "type": "string",
    "connected": "boolean",
    "peerAddress": "string",
    "peerPort": "number",
    "localAddress": "string",
    "localPort": "number"
  }}
});

// A UDP socket.
// Generally, to use you just need to call bind() at which point onData
// events will start to flow. Note that bind() should only be called
// once per instance.
fdom.apis.set('core.udpsocket', {
  // Creates a socket, binds it to an interface and port and listens for
  // messages, dispatching each message as on onData event.
  // Returns an integer, with zero meaning success and any other value
  // being implementation-dependant.
  'bind': {
    type: 'method',
    value: [
      // Interface (address) on which to bind.
      'string',
      // Port on which to bind.
      'number'
    ],
    ret: 'number'
  },

  // Retrieves the state of the socket.
  // Returns an object with the following properties:
  //  - localAddress: the socket's local address, if bound
  //  - localPort: the socket's local port, if bound
  'getInfo': {type: 'method', value: [], ret: {
    'localAddress': 'string',
    'localPort': 'number'
  }},

  // Sends data to a server.
  // The socket must be bound.
  // Returns an integer indicating the number of bytes written, with no
  // guarantee that the remote side received the data.
  'sendTo': {
    type: 'method',
    value: [
      // Data to send.
      'buffer',
      // Destination address.
      'string',
      // Destination port.
      'number'
    ],
    ret: 'number'
  },

  // Releases all resources associated with this socket.
  // No-op if the socket is not bound.
  'destroy': {type: 'method', value: []},

  // Called once for each message received on this socket, once it's
  // been successfully bound.
  'onData': {
    type: 'event',
    value: {
      // Zero means success, any other value is implementation-dependent.
      'resultCode': 'number',
      // Address from which data was received.
      'address': 'string',
      // Port from which data was received.
      'port': 'number',
      // Data received.
      'data': 'buffer'
    }
  }
});

fdom.apis.set("core.runtime", {
  'createApp': {type: "method", value: ["string", "proxy"]},
  'resolve': {type: "method", value: ["string", "string"]},
  'needFile': {type: 'event', value: ["string", "string"]}
});

fdom.apis.set('core.echo', {
  'setup': {type: "method", value: ["string"]},
  'send': {type: "method", value: ["string"]},
  'message': {type: "event", value: "string"}
});

fdom.apis.set('core.peerconnection', {
  // Setup the link to the peer and options for this peer connection.
  'setup': {
    type: "method",
    value: [
      // The freedom.js channel identifier used to setup a signalling chanel.
      "string",
      // The peerName, used debugging and console messages.
      "string",
      // The list of STUN servers to use.
      // The format of a single entry is stun:HOST:PORT, where HOST
      // and PORT are a stun server hostname and port, respectively.
      ["array", "string"]
    ]
  },

  // Send a message to the peer.
  'send': {type: "method", value: [{
    // Data channel id. If provided, will be used as the channel label.
    // The behavior is undefined if the channel label doesn't exist.
    "channelLabel": "string",
    // One of the bellow should be defined; this is the data to send.
    "text": "string",
    "binary": "blob",
    "buffer": "buffer"
  }]},

  // Called when we get a message from the peer.
  'onReceived': {type: "event", value: {
    // The label/id of the data channel.
    "channelLabel": "string",
    // One the below will be specified.
    "text": "string",
    "binary": "blob",
    "buffer": "buffer"
  }},

  // Open the data channel with this label.
  'openDataChannel': {type: "method", value: ["string"]},
  // Close the data channel with this label.
  'closeDataChannel': {type: "method", value: ["string"]},

  // A channel with this id has been opened.
  'onOpenDataChannel': {type: "event", value: {"channelId": "string"}},
  // The channale with this id has been closed.
  'onCloseDataChannel': {type: "event", value: {"channelId": "string"}},

  // Returns the number of bytes that have queued using "send", but not
  // yet sent out. Currently just exposes:
  // http://www.w3.org/TR/webrtc/#widl-RTCDataChannel-bufferedAmount
  "getBufferedAmount": {type: "method", value: ["string"]},

  // Close the peer connection.
  'close': {type: "method", value: []},
  // The peer connection has been closed.
  'onClose': {type: "event", value: {}}
});

<commit_msg>Give "getBufferedAmount" for peerconnection a return type.<commit_after>/*globals fdom:true */
/*jslint indent:2,sloppy:true */

fdom.apis.set("core", {
  'createChannel': {type: "method", value: [], ret: {
    channel: "proxy",
    identifier: "string"
  }},
  'bindChannel': {type: "method", value: ["string"], ret: "proxy"},
  'getId': {type: "method", value: [], ret: ["array", "string"]}
});

fdom.apis.set("core.view", {
  'open': {type: "method", value: ["string", {
    'file': "string",
    'code': "string"
  }]},
  'show': {type: "method", value: []},
  'close': {type: "method", value: []},
  'postMessage': {type: "method", value: ["object"]},

  'message': {type: "event", value: "object"},
  'onClose': {type: "event", value: []}
});

fdom.apis.set("core.storage", {
  'keys': {type: "method", value: [], ret: ["array", "string"]},
  'get': {type: "method", value: ["string"], ret: "string"},
  'set': {type: "method", value: ["string", "string"], ret: "string"},
  'remove': {type: "method", value: ["string"], ret: "string"},
  'clear': {type: "method", value: []}
});

fdom.apis.set("core.socket", {
  'create': {type: "method", value: ["string", "object"], ret: {
    socketId: "number"
  }},
  'connect': {
    type: "method",
    value: ["number", "string", "number"],
    ret: "number"
  },
  'onData': {type: "event", value: {"socketId": "number", "data": "buffer"}},
  'write': {type: "method", value: ["number", "buffer"], ret: "number"},
  'disconnect': {type: "method", value: ["number"]},
  'destroy': {type: "method", value: ["number"]},
  'listen': {
    type: "method",
    value: ["number", "string", "number"],
    ret: "number"
  },
  'onConnection': {type: "event", value: {
    'serverSocketId': "number",
    'clientSocketId': "number"
  }},
  'onDisconnect': {type: "event", value: {
    "socketId": "number",
    "error": "string"
  }},
  'getInfo': {type: "method", value: ["number"], ret: {
    "type": "string",
    "connected": "boolean",
    "peerAddress": "string",
    "peerPort": "number",
    "localAddress": "string",
    "localPort": "number"
  }}
});

// A UDP socket.
// Generally, to use you just need to call bind() at which point onData
// events will start to flow. Note that bind() should only be called
// once per instance.
fdom.apis.set('core.udpsocket', {
  // Creates a socket, binds it to an interface and port and listens for
  // messages, dispatching each message as on onData event.
  // Returns an integer, with zero meaning success and any other value
  // being implementation-dependant.
  'bind': {
    type: 'method',
    value: [
      // Interface (address) on which to bind.
      'string',
      // Port on which to bind.
      'number'
    ],
    ret: 'number'
  },

  // Retrieves the state of the socket.
  // Returns an object with the following properties:
  //  - localAddress: the socket's local address, if bound
  //  - localPort: the socket's local port, if bound
  'getInfo': {type: 'method', value: [], ret: {
    'localAddress': 'string',
    'localPort': 'number'
  }},

  // Sends data to a server.
  // The socket must be bound.
  // Returns an integer indicating the number of bytes written, with no
  // guarantee that the remote side received the data.
  'sendTo': {
    type: 'method',
    value: [
      // Data to send.
      'buffer',
      // Destination address.
      'string',
      // Destination port.
      'number'
    ],
    ret: 'number'
  },

  // Releases all resources associated with this socket.
  // No-op if the socket is not bound.
  'destroy': {type: 'method', value: []},

  // Called once for each message received on this socket, once it's
  // been successfully bound.
  'onData': {
    type: 'event',
    value: {
      // Zero means success, any other value is implementation-dependent.
      'resultCode': 'number',
      // Address from which data was received.
      'address': 'string',
      // Port from which data was received.
      'port': 'number',
      // Data received.
      'data': 'buffer'
    }
  }
});

fdom.apis.set("core.runtime", {
  'createApp': {type: "method", value: ["string", "proxy"]},
  'resolve': {type: "method", value: ["string", "string"]},
  'needFile': {type: 'event', value: ["string", "string"]}
});

fdom.apis.set('core.echo', {
  'setup': {type: "method", value: ["string"]},
  'send': {type: "method", value: ["string"]},
  'message': {type: "event", value: "string"}
});

fdom.apis.set('core.peerconnection', {
  // Setup the link to the peer and options for this peer connection.
  'setup': {
    type: "method",
    value: [
      // The freedom.js channel identifier used to setup a signalling chanel.
      "string",
      // The peerName, used debugging and console messages.
      "string",
      // The list of STUN servers to use.
      // The format of a single entry is stun:HOST:PORT, where HOST
      // and PORT are a stun server hostname and port, respectively.
      ["array", "string"]
    ]
  },

  // Send a message to the peer.
  'send': {type: "method", value: [{
    // Data channel id. If provided, will be used as the channel label.
    // The behavior is undefined if the channel label doesn't exist.
    "channelLabel": "string",
    // One of the bellow should be defined; this is the data to send.
    "text": "string",
    "binary": "blob",
    "buffer": "buffer"
  }]},

  // Called when we get a message from the peer.
  'onReceived': {type: "event", value: {
    // The label/id of the data channel.
    "channelLabel": "string",
    // One the below will be specified.
    "text": "string",
    "binary": "blob",
    "buffer": "buffer"
  }},

  // Open the data channel with this label.
  'openDataChannel': {type: "method", value: ["string"]},
  // Close the data channel with this label.
  'closeDataChannel': {type: "method", value: ["string"]},

  // A channel with this id has been opened.
  'onOpenDataChannel': {type: "event", value: {"channelId": "string"}},
  // The channale with this id has been closed.
  'onCloseDataChannel': {type: "event", value: {"channelId": "string"}},

  // Returns the number of bytes that have queued using "send", but not
  // yet sent out. Currently just exposes:
  // http://www.w3.org/TR/webrtc/#widl-RTCDataChannel-bufferedAmount
  "getBufferedAmount": {type: "method",
                        value: ["string"],
                        ret: "number"},

  // Close the peer connection.
  'close': {type: "method", value: []},
  // The peer connection has been closed.
  'onClose': {type: "event", value: {}}
});

<|endoftext|>


<commit_before>var authDefender = require('./../libs/auth')();

module.exports = function (app) {
  var ExpertiseModel = app.dbExpertise;
  var mongoose    = require('mongoose');
  var AccountModel = app.dbUser;

  app.get('/api/expertises', authDefender.ensureAuthenticatedAsync, index);      // curl http://0.0.0.0:3000/api/expertises/
  app.post('/api/expertises', authDefender.ensureAuthenticatedAsync, create);    // curl -X POST http://0.0.0.0:3000/api/expertises --data "url"="http://.."
  app.get('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, show);    // curl http://0.0.0.0:3000/api/expertises/537f5
  app.put('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, update);  //curl -X PUT http://0.0.0.0:3000/api/expertises/537f5 --data "url"="http://..."
  app.delete('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, del); // curl -X DELETE http://0.0.0.0:3000/api/expertises/537f5

  function index(req, res) {
    var currentUser = authDefender.getCurrentUser(req);
    return ExpertiseModel.find({account: currentUser})
      .exec(function (err, features) {
        if (err) {
          return res.send( { error: err } );
        }
          var features = features;
          return ExpertiseModel.find({_id: {$in: currentUser.expertises}}).exec(function (err, result) {
            return res.send(features.concat(result));
          });
      });
  }
  function create(req, res) {
    var attrHash = req.body;
    attrHash['account'] = mongoose.Types.ObjectId(authDefender.getCurrentUser(req)._id);

//      attrHash['authorName'] = [acc.first_name, acc.last_name].join(' ');
      var feature = new ExpertiseModel(attrHash);
      feature.save(function (err, feature, numberAffected) {
        if (err) {
          return res.send( { error: err } );
        }
        return res.send(feature);
      });
  }
  function show(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);
    return ExpertiseModel.findOne({_id: objId, account: authDefender.getCurrentUser(req)}, function(err, feature){
      if (err) return res.send( { error: err } );
      return res.send(feature);
    })
  }
  function update(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);

    var attrHash = req.body;
    var account = attrHash.account;
    var acc = authDefender.getCurrentUser(req);

//    ExpertiseModel.findOneAndUpdate({_id: objId, account: authDefender.getCurrentUser(req)}, attrHash, {}).exec(function (err, feature) {
    ExpertiseModel.findOneAndUpdate({ _id: objId }, attrHash, {}).exec(function (err, feature) {
      if (err) {
        return res.send( { error: err } );
      }
      feature.save(function () {
        return res.send(feature);
      });

    });
  }

  function del(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);
    return ExpertiseModel.findOne({_id: objId}, function (err, feature) {
      return feature.remove(function (err) {
        if (err) {
          return res.send( { error: err } );
        } else {
          return res.send(feature);
        }
      });
    });
  }
};<commit_msg>FIX: adding alternative for new expertise<commit_after>var authDefender = require('./../libs/auth')();

module.exports = function (app) {
  var ExpertiseModel = app.dbExpertise;
  var mongoose    = require('mongoose');
  var AccountModel = app.dbUser;

  app.get('/api/expertises', authDefender.ensureAuthenticatedAsync, index);      // curl http://0.0.0.0:3000/api/expertises/
  app.post('/api/expertises', authDefender.ensureAuthenticatedAsync, create);    // curl -X POST http://0.0.0.0:3000/api/expertises --data "url"="http://.."
  app.get('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, show);    // curl http://0.0.0.0:3000/api/expertises/537f5
  app.put('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, update);  //curl -X PUT http://0.0.0.0:3000/api/expertises/537f5 --data "url"="http://..."
  app.delete('/api/expertises/:id', authDefender.ensureAuthenticatedAsync, del); // curl -X DELETE http://0.0.0.0:3000/api/expertises/537f5

  function index(req, res) {
    var currentUser = authDefender.getCurrentUser(req);
    return ExpertiseModel.find({account: currentUser})
      .exec(function (err, features) {
        if (err) {
          return res.send( { error: err } );
        }
          var features = features;
          return ExpertiseModel.find({_id: {$in: currentUser.expertises}}).exec(function (err, result) {
            return res.send(features.concat(result));
          });
      });
  }
  function create(req, res) {
    var attrHash = req.body;
    attrHash['account'] = mongoose.Types.ObjectId(authDefender.getCurrentUser(req)._id);

//      attrHash['authorName'] = [acc.first_name, acc.last_name].join(' ');
      var feature = new ExpertiseModel(attrHash);
      feature.save(function (err, feature, numberAffected) {
        if (err) {
          return res.send( { error: err } );
        }
        return res.send(feature);
      });
  }
  function show(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);
    return ExpertiseModel.findOne({_id: objId, account: authDefender.getCurrentUser(req)}, function(err, feature){
      if (err) return res.send( { error: err } );
      return res.send(feature);
    })
  }
  function update(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);

    var alternatives = req.body.alternatives;
    var criterions = req.body.criterions;
    var attrHash = {alternatives: alternatives, criterions: criterions};
    var account = attrHash.account;
    var acc = authDefender.getCurrentUser(req);

//    ExpertiseModel.findOneAndUpdate({_id: objId, account: authDefender.getCurrentUser(req)}, attrHash, {}).exec(function (err, feature) {
    ExpertiseModel.findOneAndUpdate({ _id: objId }, attrHash, {}).exec(function (err, feature) {
      if (err) {
        return res.send( { error: err } );
      }
      feature.save(function () {
        return res.send(feature);
      });

    });
  }

  function del(req, res) {
    var reqId = req.param('id');
    var objId = mongoose.Types.ObjectId(reqId);
    return ExpertiseModel.findOne({_id: objId}, function (err, feature) {
      return feature.remove(function (err) {
        if (err) {
          return res.send( { error: err } );
        } else {
          return res.send(feature);
        }
      });
    });
  }
};<|endoftext|>


<commit_before>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            "id": null,
            "topicId": $rootScope.selectedTopicId,
            "title": "",
            "documentTypeId": "1",
            "statusId": null,
            "previousDocumentId": null,
            "description": "",
            "sequence": 0,
            "comment": "",
            "targetGroups": [],
            "fields": [],
            "links": []
        }
    }

    function newProfile(standardId) {
        return {
            "id": null,
            "topicId": $rootScope.selectedTopicId,
            "title": "",
            "documentTypeId": "2",
            "statusId": null,
            "previousDocumentId": null,
            "description": "",
            "sequence": 0,
            "comment": "",
            "targetGroups": [],
            "fields": [],
            "links": [],
            "standardId": standardId
        }
    }

    var allDocuments = {
        34: {
            "id": "34",
            "timestamp": "2016-04-13 11:02:14",
            "title": "Sikkerhetskrav for systemer - selvdeklarering",
            "description": "",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [],
            "targetGroups": []
        },
        63: {
            "id": "63",
            "timestamp": "2016-04-27 13:08:31",
            "title": "Krav til tjenestebasert adressering og identifikatorer ved elektronisk samhandling",
            "description": "TBA",
            "statusId": null,
            "sequence": "0",
            "topicId": "141",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "69",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": "136.1"
                }
            ],
            "targetGroups": [
                {
                    "documentId": "63",
                    "description": "",
                    "actionId": null,
                    "deadline": "",
                    "mandatoryId": null,
                    "targetGroupId": "3"
                }
            ]
        },
        64: {
            "id": "64",
            "timestamp": "2016-04-28 11:55:06",
            "title": "TITLE TITLE TITLE",
            "description": "sdd",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": ""
                }
            ],
            "targetGroups": []
        },
        65: {
            "id": "65",
            "timestamp": "2016-04-28 12:02:33",
            "title": "asdsad",
            "description": "asdsda",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": ""
                }
            ],
            "targetGroups": []
        }
    };

    var current_document = newDocument();
    var documents = [];
    var link_category_list = [];

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
        console.log(current_document.fields);
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 6000);
                }
                ,
                function () {
                    console.log("New document could not be created");
                    $rootScope.notifyError("Standard kunne ikke opprettes", 6000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    setCurrentDocument(data);
                    documents.push(data);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 6000);
                    $rootScope.buttonState = 'editDocument';
                }
                ,
                function () {
                    $rootScope.notifyError("Standard kunne ikke opprettes", 6000);
                }
            );
        }
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){

                $rootScope.notifySuccess("Dokumentet ble slettet", 5000);
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 5000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == document.id) {
                setDocument(documents[i], document);
                break;
            }
        }
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getDocumentsByTopicId(id) {
        documents = [];
        $rootScope.get('topics/' + id, function (data) {
            Array.prototype.push.apply(documents, data.documents);

        }, function () {
        });
        return documents;
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
        console.log(link_category_list);
        console.log(current_document.links);
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        console.log(link_category_ids);
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        console.log(id);
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        return allDocuments;
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        getAllDocuments: getAllDocuments,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<commit_msg>Delete topics work<commit_after>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            "id": null,
            "topicId": $rootScope.selectedTopicId,
            "title": "",
            "documentTypeId": "1",
            "statusId": null,
            "previousDocumentId": null,
            "description": "",
            "sequence": 0,
            "comment": "",
            "targetGroups": [],
            "fields": [],
            "links": []
        }
    }

    function newProfile(standardId) {
        return {
            "id": null,
            "topicId": $rootScope.selectedTopicId,
            "title": "",
            "documentTypeId": "2",
            "statusId": null,
            "previousDocumentId": null,
            "description": "",
            "sequence": 0,
            "comment": "",
            "targetGroups": [],
            "fields": [],
            "links": [],
            "standardId": standardId
        }
    }

    var allDocuments = {
        34: {
            "id": "34",
            "timestamp": "2016-04-13 11:02:14",
            "title": "Sikkerhetskrav for systemer - selvdeklarering",
            "description": "",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [],
            "targetGroups": []
        },
        63: {
            "id": "63",
            "timestamp": "2016-04-27 13:08:31",
            "title": "Krav til tjenestebasert adressering og identifikatorer ved elektronisk samhandling",
            "description": "TBA",
            "statusId": null,
            "sequence": "0",
            "topicId": "141",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "69",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": "136.1"
                }
            ],
            "targetGroups": [
                {
                    "documentId": "63",
                    "description": "",
                    "actionId": null,
                    "deadline": "",
                    "mandatoryId": null,
                    "targetGroupId": "3"
                }
            ]
        },
        64: {
            "id": "64",
            "timestamp": "2016-04-28 11:55:06",
            "title": "TITLE TITLE TITLE",
            "description": "sdd",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": ""
                }
            ],
            "targetGroups": []
        },
        65: {
            "id": "65",
            "timestamp": "2016-04-28 12:02:33",
            "title": "asdsad",
            "description": "asdsda",
            "statusId": null,
            "sequence": "0",
            "topicId": "136",
            "comment": "",
            "documentTypeId": "2",
            "standardId": "70",
            "previousDocumentId": null,
            "profiles": [],
            "links": [],
            "fields": [
                {
                    "fieldId": "76",
                    "value": ""
                }
            ],
            "targetGroups": []
        }
    };

    var current_document = newDocument();
    var documents = [];
    var link_category_list = [];

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
        console.log(current_document.fields);
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 6000);
                }
                ,
                function () {
                    console.log("New document could not be created");
                    $rootScope.notifyError("Standard kunne ikke opprettes", 6000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    setCurrentDocument(data);
                    documents.push(data);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 6000);
                    $rootScope.buttonState = 'editDocument';
                }
                ,
                function () {
                    $rootScope.notifyError("Standard kunne ikke opprettes", 6000);
                }
            );
        }
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){
                deleteCurrentDocumentFromDocumentsList();
                $rootScope.notifySuccess("Dokumentet ble slettet", 5000);
                $rootScope.changeContentView('');
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 5000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == document.id) {
                setDocument(documents[i], document);
                break;
            }
        }
    }

    function deleteCurrentDocumentFromDocumentsList() {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == current_document.id) {
                documents.splice(i,1);
                break;
            }
        }
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getDocumentsByTopicId(id) {
        documents = [];
        $rootScope.get('topics/' + id, function (data) {
            Array.prototype.push.apply(documents, data.documents);

        }, function () {
        });
        return documents;
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
        console.log(link_category_list);
        console.log(current_document.links);
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        console.log(link_category_ids);
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        console.log(id);
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        return allDocuments;
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        getAllDocuments: getAllDocuments,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<|endoftext|>