How to use Doc method in Mocha

Best JavaScript code snippet using mocha

sidebars.js

Source:sidebars.js Github

copy

Full Screen

1module.exports = {2 "someSidebar": [3 {4 "collapsed": true,5 "type": "category",6 "label": "Introduction",7 "items": [8 {9 "type": "doc",10 "id": "introduction/index"11 },12 {13 "type": "doc",14 "id": "introduction/features"15 },16 {17 "type": "doc",18 "id": "introduction/architecture"19 }20 ]21 },22 {23 "collapsed": true,24 "type": "category",25 "label": "System Requirements",26 "items": [27 {28 "type": "doc",29 "id": "system-requirements/hardware/index"30 },31 {32 "collapsed": true,33 "type": "category",34 "label": "Software",35 "items": [36 {37 "type": "doc",38 "id": "system-requirements/software/index"39 },40 {41 "type": "doc",42 "id": "system-requirements/software/git"43 },44 {45 "type": "doc",46 "id": "system-requirements/software/java"47 },48 {49 "type": "doc",50 "id": "system-requirements/software/perl"51 },52 {53 "collapsed": true,54 "type": "category",55 "label": "PostgreSQL",56 "items": [57 {58 "type": "doc",59 "id": "system-requirements/software/postgres/postgres"60 },61 {62 "type": "doc",63 "id": "system-requirements/software/postgres/hikari"64 }65 ]66 },67 {68 "type": "doc",69 "id": "system-requirements/software/tomcat"70 },71 {72 "type": "doc",73 "id": "system-requirements/software/macs"74 },75 {76 "type": "doc",77 "id": "system-requirements/software/solr"78 },79 {80 "collapsed": true,81 "type": "category",82 "label": "Gradle",83 "items": [84 {85 "type": "doc",86 "id": "system-requirements/software/gradle/index"87 },88 {89 "type": "doc",90 "id": "system-requirements/software/gradle/faqs"91 }92 ]93 },94 {95 "type": "doc",96 "id": "system-requirements/software/intellij"97 },98 {99 "type": "doc",100 "id": "system-requirements/software/maven"101 }102 ]103 }104 ]105 },106 {107 "collapsed": true,108 "type": "category",109 "label": "Get started",110 "items": [111 {112 "type": "doc",113 "id": "get-started/tutorial/index"114 },115 {116 "type": "doc",117 "id": "get-started/tutorial/webapp"118 },119 {120 "type": "doc",121 "id": "get-started/tutorial/test-data"122 },123 {124 "type": "doc",125 "id": "get-started/quick-start"126 },127 {128 "type": "doc",129 "id": "get-started/create-your-mine"130 },131 {132 "type": "doc",133 "id": "get-started/testmine"134 },135 {136 "type": "doc",137 "id": "get-started/intermine-tests"138 }139 ]140 },141 {142 "collapsed": true,143 "type": "category",144 "label": "InterMine",145 "items": [146 {147 "type": "doc",148 "id": "intermine/intermine"149 },150 {151 "type": "doc",152 "id": "intermine/upgrade"153 },154 {155 "type": "doc",156 "id": "intermine/roadmap"157 },158 {159 "type": "doc",160 "id": "intermine/intermine-versions"161 },162 {163 "type": "doc",164 "id": "intermine/javadoc/index"165 },166 {167 "type": "doc",168 "id": "intermine/get-involved"169 },170 {171 "type": "doc",172 "id": "intermine/amazon"173 }174 ]175 },176 {177 "collapsed": true,178 "type": "category",179 "label": "Data Model",180 "items": [181 {182 "type": "doc",183 "id": "data-model/overview"184 },185 {186 "type": "doc",187 "id": "data-model/model"188 },189 {190 "type": "doc",191 "id": "data-model/data-labels"192 },193 {194 "type": "doc",195 "id": "api/pathquery"196 },197 {198 "type": "doc",199 "id": "data-model/overlaps"200 },201 {202 "type": "doc",203 "id": "data-model/model-ontologies"204 }205 ]206 },207 {208 "collapsed": true,209 "type": "category",210 "label": "Database",211 "items": [212 {213 "type": "doc",214 "id": "database/download-scripts"215 },216 {217 "collapsed": true,218 "type": "category",219 "label": "Data Sources",220 "items": [221 {222 "collapsed": true,223 "type": "category",224 "label": "Data Source Library",225 "items": [226 {227 "type": "doc",228 "id": "database/data-sources/library/index"229 },230 {231 "collapsed": true,232 "type": "category",233 "label": "Gene Ontology",234 "items": [235 {236 "type": "doc",237 "id": "database/data-sources/library/go/go-annotation"238 },239 {240 "type": "doc",241 "id": "database/data-sources/library/go/go-obo"242 }243 ]244 },245 {246 "collapsed": true,247 "type": "category",248 "label": "Homologue Data Sources",249 "items": [250 {251 "type": "doc",252 "id": "database/data-sources/library/homologues/index"253 },254 {255 "type": "doc",256 "id": "database/data-sources/library/homologues/treefam"257 },258 {259 "type": "doc",260 "id": "database/data-sources/library/homologues/homologene"261 },262 {263 "type": "doc",264 "id": "database/data-sources/library/homologues/orthodb"265 },266 {267 "type": "doc",268 "id": "database/data-sources/library/homologues/panther"269 },270 {271 "type": "doc",272 "id": "database/data-sources/library/homologues/compara"273 }274 ]275 },276 {277 "collapsed": true,278 "type": "category",279 "label": "Interactions",280 "items": [281 {282 "type": "doc",283 "id": "database/data-sources/library/interactions/biogrid"284 },285 {286 "type": "doc",287 "id": "database/data-sources/library/interactions/intact"288 },289 {290 "type": "doc",291 "id": "database/data-sources/library/interactions/intact-complexes"292 },293 {294 "type": "doc",295 "id": "database/data-sources/library/interactions/psi-mi-ontology"296 }297 ]298 },299 {300 "collapsed": true,301 "type": "category",302 "label": "Pathway data sources",303 "items": [304 {305 "type": "doc",306 "id": "database/data-sources/library/pathways/kegg"307 },308 {309 "type": "doc",310 "id": "database/data-sources/library/pathways/reactome"311 }312 ]313 },314 {315 "collapsed": true,316 "type": "category",317 "label": "Proteins",318 "items": [319 {320 "type": "doc",321 "id": "database/data-sources/library/proteins/uniprot"322 },323 {324 "type": "doc",325 "id": "database/data-sources/library/proteins/interpro"326 }327 ]328 },329 {330 "collapsed": true,331 "type": "category",332 "label": "Publications",333 "items": [334 {335 "type": "doc",336 "id": "database/data-sources/library/publications/pubmed"337 },338 {339 "type": "doc",340 "id": "database/data-sources/library/publications/publications"341 }342 ]343 },344 {345 "type": "doc",346 "id": "database/data-sources/library/ncbi-gene"347 },348 {349 "type": "doc",350 "id": "database/data-sources/library/chado"351 },352 {353 "type": "doc",354 "id": "database/data-sources/library/fasta"355 },356 {357 "type": "doc",358 "id": "database/data-sources/library/gff"359 },360 {361 "type": "doc",362 "id": "database/data-sources/library/identifiers/index"363 },364 {365 "type": "doc",366 "id": "database/data-sources/library/intermine-items-xml"367 },368 {369 "type": "doc",370 "id": "database/data-sources/library/omim"371 },372 {373 "type": "doc",374 "id": "database/data-sources/library/organism"375 },376 {377 "type": "doc",378 "id": "database/data-sources/library/so"379 },380 {381 "type": "doc",382 "id": "database/data-sources/library/uberon"383 },384 {385 "type": "doc",386 "id": "database/data-sources/library/data-sources"387 },388 {389 "type": "doc",390 "id": "database/data-sources/library/data-sets"391 },392 {393 "type": "doc",394 "id": "database/data-sources/library/variation/vcf"395 }396 ]397 },398 {399 "type": "doc",400 "id": "database/data-sources/custom/index"401 },402 {403 "collapsed": true,404 "type": "category",405 "label": "InterMine Items XML",406 "items": [407 {408 "type": "doc",409 "id": "database/data-sources/apis/index"410 },411 {412 "type": "doc",413 "id": "database/data-sources/apis/java-items-api"414 },415 {416 "type": "doc",417 "id": "database/data-sources/apis/perl-items-api"418 },419 {420 "type": "doc",421 "id": "database/data-sources/apis/python-items-api"422 }423 ]424 },425 {426 "type": "doc",427 "id": "database/data-sources/id-resolvers"428 },429 {430 "type": "doc",431 "id": "database/data-sources/data-licences"432 }433 ]434 },435 {436 "collapsed": true,437 "type": "category",438 "label": "Database Building",439 "items": [440 {441 "type": "doc",442 "id": "database/database-building/index"443 },444 {445 "type": "doc",446 "id": "database/database-building/build-script"447 },448 {449 "type": "doc",450 "id": "database/database-building/project-xml"451 },452 {453 "type": "doc",454 "id": "database/database-building/data-integration"455 },456 {457 "type": "doc",458 "id": "database/database-building/model-merging"459 },460 {461 "type": "doc",462 "id": "database/database-building/primary-keys"463 },464 {465 "type": "doc",466 "id": "database/database-building/priority-config"467 },468 {469 "type": "doc",470 "id": "database/database-building/post-processing/index"471 },472 {473 "type": "doc",474 "id": "database/database-building/post-build-updating-with-sql-triggers"475 },476 {477 "type": "doc",478 "id": "database/database-building/debugging"479 }480 ]481 },482 {483 "collapsed": true,484 "type": "category",485 "label": "Data Integrity Checks",486 "items": [487 {488 "type": "doc",489 "id": "database/data-integrity-checks/template-comparison"490 },491 {492 "type": "doc",493 "id": "database/data-integrity-checks/acceptance-tests"494 }495 ]496 },497 {498 "collapsed": true,499 "type": "category",500 "label": "InterMine performance",501 "items": [502 {503 "type": "doc",504 "id": "database/performance/data-loading"505 },506 {507 "type": "doc",508 "id": "database/performance/precomputing"509 },510 {511 "type": "doc",512 "id": "database/performance/configuration"513 }514 ]515 }516 ]517 },518 {519 "collapsed": true,520 "type": "category",521 "label": "Web Application",522 "items": [523 {524 "type": "doc",525 "id": "webapp/bluegenes/index"526 },527 {528 "type": "doc",529 "id": "webapp/layout/index"530 },531 {532 "type": "doc",533 "id": "webapp/homepage/index"534 },535 {536 "collapsed": true,537 "type": "category",538 "label": "Report Page",539 "items": [540 {541 "type": "doc",542 "id": "webapp/report-page/permanentURL"543 }544 ]545 },546 {547 "collapsed": true,548 "type": "category",549 "label": "Lists",550 "items": [551 {552 "type": "doc",553 "id": "webapp/lists/lists-page"554 },555 {556 "type": "doc",557 "id": "webapp/lists/list-upload"558 },559 {560 "type": "doc",561 "id": "webapp/lists/list-upgrade"562 },563 {564 "collapsed": true,565 "type": "category",566 "label": "List widgets",567 "items": [568 {569 "type": "doc",570 "id": "webapp/lists/list-widgets/index"571 },572 {573 "type": "doc",574 "id": "webapp/lists/list-widgets/embedding"575 },576 {577 "type": "doc",578 "id": "webapp/lists/list-widgets/enrichment-widgets"579 }580 ]581 }582 ]583 },584 {585 "type": "doc",586 "id": "webapp/template-queries/index"587 },588 {589 "type": "doc",590 "id": "webapp/query-results/index"591 },592 {593 "type": "doc",594 "id": "webapp/query-builder/index"595 },596 {597 "type": "doc",598 "id": "webapp/keyword-search/index"599 },600 {601 "collapsed": true,602 "type": "category",603 "label": "Customise Web Application",604 "items": [605 {606 "type": "doc",607 "id": "webapp/properties/web-properties"608 },609 {610 "type": "doc",611 "id": "webapp/properties/oauth2"612 },613 {614 "type": "doc",615 "id": "webapp/properties/webconfig-model"616 },617 {618 "type": "doc",619 "id": "webapp/properties/class-keys"620 }621 ]622 },623 {624 "type": "doc",625 "id": "webapp/markup/index"626 },627 {628 "type": "doc",629 "id": "webapp/https"630 },631 {632 "type": "doc",633 "id": "webapp/jbrowse"634 },635 {636 "collapsed": true,637 "type": "category",638 "label": "Tool API",639 "items": [640 {641 "type": "doc",642 "id": "webapp/tool-api/overview"643 },644 {645 "type": "doc",646 "id": "webapp/tool-api/tutorial"647 },648 {649 "type": "doc",650 "id": "webapp/tool-api/specification"651 }652 ]653 },654 {655 "collapsed": true,656 "type": "category",657 "label": "Monitoring Site Usage",658 "items": [659 {660 "type": "doc",661 "id": "webapp/monitoring-site-usage/google-analytics"662 }663 ]664 },665 {666 "type": "doc",667 "id": "webapp/admin/index"668 },669 {670 "collapsed": true,671 "type": "category",672 "label": "User Accounts",673 "items": [674 {675 "type": "doc",676 "id": "webapp/user-accounts/userprofile"677 }678 ]679 },680 {681 "type": "doc",682 "id": "webapp/frictionless/index"683 }684 ]685 },686 {687 "collapsed": true,688 "type": "category",689 "label": "Web Services",690 "items": [691 { 692 "type": "doc",693 "id": "web-services/index"694 },695 {696 "type": "doc",697 "id": "web-services/intermine-properties"698 },699 { 700 "type": "doc",701 "id": "web-services/authentication"702 },703 {704 "type": "doc",705 "id": "web-services/diagnostic"706 },707 {708 "type": "doc",709 "id": "web-services/iodocs"710 }]711 },712 {713 "collapsed": true,714 "type": "category",715 "label": "Support",716 "items": [717 {718 "type": "doc",719 "id": "support/mailing-list"720 },721 {722 "type": "doc",723 "id": "support/troubleshooting-tips"724 }725 ]726 },727 {728 "collapsed": true,729 "type": "category",730 "label": "About Us",731 "items": [732 {733 "type": "doc",734 "id": "about/index"735 },736 {737 "type": "doc",738 "id": "about/contact-us"739 },740 {741 "type": "doc",742 "id": "about/privacy-policy"743 }744 ]745 }746 ]...

Full Screen

Full Screen

Doc.test.jsx

Source:Doc.test.jsx Github

copy

Full Screen

1const extensions = require('@readme/oas-extensions');2const { Request, Response } = require('node-fetch');3const Oas = require('oas');4const { Button, Tabs } = require('@readme/ui/.bundles/es/ui/components');5const { TutorialModal, TutorialTile } = require('@readme/ui/.bundles/es/ui/compositions');6const { cmVariableContext: TutorialVariableContext } = require('@readme/ui/.bundles/es/views');7const { DEFAULT_TUTORIAL } = require('@readme/ui/.bundles/es/ui/compositions/Tutorials/Modal/constants/stepDefaults');8global.Request = Request;9const React = require('react');10const { shallow, mount } = require('enzyme');11const Doc = require('../src/Doc');12const ErrorBoundary = require('../src/ErrorBoundary');13const petstore = require('@readme/oas-examples/3.0/json/petstore.json');14const uspto = require('@readme/oas-examples/3.0/json/uspto.json');15const petstoreWithAuth = require('./__fixtures__/petstore/oas.json');16const multipleSecurities = require('./__fixtures__/multiple-securities/oas.json');17const oas = new Oas(petstore);18const props = {19 auth: {},20 doc: {21 api: { method: 'get' },22 formData: { path: { petId: '1' }, auth: { api_key: '' } },23 slug: 'slug',24 swagger: { path: '/pet/{petId}' },25 title: 'Title',26 type: 'endpoint',27 },28 language: 'node',29 lazy: false,30 oas,31 oauth: false,32 onAuthChange: () => {},33 onAuthGroupChange: () => {},34 setLanguage: () => {},35 suggestedEdits: false,36 tryItMetrics: () => {},37 ui: {38 Button,39 Tabs,40 tutorials: {41 DEFAULT_TUTORIAL,42 TutorialModal,43 TutorialTile,44 TutorialVariableContext,45 },46 },47};48const petExample = {49 category: {50 id: 0,51 name: 'string',52 },53 name: 'doggie',54 photoUrls: ['string'],55 status: 'available',56 tags: [57 {58 id: 0,59 name: 'string',60 },61 ],62};63function assertDocElements(component, doc) {64 expect(component.find(`#page-${doc.slug}`)).toHaveLength(1);65 expect(component.find('a.anchor-page-title')).toHaveLength(1);66 expect(component.find('h2').text()).toBe(doc.title);67}68beforeAll(async () => {69 await oas.dereference();70});71test('should output a div', () => {72 const doc = shallow(<Doc {...props} />);73 doc.setState({ showEndpoint: true });74 assertDocElements(doc, props.doc);75 expect(doc.find('.hub-api')).toHaveLength(1);76 expect(doc.find('PathUrl')).toHaveLength(1);77 expect(doc.find('CodeSample')).toHaveLength(1);78 // This test needs the component to be `mount()`ed but for some reason when I mount in this test it makes the test79 // below that uses `jest.useFakeTimers()` fail ¯\_(ツ)_/¯. Skipping for now.80 // expect(doc.find('Params').length).toBe(1);81 expect(doc.find('Content')).toHaveLength(1);82});83test('should render straight away if `appearance.splitReferenceDocs` is true', () => {84 const doc = mount(85 <Doc86 {...props}87 appearance={{88 splitReferenceDocs: true,89 }}90 />91 );92 expect(doc.find('Waypoint')).toHaveLength(0);93});94test('should render a manual endpoint', () => {95 const doc = JSON.parse(JSON.stringify(props.doc));96 doc.api = {97 ...doc.api,98 examples: {99 codes: [],100 },101 params: [102 {103 default: 'test',104 desc: 'test',105 in: 'path',106 name: 'test',107 ref: '',108 required: false,109 type: 'string',110 },111 ],112 };113 const node = mount(114 <Doc115 {...props}116 appearance={{117 splitReferenceDocs: true,118 }}119 doc={doc}120 oas={props.oas}121 />122 );123 assertDocElements(node, doc);124 expect(node.find('Params')).toHaveLength(1);125});126test('should work without a doc.swagger/doc.path/oas', () => {127 const doc = { title: 'title', slug: 'slug', type: 'basic' };128 const docComponent = shallow(129 <Doc130 auth={{}}131 doc={doc}132 language="node"133 oas={new Oas()}134 oauth={false}135 onAuthChange={() => {}}136 onAuthGroupChange={() => {}}137 setLanguage={() => {}}138 suggestedEdits139 tryItMetrics={() => {}}140 />141 );142 expect(docComponent.find('Waypoint')).toHaveLength(1);143 docComponent.setState({ showEndpoint: true });144 assertDocElements(docComponent, doc);145 expect(docComponent.find('.hub-api')).toHaveLength(0);146 expect(docComponent.find('Content')).toHaveLength(1);147});148test('should still display `Content` with column-style layout', () => {149 const doc = { title: 'title', slug: 'slug', type: 'basic' };150 const docComponent = shallow(151 <Doc152 appearance={{ referenceLayout: 'column' }}153 auth={{}}154 doc={doc}155 language="node"156 oas={new Oas()}157 oauth={false}158 onAuthChange={() => {}}159 onAuthGroupChange={() => {}}160 setLanguage={() => {}}161 suggestedEdits162 tryItMetrics={() => {}}163 />164 );165 docComponent.setState({ showEndpoint: true });166 assertDocElements(docComponent, doc);167 expect(docComponent.find('.hub-api')).toHaveLength(1);168 expect(docComponent.find('Content')).toHaveLength(2);169});170describe('state.dirty', () => {171 it('should default to false', () => {172 const doc = shallow(<Doc {...props} />);173 expect(doc.state('dirty')).toStrictEqual({ form: false, json: false });174 });175 it('should switch to true on form change', () => {176 const doc = shallow(<Doc {...props} />);177 doc.instance().onChange({ a: 1 });178 expect(doc.state('dirty')).toStrictEqual({ form: true, json: false });179 });180});181describe('onSubmit', () => {182 const { fetch } = window;183 afterEach(() => {184 window.fetch = fetch;185 });186 it('should display authentication warning if auth is required for endpoint', () => {187 jest.useFakeTimers();188 const petstoreWithAuthOas = new Oas(petstoreWithAuth);189 const doc = mount(<Doc {...props} oas={petstoreWithAuthOas} />);190 doc.instance().onSubmit();191 expect(doc.state('showAuthBox')).toBe(true);192 jest.runAllTimers();193 expect(doc.state('needsAuth')).toBe(true);194 });195 it('should make request on Submit', async () => {196 expect.assertions(3);197 const petstoreWithAuthOas = new Oas(petstoreWithAuth);198 await petstoreWithAuthOas.dereference();199 const props2 = {200 auth: { petstore_auth: 'api-key' },201 doc: {202 title: 'Title',203 slug: 'slug',204 type: 'endpoint',205 swagger: { path: '/pet' },206 api: { method: 'post' },207 formData: {208 body: {209 name: '1',210 photoUrls: ['1'],211 },212 },213 onSubmit: () => {},214 },215 language: 'node',216 oas: petstoreWithAuthOas,217 oauth: false,218 setLanguage: () => {},219 };220 window.fetch = request => {221 expect(request.url).toContain(petstoreWithAuthOas.servers[0].url);222 return Promise.resolve(223 new Response(JSON.stringify({ id: 1 }), {224 headers: { 'content-type': 'application/json' },225 })226 );227 };228 const doc = mount(<Doc {...props} {...props2} />);229 return doc230 .instance()231 .onSubmit()232 .then(() => {233 expect(doc.state('loading')).toBe(false);234 expect(doc.state('result')).not.toBeNull();235 });236 });237 it('should make request to the proxy url if necessary', () => {238 expect.assertions(1);239 const proxyOas = new Oas({240 servers: [{ url: 'http://example.com' }],241 'x-readme': {242 [extensions.PROXY_ENABLED]: true,243 },244 paths: {245 '/pet/{petId}': {246 get: {247 responses: {248 default: {249 description: 'desc',250 },251 },252 },253 },254 },255 });256 const doc = mount(<Doc {...props} oas={proxyOas} />);257 window.fetch = request => {258 expect(request.url).toContain(`https://try.readme.io/${proxyOas.servers[0].url}`);259 return Promise.resolve(new Response());260 };261 return doc.instance().onSubmit();262 });263 it('should call `tryItMetrics` on success', async () => {264 const tryItMetrics = jest.fn();265 const doc = mount(<Doc {...props} auth={{ api_key: 'api-key' }} tryItMetrics={tryItMetrics} />);266 window.fetch = () => {267 return Promise.resolve(new Response());268 };269 await doc.instance().onSubmit();270 expect(tryItMetrics).toHaveBeenCalled();271 });272});273describe('toggleAuth', () => {274 it('toggleAuth should change state of showAuthBox', () => {275 const doc = shallow(<Doc {...props} />);276 expect(doc.state('showAuthBox')).toBe(false);277 doc.instance().toggleAuth({ preventDefault() {} });278 expect(doc.state('showAuthBox')).toBe(true);279 doc.instance().toggleAuth({ preventDefault() {} });280 expect(doc.state('showAuthBox')).toBe(false);281 });282});283describe('state.loading', () => {284 it('should default to false', () => {285 const doc = shallow(<Doc {...props} />);286 expect(doc.state('loading')).toBe(false);287 });288});289describe('suggest edits', () => {290 it('should not show if suggestedEdits is false', () => {291 const doc = shallow(<Doc {...props} suggestedEdits={false} />);292 expect(doc.find('a.hub-reference-edit.pull-right')).toHaveLength(0);293 });294 it('should show icon if suggested edits is true', () => {295 const doc = shallow(<Doc {...props} suggestedEdits />);296 expect(doc.find('a.hub-reference-edit.pull-right')).toHaveLength(1);297 });298 it('should have child project if baseUrl is set', () => {299 const doc = shallow(<Doc {...{ baseUrl: '/child', ...props }} suggestedEdits />);300 expect(doc.find('a.hub-reference-edit.pull-right').prop('href')).toBe(`/child/reference-edit/${props.doc.slug}`);301 });302});303describe('ResponseSchema', () => {304 it('should render ResponseSchema if endpoint does have a response', async () => {305 const petstoreWithAuthOas = new Oas(petstoreWithAuth);306 await petstoreWithAuthOas.dereference();307 const doc = shallow(<Doc {...props} oas={petstoreWithAuthOas} />);308 doc.setState({ showEndpoint: true });309 expect(doc.find('ResponseSchema')).toHaveLength(1);310 });311 it('should not render ResponseSchema if endpoint does not have a response', async () => {312 const multipleSecuritiesOas = new Oas(multipleSecurities);313 await multipleSecuritiesOas.dereference();314 const doc = shallow(315 <Doc316 {...props}317 doc={{318 title: 'Title',319 slug: 'slug',320 type: 'endpoint',321 swagger: { path: '/unknown-scheme' },322 api: { method: 'post' },323 }}324 oas={multipleSecuritiesOas}325 />326 );327 expect(doc.find('ResponseSchema')).toHaveLength(0);328 });329});330describe('RenderLogs', () => {331 it('should return a log component', () => {332 const doc = shallow(<Doc {...props} Logs={() => {}} />);333 const res = doc.instance().renderLogs();334 expect(typeof res).toBe('object');335 });336});337describe('themes', () => {338 it('should output code samples and responses in the right column', () => {339 const doc = shallow(<Doc {...props} appearance={{ referenceLayout: 'column' }} />);340 doc.setState({ showEndpoint: true });341 expect(doc.find('.hub-reference-right').find('CodeSample')).toHaveLength(1);342 expect(doc.find('.hub-reference-right').find('Response')).toHaveLength(1);343 });344});345describe('error handling', () => {346 const brokenOas = new Oas({347 paths: {348 '/path': {349 post: {350 requestBody: {351 $ref: '#/components/schemas/UnknownSchema',352 },353 },354 },355 },356 });357 const docProps = {358 title: 'title',359 slug: 'slug',360 type: 'endpoint',361 swagger: { path: '/path' },362 api: { method: 'post' },363 };364 const originalConsole = console;365 // We're testing errors here, so we don't need `console.error` logs spamming the test output.366 beforeEach(() => {367 // eslint-disable-next-line no-console368 console.error = () => {};369 });370 afterEach(() => {371 // eslint-disable-next-line no-console372 console.error = originalConsole.error;373 });374 it('should output with a masked error message if the endpoint fails to load', () => {375 const doc = mount(<Doc {...props} doc={docProps} maskErrorMessages={true} oas={brokenOas} />);376 expect(doc.find(ErrorBoundary)).toHaveLength(1);377 const html = doc.html();378 expect(html).not.toMatch('support@readme.io');379 expect(html).toMatch("endpoint's documentation");380 });381 describe('support-focused error messaging', () => {382 it('should output with an error message if the endpoint fails to load, with a unique error event id', () => {383 const doc = mount(<Doc {...props} doc={docProps} maskErrorMessages={false} oas={brokenOas} />);384 doc.setState({ showEndpoint: true });385 const html = doc.html();386 expect(doc.find(ErrorBoundary)).toHaveLength(1);387 expect(html).toMatch('support@readme.io');388 expect(html).toMatch("endpoint's documentation");389 });390 });391 it('should call the onError handler', () => {392 const mockErrorHandler = jest.fn();393 const doc = mount(394 <Doc {...props} doc={docProps} maskErrorMessages={false} oas={brokenOas} onError={() => mockErrorHandler()} />395 );396 doc.setState({ showEndpoint: true });397 const html = doc.html();398 expect(mockErrorHandler).toHaveBeenCalled();399 expect(doc.find(ErrorBoundary)).toHaveLength(1);400 expect(html).toMatch('support@readme.io');401 expect(html).toMatch("endpoint's documentation");402 expect(html).toMatch(/ERR-([0-9A-Z]{6})/);403 });404});405describe('#enableRequestBodyJsonEditor', () => {406 it('should not show the editor on an operation without a request body', () => {407 const doc = shallow(<Doc {...props} enableRequestBodyJsonEditor={true} />);408 expect(doc.find('Tabs')).toHaveLength(0);409 });410 it('should not show the editor on an operation with a non-json request body', async () => {411 const usptoOas = new Oas(uspto);412 await usptoOas.dereference();413 const doc = mount(414 <Doc415 {...props}416 doc={{417 ...props.doc,418 api: { method: 'post' },419 swagger: { path: '/{dataset}/{version}/records' },420 }}421 enableRequestBodyJsonEditor={true}422 oas={usptoOas}423 />424 );425 expect(doc.find('Tabs')).toHaveLength(0);426 });427 it('should show the editor on an operation with a json-compatible request body', () => {428 const doc = mount(429 <Doc430 {...props}431 doc={{432 ...props.doc,433 api: { method: 'post' },434 swagger: { path: '/pet' },435 }}436 enableRequestBodyJsonEditor={true}437 oas={oas}438 />439 );440 expect(doc.find('Tabs')).toHaveLength(1);441 });442 describe('#formDataJson', () => {443 it('should fill formDataJson with an example request body', () => {444 const doc = mount(445 <Doc446 {...props}447 doc={{448 ...props.doc,449 api: { method: 'post' },450 swagger: { path: '/pet' },451 }}452 enableRequestBodyJsonEditor={true}453 oas={oas}454 />455 );456 expect(doc.state('formDataJson')).toStrictEqual(petExample);457 expect(doc.state('formDataJsonOriginal')).toStrictEqual(doc.state('formDataJson'));458 expect(doc.state('formDataJsonRaw')).toMatch('"status": "available"');459 });460 });461});462describe('#resetForm()', () => {463 it('should reset formDataJson', () => {464 const doc = mount(465 <Doc466 {...props}467 doc={{468 ...props.doc,469 api: { method: 'post' },470 swagger: { path: '/pet' },471 }}472 enableRequestBodyJsonEditor={true}473 oas={oas}474 />475 );476 expect(doc.state('formDataJson')).toStrictEqual(petExample);477 doc.setState({ formDataJson: { name: 'buster' } });478 doc.instance().resetForm();479 expect(doc.state('formDataJson')).toStrictEqual(petExample);480 expect(doc.state('formDataJsonRaw')).toMatch('"status": "available"');481 expect(doc.state('validationErrors')).toStrictEqual({ form: false, json: false });482 expect(doc.state('dirty')).toStrictEqual({ form: true, json: false });483 });484});485describe('#onJsonChange()', () => {486 it('should update formDataJson when given valid json', () => {487 const doc = shallow(488 <Doc489 {...props}490 doc={{491 ...props.doc,492 api: { method: 'post' },493 swagger: { path: '/pet' },494 }}495 enableRequestBodyJsonEditor={true}496 oas={oas}497 />498 );499 doc.instance().onJsonChange(JSON.stringify({ name: 'buster' }));500 expect(doc.state('formDataJson')).toStrictEqual({ name: 'buster' });501 expect(doc.state('formDataJsonRaw')).toStrictEqual(JSON.stringify({ name: 'buster' }));502 expect(doc.state('validationErrors')).toStrictEqual({ form: false, json: false });503 expect(doc.state('dirty')).toStrictEqual({ form: false, json: true });504 });505 it('should set validation errors when given invalid JSON', () => {506 const doc = shallow(507 <Doc508 {...props}509 doc={{510 ...props.doc,511 api: { method: 'post' },512 swagger: { path: '/pet' },513 }}514 enableRequestBodyJsonEditor={true}515 oas={oas}516 />517 );518 doc.instance().onJsonChange(JSON.stringify({ name: 'buster' }));519 doc.instance().onJsonChange('{ invalid json }');520 expect(doc.state('formDataJson')).toStrictEqual({ name: 'buster' });521 expect(doc.state('formDataJsonRaw')).toStrictEqual('{ invalid json }');522 expect(doc.state('validationErrors')).toStrictEqual({523 form: false,524 json: expect.any(String),525 });526 expect(doc.state('dirty')).toStrictEqual({ form: false, json: true });527 });528});529describe('#onModeChange()', () => {530 it('should change the editing mode', () => {531 const doc = shallow(<Doc {...props} />);532 expect(doc.state('editingMode')).toBe('form');533 doc.instance().onModeChange('JSON');534 expect(doc.state('editingMode')).toBe('json');535 });536});537describe('#isDirty()', () => {538 it('should return a dirty state based on the current editing mode', () => {539 const doc = shallow(<Doc {...props} />);540 doc.setState({ dirty: { form: true, json: false } });541 expect(doc.instance().isDirty()).toBe(true);542 doc.setState({ editingMode: 'json' });543 expect(doc.instance().isDirty()).toBe(false);544 });545});546describe('#getValidationErrors()', () => {547 it('should return validation errors based on the current editing mode', () => {548 const doc = shallow(<Doc {...props} />);549 doc.setState({ validationErrors: { form: false, json: 'invalid json' } });550 expect(doc.instance().getValidationErrors()).toBe(false);551 doc.setState({ editingMode: 'json' });552 expect(doc.instance().getValidationErrors()).toBe('invalid json');553 });554});555describe('#getFormDataForCurrentMode()', () => {556 it('should pull back the appropriate form data for the current editing mode', () => {557 const doc = shallow(<Doc {...props} />);558 doc.setState({559 formData: {560 headers: {561 'x-breed': 'pug',562 },563 body: {564 name: 'booster',565 },566 },567 formDataJson: {568 name: 'buster',569 },570 });571 expect(doc.instance().getFormDataForCurrentMode()).toStrictEqual({572 headers: { 'x-breed': 'pug' },573 body: { name: 'booster' },574 });575 doc.setState({ editingMode: 'json' });576 expect(doc.instance().getFormDataForCurrentMode()).toStrictEqual({577 headers: { 'x-breed': 'pug' },578 body: { name: 'buster' },579 });580 });...

Full Screen

Full Screen

stock_entry.js

Source:stock_entry.js Github

copy

Full Screen

1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3cur_frm.cscript.tname = "Stock Entry Detail";4cur_frm.cscript.fname = "mtn_details";5frappe.require("assets/erpnext/js/controllers/stock_controller.js");6frappe.provide("erpnext.stock");7erpnext.stock.StockEntry = erpnext.stock.StockController.extend({8 setup: function() {9 var me = this;10 this.frm.fields_dict.delivery_note_no.get_query = function() {11 return { query: "erpnext.stock.doctype.stock_entry.stock_entry.query_sales_return_doc" };12 };13 this.frm.fields_dict.sales_invoice_no.get_query =14 this.frm.fields_dict.delivery_note_no.get_query;15 this.frm.fields_dict.purchase_receipt_no.get_query = function() {16 return {17 filters:{ 'docstatus': 1 }18 };19 };20 this.frm.fields_dict.mtn_details.grid.get_field('item_code').get_query = function() {21 if(in_list(["Sales Return", "Purchase Return"], me.frm.doc.purpose) &&22 me.get_doctype_docname()) {23 return {24 query: "erpnext.stock.doctype.stock_entry.stock_entry.query_return_item",25 filters: {26 purpose: me.frm.doc.purpose,27 delivery_note_no: me.frm.doc.delivery_note_no,28 sales_invoice_no: me.frm.doc.sales_invoice_no,29 purchase_receipt_no: me.frm.doc.purchase_receipt_no30 }31 };32 } else {33 return erpnext.queries.item({is_stock_item: "Yes"});34 }35 };36 if(cint(frappe.defaults.get_default("auto_accounting_for_stock"))) {37 this.frm.add_fetch("company", "stock_adjustment_account", "expense_account");38 this.frm.fields_dict.mtn_details.grid.get_field('expense_account').get_query =39 function() {40 return {41 filters: {42 "company": me.frm.doc.company,43 "group_or_ledger": "Ledger"44 }45 }46 }47 }48 },49 onload_post_render: function() {50 cur_frm.get_field(this.fname).grid.set_multiple_add("item_code", "qty");51 this.set_default_account();52 },53 refresh: function() {54 var me = this;55 erpnext.toggle_naming_series();56 this.toggle_related_fields(this.frm.doc);57 this.toggle_enable_bom();58 this.show_stock_ledger();59 this.show_general_ledger();60 if(this.frm.doc.docstatus === 1 &&61 frappe.boot.user.can_create.indexOf("Journal Voucher")!==-1) {62 if(this.frm.doc.purpose === "Sales Return") {63 this.frm.add_custom_button(__("Make Credit Note"),64 function() { me.make_return_jv(); }, frappe.boot.doctype_icons["Journal Voucher"]);65 this.add_excise_button();66 } else if(this.frm.doc.purpose === "Purchase Return") {67 this.frm.add_custom_button(__("Make Debit Note"),68 function() { me.make_return_jv(); }, frappe.boot.doctype_icons["Journal Voucher"]);69 this.add_excise_button();70 }71 if(this.frm.doc.purpose=='Manufacture' || this.frm.doc.purpose=='Repack'){72 this.frm.add_custom_button(__("Perform Quality Control"), function() {73 me.make_quality_checking();74 });75 }76 }77 },78 on_submit: function() {79 this.clean_up();80 location.reload();81 },82 after_cancel: function() {83 this.clean_up();84 },85 set_default_account: function() {86 var me = this;87 if(cint(frappe.defaults.get_default("auto_accounting_for_stock")) && this.frm.doc.company) {88 var account_for = "stock_adjustment_account";89 if (this.frm.doc.purpose == "Purchase Return")90 account_for = "stock_received_but_not_billed";91 return this.frm.call({92 method: "erpnext.accounts.utils.get_company_default",93 args: {94 "fieldname": account_for,95 "company": this.frm.doc.company96 },97 callback: function(r) {98 if (!r.exc) {99 $.each(me.frm.doc.mtn_details || [], function(i, d) {100 if(!d.expense_account) d.expense_account = r.message;101 });102 }103 }104 });105 }106 },107 clean_up: function() {108 // Clear Production Order record from locals, because it is updated via Stock Entry109 if(this.frm.doc.production_order &&110 this.frm.doc.purpose == "Manufacture") {111 frappe.model.remove_from_locals("Production Order",112 this.frm.doc.production_order);113 }114 },115 get_items: function() {116 if(this.frm.doc.production_order || this.frm.doc.bom_no) {117 // if production order / bom is mentioned, get items118 return this.frm.call({119 doc: this.frm.doc,120 method: "get_items",121 callback: function(r) {122 if(!r.exc) refresh_field("mtn_details");123 }124 });125 }126 },127 qty: function(doc, cdt, cdn) {128 var d = locals[cdt][cdn];129 d.transfer_qty = flt(d.qty) * flt(d.conversion_factor);130 refresh_field('mtn_details');131 },132 production_order: function() {133 var me = this;134 this.toggle_enable_bom();135 return this.frm.call({136 method: "get_production_order_details",137 args: {production_order: this.frm.doc.production_order},138 callback: function(r) {139 if (!r.exc) {140 if (me.frm.doc.purpose == "Material Transfer" && !me.frm.doc.to_warehouse)141 me.frm.set_value("to_warehouse", r.message["wip_warehouse"]);142 }143 }144 });145 },146 toggle_enable_bom: function() {147 this.frm.toggle_enable("bom_no", this.frm.doc.purpose!="Manufacture");148 },149 get_doctype_docname: function() {150 if(this.frm.doc.purpose === "Sales Return") {151 if(this.frm.doc.delivery_note_no && this.frm.doc.sales_invoice_no) {152 // both specified153 msgprint(__("You can not enter both Delivery Note No and Sales Invoice No. Please enter any one."));154 } else if(!(this.frm.doc.delivery_note_no || this.frm.doc.sales_invoice_no)) {155 // none specified156 msgprint(__("Please enter Delivery Note No or Sales Invoice No to proceed"));157 } else if(this.frm.doc.delivery_note_no) {158 return {doctype: "Delivery Note", docname: this.frm.doc.delivery_note_no};159 } else if(this.frm.doc.sales_invoice_no) {160 return {doctype: "Sales Invoice", docname: this.frm.doc.sales_invoice_no};161 }162 } else if(this.frm.doc.purpose === "Purchase Return") {163 if(this.frm.doc.purchase_receipt_no) {164 return {doctype: "Purchase Receipt", docname: this.frm.doc.purchase_receipt_no};165 } else {166 // not specified167 msgprint(__("Please enter Purchase Receipt No to proceed"));168 }169 }170 },171 add_excise_button: function() {172 if(frappe.boot.sysdefaults.country === "India")173 this.frm.add_custom_button(__("Make Excise Invoice"), function() {174 var excise = frappe.model.make_new_doc_and_get_name('Journal Voucher');175 excise = locals['Journal Voucher'][excise];176 excise.voucher_type = 'Excise Voucher';177 loaddoc('Journal Voucher', excise.name);178 }, frappe.boot.doctype_icons["Journal Voucher"], "btn-default");179 },180 make_return_jv: function() {181 if(this.get_doctype_docname()) {182 return this.frm.call({183 method: "make_return_jv",184 args: {185 stock_entry: this.frm.doc.name186 },187 callback: function(r) {188 if(!r.exc) {189 var doclist = frappe.model.sync(r.message);190 frappe.set_route("Form", doclist[0].doctype, doclist[0].name);191 }192 }193 });194 }195 },196 mtn_details_add: function(doc, cdt, cdn) {197 var row = frappe.get_doc(cdt, cdn);198 this.frm.script_manager.copy_from_first_row("mtn_details", row,199 ["expense_account", "cost_center"]);200 if(!row.s_warehouse) row.s_warehouse = this.frm.doc.from_warehouse;201 if(!row.t_warehouse) row.t_warehouse = this.frm.doc.to_warehouse;202 },203 source_mandatory: ["Material Issue", "Material Transfer", "Purchase Return"],204 target_mandatory: ["Material Receipt", "Material Transfer", "Sales Return"],205 from_warehouse: function(doc) {206 var me = this;207 this.set_warehouse_if_missing("s_warehouse", doc.from_warehouse, function(row) {208 return me.source_mandatory.indexOf(me.frm.doc.purpose)!==-1;209 });210 },211 to_warehouse: function(doc) {212 var me = this;213 this.set_warehouse_if_missing("t_warehouse", doc.to_warehouse, function(row) {214 return me.target_mandatory.indexOf(me.frm.doc.purpose)!==-1;215 });216 },217 set_warehouse_if_missing: function(fieldname, value, condition) {218 for (var i=0, l=(this.frm.doc.mtn_details || []).length; i<l; i++) {219 var row = this.frm.doc.mtn_details[i];220 if (!row[fieldname]) {221 if (condition && !condition(row)) {222 continue;223 }224 frappe.model.set_value(row.doctype, row.name, fieldname, value, "Link");225 }226 }227 },228 mtn_details_on_form_rendered: function(doc, grid_row) {229 erpnext.setup_serial_no(grid_row)230 },231 customer: function() {232 this.get_party_details({233 party: this.frm.doc.customer,234 party_type:"Customer",235 doctype: this.frm.doc.doctype236 });237 },238 supplier: function() {239 this.get_party_details({240 party: this.frm.doc.supplier,241 party_type:"Supplier",242 doctype: this.frm.doc.doctype243 });244 },245 get_party_details: function(args) {246 var me = this;247 frappe.call({248 method: "erpnext.accounts.party.get_party_details",249 args: args,250 callback: function(r) {251 if(r.message) {252 me.frm.set_value({253 "customer_name": r.message["customer_name"],254 "customer_address": r.message["address_display"]255 });256 }257 }258 });259 },260 delivery_note_no: function() {261 this.get_party_details_from_against_voucher({262 ref_dt: "Delivery Note",263 ref_dn: this.frm.doc.delivery_note_no264 })265 },266 sales_invoice_no: function() {267 this.get_party_details_from_against_voucher({268 ref_dt: "Sales Invoice",269 ref_dn: this.frm.doc.sales_invoice_no270 })271 },272 purchase_receipt_no: function() {273 this.get_party_details_from_against_voucher({274 ref_dt: "Purchase Receipt",275 ref_dn: this.frm.doc.purchase_receipt_no276 })277 },278 get_party_details_from_against_voucher: function(args) {279 return this.frm.call({280 method: "erpnext.stock.doctype.stock_entry.stock_entry.get_party_details",281 args: args,282 })283 },284 make_quality_checking:function(){285 return this.frm.call({286 method: "erpnext.stock.custom_methods.make_quality_checking",287 args: {mtn_details:this.frm.doc.mtn_details},288 })289 }290});291cur_frm.script_manager.make(erpnext.stock.StockEntry);292cur_frm.cscript.toggle_related_fields = function(doc) {293 disable_from_warehouse = inList(["Material Receipt", "Sales Return"], doc.purpose);294 disable_to_warehouse = inList(["Material Issue", "Purchase Return"], doc.purpose);295 cur_frm.toggle_enable("from_warehouse", !disable_from_warehouse);296 cur_frm.toggle_enable("to_warehouse", !disable_to_warehouse);297 cur_frm.fields_dict["mtn_details"].grid.set_column_disp("s_warehouse", !disable_from_warehouse);298 cur_frm.fields_dict["mtn_details"].grid.set_column_disp("t_warehouse", !disable_to_warehouse);299 cur_frm.cscript.toggle_enable_bom();300 if(doc.purpose == 'Purchase Return') {301 doc.customer = doc.customer_name = doc.customer_address =302 doc.delivery_note_no = doc.sales_invoice_no = null;303 doc.bom_no = doc.production_order = doc.fg_completed_qty = null;304 } else if(doc.purpose == 'Sales Return') {305 doc.supplier=doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no=null;306 doc.bom_no = doc.production_order = doc.fg_completed_qty = null;307 } else {308 doc.customer = doc.customer_name = doc.customer_address =309 doc.delivery_note_no = doc.sales_invoice_no = doc.supplier =310 doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no = null;311 }312}313cur_frm.fields_dict['production_order'].get_query = function(doc) {314 return {315 filters: [316 ['Production Order', 'docstatus', '=', 1],317 ['Production Order', 'qty', '>','`tabProduction Order`.produced_qty']318 ]319 }320}321cur_frm.cscript.purpose = function(doc, cdt, cdn) {322 cur_frm.cscript.toggle_related_fields(doc);323}324// Overloaded query for link batch_no325cur_frm.fields_dict['mtn_details'].grid.get_field('batch_no').get_query = function(doc, cdt, cdn) {326 var d = locals[cdt][cdn];327 if(d.item_code) {328 return{329 query: "erpnext.stock.doctype.stock_entry.stock_entry.get_batch_no",330 filters:{331 'item_code': d.item_code,332 's_warehouse': d.s_warehouse,333 'posting_date': doc.posting_date334 }335 }336 } else {337 msgprint(__("Please enter Item Code to get batch no"));338 }339}340cur_frm.cscript.item_code = function(doc, cdt, cdn) {341 var d = locals[cdt][cdn];342 if(d.item_code) {343 args = {344 'item_code' : d.item_code,345 'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),346 'transfer_qty' : d.transfer_qty,347 'serial_no' : d.serial_no,348 'bom_no' : d.bom_no,349 'expense_account' : d.expense_account,350 'cost_center' : d.cost_center,351 'company' : cur_frm.doc.company352 };353 return get_server_fields('get_item_details', JSON.stringify(args),354 'mtn_details', doc, cdt, cdn, 1);355 }356}357cur_frm.cscript.s_warehouse = function(doc, cdt, cdn) {358 var d = locals[cdt][cdn];359 if(!d.bom_no) {360 args = {361 'item_code' : d.item_code,362 'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),363 'transfer_qty' : d.transfer_qty,364 'serial_no' : d.serial_no,365 'qty' : d.s_warehouse ? -1* d.qty : d.qty366 }367 return get_server_fields('get_warehouse_details', JSON.stringify(args),368 'mtn_details', doc, cdt, cdn, 1);369 }370}371cur_frm.cscript.t_warehouse = cur_frm.cscript.s_warehouse;372cur_frm.cscript.uom = function(doc, cdt, cdn) {373 var d = locals[cdt][cdn];374 if(d.uom && d.item_code){375 var arg = {'item_code':d.item_code, 'uom':d.uom, 'qty':d.qty}376 return get_server_fields('get_uom_details', JSON.stringify(arg),377 'mtn_details', doc, cdt, cdn, 1);378 }379}380cur_frm.cscript.validate = function(doc, cdt, cdn) {381 cur_frm.cscript.validate_items(doc);382 if($.inArray(cur_frm.doc.purpose, ["Purchase Return", "Sales Return"])!==-1)383 validated = cur_frm.cscript.get_doctype_docname() ? true : false;384}385cur_frm.cscript.validate_items = function(doc) {386 cl = doc.mtn_details || [];387 if (!cl.length) {388 msgprint(__("Item table can not be blank"));389 validated = false;390 }391}392cur_frm.cscript.expense_account = function(doc, cdt, cdn) {393 cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "expense_account");394}395cur_frm.cscript.cost_center = function(doc, cdt, cdn) {396 cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "cost_center");397}398cur_frm.fields_dict.customer.get_query = function(doc, cdt, cdn) {399 return { query: "erpnext.controllers.queries.customer_query" }400}401cur_frm.fields_dict.supplier.get_query = function(doc, cdt, cdn) {402 return { query: "erpnext.controllers.queries.supplier_query" }403}404cur_frm.add_fetch('production_order', 'total_fixed_cost', 'total_fixed_cost');405cur_frm.add_fetch('bom_no', 'total_fixed_cost', 'total_fixed_cost');406cur_frm.cscript.source_batch = function(doc, cdt, cdn) {407 var d=locals[cdt][cdn]408 get_server_fields("get_serial_nos",d.item_code,'',doc,cdt,cdn,1,function(){409 refresh_field('mtn_details')410 })411}412cur_frm.fields_dict.mtn_details.grid.get_field("source_batch").get_query = function(doc,cdt,cdn) {413 var d = locals[cdt][cdn]414 if(d.s_warehouse)415 {416 return {417 filters: {418 'warehouse': d.s_warehouse 419 }420 }421 }422 423}424cur_frm.cscript.add = function(doc,cdt,cdn) { //live rohit_sw425 var d = locals[cdt][cdn] 426 get_server_fields("get_source_batch",d.item_code,'',doc,cdt,cdn,1,function(){427 refresh_field('mtn_details')428 })429}430cur_frm.fields_dict.mtn_details.grid.get_field("serial_no_link").get_query = function(doc,cdt,cdn) {431 var d = locals[cdt][cdn]432 filter={'purpose':doc.purpose || '','s_warehouse':d.s_warehouse || '','t_warehouse':d.t_warehouse || '','item_code':d.item_code || '','qty_per_drum_bag':d.qty_per_drum_bag || ''}433 return {434 query: "erpnext.stock.custom_methods.get_serial_no",435 filters:{436 'doc':filter437 }438 }439}440cur_frm.fields_dict.mtn_details.grid.get_field("target_batch").get_query = function(doc,cdt,cdn) {441 var d = locals[cdt][cdn]442 if(d.t_warehouse && doc.purpose=='Manufacture/Repack')443 {444 return {445 filters: {446 'warehouse': d.t_warehouse,447 'used':'No'448 }449 }450 }...

Full Screen

Full Screen

journal_voucher.js

Source:journal_voucher.js Github

copy

Full Screen

1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3frappe.provide("erpnext.accounts");4erpnext.accounts.JournalVoucher = frappe.ui.form.Controller.extend({5 onload: function() {6 this.load_defaults();7 this.setup_queries();8 this.setup_balance_formatter();9 },10 onload_post_render: function() {11 cur_frm.get_field("entries").grid.set_multiple_add("account");12 },13 load_defaults: function() {14 if(this.frm.doc.__islocal && this.frm.doc.company) {15 frappe.model.set_default_values(this.frm.doc);16 $.each(this.frm.doc.entries || [], function(i, jvd) {17 frappe.model.set_default_values(jvd);18 }19 );20 if(!this.frm.doc.amended_from) this.frm.doc.posting_date = get_today();21 }22 },23 setup_queries: function() {24 var me = this;25 $.each(["account", "cost_center"], function(i, fieldname) {26 me.frm.set_query(fieldname, "entries", function() {27 frappe.model.validate_missing(me.frm.doc, "company");28 return {29 filters: {30 company: me.frm.doc.company,31 group_or_ledger: "Ledger"32 }33 };34 });35 });36 $.each([["against_voucher", "Purchase Invoice", "credit_to"],37 ["against_invoice", "Sales Invoice", "debit_to"]], function(i, opts) {38 me.frm.set_query(opts[0], "entries", function(doc, cdt, cdn) {39 var jvd = frappe.get_doc(cdt, cdn);40 frappe.model.validate_missing(jvd, "account");41 return {42 filters: [43 [opts[1], opts[2], "=", jvd.account],44 [opts[1], "docstatus", "=", 1],45 [opts[1], "outstanding_amount", ">", 0]46 ]47 };48 });49 });50 this.frm.set_query("against_jv", "entries", function(doc, cdt, cdn) {51 var jvd = frappe.get_doc(cdt, cdn);52 frappe.model.validate_missing(jvd, "account");53 return {54 query: "erpnext.accounts.doctype.journal_voucher.journal_voucher.get_against_jv",55 filters: { account: jvd.account }56 };57 });58 },59 setup_balance_formatter: function() {60 var df = frappe.meta.get_docfield("Journal Voucher Detail", "balance", this.frm.doc.name);61 df.formatter = function(value, df, options, doc) {62 var currency = frappe.meta.get_field_currency(df, doc);63 var dr_or_cr = value ? ('<label>' + (value > 0.0 ? __("Dr") : __("Cr")) + '</label>') : "";64 return "<div style='text-align: right'>"65 + ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))66 + " " + dr_or_cr67 + "</div>";68 }69 },70 against_voucher: function(doc, cdt, cdn) {71 var d = frappe.get_doc(cdt, cdn);72 if (d.against_voucher && !flt(d.debit)) {73 this.get_outstanding({74 'doctype': 'Purchase Invoice',75 'docname': d.against_voucher76 }, d)77 }78 },79 against_invoice: function(doc, cdt, cdn) {80 var d = frappe.get_doc(cdt, cdn);81 if (d.against_invoice && !flt(d.credit)) {82 this.get_outstanding({83 'doctype': 'Sales Invoice',84 'docname': d.against_invoice85 }, d)86 }87 },88 against_jv: function(doc, cdt, cdn) {89 var d = frappe.get_doc(cdt, cdn);90 if (d.against_jv && !flt(d.credit) && !flt(d.debit)) {91 this.get_outstanding({92 'doctype': 'Journal Voucher',93 'docname': d.against_jv,94 'account': d.account95 }, d)96 }97 },98 get_outstanding: function(args, child) {99 var me = this;100 return this.frm.call({101 child: child,102 method: "get_outstanding",103 args: { args: args},104 callback: function(r) {105 cur_frm.cscript.update_totals(me.frm.doc);106 }107 });108 }109});110cur_frm.script_manager.make(erpnext.accounts.JournalVoucher);111cur_frm.cscript.refresh = function(doc) {112 cur_frm.cscript.is_opening(doc)113 erpnext.toggle_naming_series();114 cur_frm.cscript.voucher_type(doc);115 if(doc.docstatus==1) {116 cur_frm.appframe.add_button(__('View Ledger'), function() {117 frappe.route_options = {118 "voucher_no": doc.name,119 "from_date": doc.posting_date,120 "to_date": doc.posting_date,121 "company": doc.company,122 group_by_voucher: 0123 };124 frappe.set_route("query-report", "General Ledger");125 }, "icon-table");126 }127}128cur_frm.cscript.company = function(doc, cdt, cdn) {129 cur_frm.refresh_fields();130}131cur_frm.cscript.is_opening = function(doc, cdt, cdn) {132 hide_field('aging_date');133 if (doc.is_opening == 'Yes') unhide_field('aging_date');134}135cur_frm.cscript.update_totals = function(doc) {136 var td=0.0; var tc =0.0;137 var el = doc.entries || [];138 for(var i in el) {139 td += flt(el[i].debit, precision("debit", el[i]));140 tc += flt(el[i].credit, precision("credit", el[i]));141 }142 var doc = locals[doc.doctype][doc.name];143 doc.total_debit = td;144 doc.total_credit = tc;145 doc.difference = flt((td - tc), precision("difference"));146 refresh_many(['total_debit','total_credit','difference']);147}148cur_frm.cscript.debit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }149cur_frm.cscript.credit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }150cur_frm.cscript.get_balance = function(doc,dt,dn) {151 cur_frm.cscript.update_totals(doc);152 return $c_obj(cur_frm.doc, 'get_balance', '', function(r, rt){153 cur_frm.refresh();154 });155}156// Get balance157// -----------158cur_frm.cscript.account = function(doc,dt,dn) {159 var d = locals[dt][dn];160 if(d.account) {161 return frappe.call({162 method: "erpnext.accounts.utils.get_balance_on",163 args: {account: d.account, date: doc.posting_date},164 callback: function(r) {165 d.balance = r.message;166 refresh_field('balance', d.name, 'entries');167 }168 });169 }170}171cur_frm.cscript.validate = function(doc,cdt,cdn) {172 cur_frm.cscript.update_totals(doc);173}174cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){175 if(doc.select_print_heading){176 // print heading177 cur_frm.pformat.print_heading = doc.select_print_heading;178 }179 else180 cur_frm.pformat.print_heading = __("Journal Voucher");181}182cur_frm.cscript.voucher_type = function(doc, cdt, cdn) {183 cur_frm.set_df_property("cheque_no", "reqd", doc.voucher_type=="Bank Voucher");184 cur_frm.set_df_property("cheque_date", "reqd", doc.voucher_type=="Bank Voucher");185 if((doc.entries || []).length!==0 || !doc.company) // too early186 return;187 var update_jv_details = function(doc, r) {188 var jvdetail = frappe.model.add_child(doc, "Journal Voucher Detail", "entries");189 $.each(r, function(i, d) {190 var row = frappe.model.add_child(doc, "Journal Voucher Detail", "entries");191 row.account = d.account;192 row.balance = d.balance;193 });194 refresh_field("entries");195 }196 if(in_list(["Bank Voucher", "Cash Voucher"], doc.voucher_type)) {197 return frappe.call({198 type: "GET",199 method: "erpnext.accounts.doctype.journal_voucher.journal_voucher.get_default_bank_cash_account",200 args: {201 "voucher_type": doc.voucher_type,202 "company": doc.company203 },204 callback: function(r) {205 if(r.message) {206 update_jv_details(doc, [r.message]);207 }208 }209 })210 } else if(doc.voucher_type=="Opening Entry") {211 return frappe.call({212 type:"GET",213 method: "erpnext.accounts.doctype.journal_voucher.journal_voucher.get_opening_accounts",214 args: {215 "company": doc.company216 },217 callback: function(r) {218 frappe.model.clear_table(doc, "entries");219 if(r.message) {220 update_jv_details(doc, r.message);221 }222 cur_frm.set_value("is_opening", "Yes")223 }224 })225 }...

Full Screen

Full Screen

bom.js

Source:bom.js Github

copy

Full Screen

1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3// On REFRESH4frappe.provide("erpnext.bom");5cur_frm.cscript.refresh = function(doc,dt,dn){6 cur_frm.toggle_enable("item", doc.__islocal);7 if (!doc.__islocal && doc.docstatus<2) {8 cur_frm.add_custom_button(__("Update Cost"), cur_frm.cscript.update_cost,9 "icon-money", "btn-default");10 }11 cur_frm.cscript.with_operations(doc);12 erpnext.bom.set_operation_no(doc);13}14cur_frm.cscript.update_cost = function() {15 return frappe.call({16 doc: cur_frm.doc,17 method: "update_cost",18 callback: function(r) {19 if(!r.exc) cur_frm.refresh_fields();20 }21 })22}23cur_frm.cscript.with_operations = function(doc) {24 cur_frm.fields_dict["bom_materials"].grid.set_column_disp("operation_no", doc.with_operations);25 cur_frm.fields_dict["bom_materials"].grid.toggle_reqd("operation_no", doc.with_operations);26}27cur_frm.cscript.operation_no = function(doc, cdt, cdn) {28 var child = locals[cdt][cdn];29 if(child.parentfield=="bom_operations") erpnext.bom.set_operation_no(doc);30}31erpnext.bom.set_operation_no = function(doc) {32 var op_table = doc.bom_operations || [];33 var operations = [];34 for (var i=0, j=op_table.length; i<j; i++) {35 var op = op_table[i].operation_no;36 if (op && !inList(operations, op)) operations.push(op);37 }38 frappe.meta.get_docfield("BOM Item", "operation_no",39 cur_frm.docname).options = operations.join("\n");40 $.each(doc.bom_materials || [], function(i, v) {41 if(!inList(operations, cstr(v.operation_no))) v.operation_no = null;42 });43 refresh_field("bom_materials");44}45cur_frm.cscript.bom_operations_remove = function(){46 erpnext.bom.set_operation_no(doc);47}48cur_frm.add_fetch("item", "description", "description");49cur_frm.add_fetch("item", "stock_uom", "uom");50cur_frm.cscript.workstation = function(doc,dt,dn) {51 var d = locals[dt][dn];52 frappe.model.with_doc("Workstation", d.workstation, function(name, r) {53 d.hour_rate = r.docs[0].hour_rate;54 refresh_field("hour_rate", dn, "bom_operations");55 erpnext.bom.calculate_op_cost(doc);56 erpnext.bom.calculate_total(doc);57 });58}59cur_frm.cscript.hour_rate = function(doc, dt, dn) {60 erpnext.bom.calculate_op_cost(doc);61 erpnext.bom.calculate_total(doc);62}63cur_frm.cscript.time_in_mins = cur_frm.cscript.hour_rate;64cur_frm.cscript.fixed_cycle_cost = cur_frm.cscript.hour_rate;65cur_frm.cscript.item_code = function(doc, cdt, cdn) {66 get_bom_material_detail(doc, cdt, cdn);67}68cur_frm.cscript.bom_no = function(doc, cdt, cdn) {69 get_bom_material_detail(doc, cdt, cdn);70}71cur_frm.cscript.is_default = function(doc) {72 if (doc.is_default) cur_frm.set_value("is_active", 1);73}74var get_bom_material_detail= function(doc, cdt, cdn) {75 var d = locals[cdt][cdn];76 if (d.item_code) {77 return frappe.call({78 doc: cur_frm.doc,79 method: "get_bom_material_detail",80 args: {81 'item_code': d.item_code,82 'bom_no': d.bom_no != null ? d.bom_no: '',83 'qty': d.qty84 },85 callback: function(r) {86 d = locals[cdt][cdn];87 $.extend(d, r.message);88 refresh_field("bom_materials");89 doc = locals[doc.doctype][doc.name];90 erpnext.bom.calculate_rm_cost(doc);91 erpnext.bom.calculate_total(doc);92 },93 freeze: true94 });95 }96}97cur_frm.cscript.qty = function(doc, cdt, cdn) {98 erpnext.bom.calculate_rm_cost(doc);99 erpnext.bom.calculate_total(doc);100}101cur_frm.cscript.rate = function(doc, cdt, cdn) {102 var d = locals[cdt][cdn];103 if (d.bom_no) {104 msgprint(__("You can not change rate if BOM mentioned agianst any item"));105 get_bom_material_detail(doc, cdt, cdn);106 } else {107 erpnext.bom.calculate_rm_cost(doc);108 erpnext.bom.calculate_total(doc);109 }110}111erpnext.bom.calculate_op_cost = function(doc) {112 var op = doc.bom_operations || [];113 total_op_cost = 0;114 for(var i=0;i<op.length;i++) {115 op_cost = flt(flt(op[i].hour_rate) * flt(op[i].time_in_mins) / 60, 2);116 set_multiple('BOM Operation',op[i].name, {'operating_cost': op_cost}, 'bom_operations');117 total_op_cost += op_cost;118 }119 doc.operating_cost = total_op_cost;120 refresh_field('operating_cost');121}122erpnext.bom.calculate_rm_cost = function(doc) {123 var rm = doc.bom_materials || [];124 total_rm_cost = 0;125 for(var i=0;i<rm.length;i++) {126 amt = flt(rm[i].rate) * flt(rm[i].qty);127 set_multiple('BOM Item',rm[i].name, {'amount': amt}, 'bom_materials');128 set_multiple('BOM Item',rm[i].name,129 {'qty_consumed_per_unit': flt(rm[i].qty)/flt(doc.quantity)}, 'bom_materials');130 total_rm_cost += amt;131 }132 doc.raw_material_cost = total_rm_cost;133 refresh_field('raw_material_cost');134}135// Calculate Total Cost136erpnext.bom.calculate_total = function(doc) {137 doc.total_cost = flt(doc.raw_material_cost) + flt(doc.operating_cost);138 refresh_field('total_cost');139}140cur_frm.fields_dict['item'].get_query = function(doc) {141 return{142 query: "erpnext.controllers.queries.item_query",143 filters:{144 'is_manufactured_item': 'Yes'145 }146 }147}148cur_frm.fields_dict['project_name'].get_query = function(doc, dt, dn) {149 return{150 filters:[151 ['Project', 'status', 'not in', 'Completed, Cancelled']152 ]153 }154}155cur_frm.fields_dict['bom_materials'].grid.get_field('item_code').get_query = function(doc) {156 return{157 query: "erpnext.controllers.queries.item_query"158 }159}160cur_frm.fields_dict['bom_materials'].grid.get_field('bom_no').get_query = function(doc, cdt, cdn) {161 var d = locals[cdt][cdn];162 return{163 filters:{164 'item': d.item_code,165 'is_active': 1,166 'docstatus': 1167 }168 }169}170cur_frm.cscript.validate = function(doc, dt, dn) {171 erpnext.bom.calculate_op_cost(doc);172 erpnext.bom.calculate_rm_cost(doc);173 erpnext.bom.calculate_total(doc);...

Full Screen

Full Screen

salary_slip.js

Source:salary_slip.js Github

copy

Full Screen

1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3cur_frm.add_fetch('employee', 'company', 'company');4// On load5// -------------------------------------------------------------------6cur_frm.cscript.onload = function(doc,dt,dn){7 if((cint(doc.__islocal) == 1) && !doc.amended_from){8 if(!doc.month) {9 var today=new Date();10 month = (today.getMonth()+01).toString();11 if(month.length>1) doc.month = month;12 else doc.month = '0'+month;13 }14 if(!doc.fiscal_year) doc.fiscal_year = sys_defaults['fiscal_year'];15 refresh_many(['month', 'fiscal_year']);16 }17}18// Get leave details19//---------------------------------------------------------------------20cur_frm.cscript.fiscal_year = function(doc,dt,dn){21 return $c_obj(doc, 'get_emp_and_leave_details','',function(r, rt) {22 var doc = locals[dt][dn];23 cur_frm.refresh();24 calculate_all(doc, dt, dn);25 });26}27cur_frm.cscript.month = cur_frm.cscript.employee = cur_frm.cscript.fiscal_year;28cur_frm.cscript.leave_without_pay = function(doc,dt,dn){29 if (doc.employee && doc.fiscal_year && doc.month) {30 return $c_obj(doc, 'get_leave_details',doc.leave_without_pay,function(r, rt) {31 var doc = locals[dt][dn];32 cur_frm.refresh();33 calculate_all(doc, dt, dn);34 });35 }36}37var calculate_all = function(doc, dt, dn) {38 calculate_earning_total(doc, dt, dn);39 calculate_ded_total(doc, dt, dn);40 calculate_net_pay(doc, dt, dn);41}42cur_frm.cscript.e_modified_amount = function(doc,dt,dn){43 calculate_earning_total(doc, dt, dn);44 calculate_net_pay(doc, dt, dn);45}46cur_frm.cscript.e_depends_on_lwp = cur_frm.cscript.e_modified_amount;47// Trigger on earning modified amount and depends on lwp48// ------------------------------------------------------------------------49cur_frm.cscript.d_modified_amount = function(doc,dt,dn){50 calculate_ded_total(doc, dt, dn);51 calculate_net_pay(doc, dt, dn);52}53cur_frm.cscript.d_depends_on_lwp = cur_frm.cscript.d_modified_amount;54// Calculate earning total55// ------------------------------------------------------------------------56var calculate_earning_total = function(doc, dt, dn) {57 var tbl = doc.earning_details || [];58 var total_earn = 0;59 for(var i = 0; i < tbl.length; i++){60 if(cint(tbl[i].e_depends_on_lwp) == 1) {61 tbl[i].e_modified_amount = Math.round(tbl[i].e_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100; 62 refresh_field('e_modified_amount', tbl[i].name, 'earning_details');63 }64 total_earn += flt(tbl[i].e_modified_amount);65 }66 doc.gross_pay = total_earn + flt(doc.arrear_amount) + flt(doc.leave_encashment_amount);67 refresh_many(['e_modified_amount', 'gross_pay']);68}69// Calculate deduction total70// ------------------------------------------------------------------------71var calculate_ded_total = function(doc, dt, dn) {72 var tbl = doc.deduction_details || [];73 var total_ded = 0;74 for(var i = 0; i < tbl.length; i++){75 if(cint(tbl[i].d_depends_on_lwp) == 1) {76 tbl[i].d_modified_amount = Math.round(tbl[i].d_amount)*(flt(doc.payment_days)/cint(doc.total_days_in_month)*100)/100;77 refresh_field('d_modified_amount', tbl[i].name, 'deduction_details');78 }79 total_ded += flt(tbl[i].d_modified_amount);80 }81 doc.total_deduction = total_ded;82 refresh_field('total_deduction'); 83}84// Calculate net payable amount85// ------------------------------------------------------------------------86var calculate_net_pay = function(doc, dt, dn) {87 doc.net_pay = flt(doc.gross_pay) - flt(doc.total_deduction);88 doc.rounded_total = Math.round(doc.net_pay);89 refresh_many(['net_pay', 'rounded_total']);90}91// trigger on arrear92// ------------------------------------------------------------------------93cur_frm.cscript.arrear_amount = function(doc,dt,dn){94 calculate_earning_total(doc, dt, dn);95 calculate_net_pay(doc, dt, dn);96}97// trigger on encashed amount98// ------------------------------------------------------------------------99cur_frm.cscript.leave_encashment_amount = cur_frm.cscript.arrear_amount;100// validate101// ------------------------------------------------------------------------102cur_frm.cscript.validate = function(doc, dt, dn) {103 calculate_all(doc, dt, dn);104}105cur_frm.fields_dict.employee.get_query = function(doc,cdt,cdn) {106 return{107 query: "erpnext.controllers.queries.employee_query"108 } ...

Full Screen

Full Screen

leave_application.js

Source:leave_application.js Github

copy

Full Screen

1// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors2// License: GNU General Public License v3. See license.txt3cur_frm.add_fetch('employee','employee_name','employee_name');4cur_frm.cscript.onload = function(doc, dt, dn) {5 if(!doc.posting_date)6 set_multiple(dt,dn,{posting_date:get_today()});7 if(doc.__islocal) {8 cur_frm.set_value("status", "Open");9 cur_frm.cscript.calculate_total_days(doc, dt, dn);10 }11 cur_frm.set_query("leave_approver", function() {12 return {13 filters: [["UserRole", "role", "=", "Leave Approver"]]14 };15 });16 cur_frm.cscript.get_leave_balance(cur_frm.doc);17}18cur_frm.cscript.refresh = function(doc, dt, dn) {19 if(doc.__islocal) {20 cur_frm.set_value("status", "Open")21 }22 cur_frm.set_intro("");23 if(doc.__islocal && !in_list(user_roles, "HR User")) {24 cur_frm.set_intro(__("Fill the form and save it"))25 } else {26 if(doc.docstatus==0 && doc.status=="Open") {27 if(user==doc.leave_approver) {28 cur_frm.set_intro(__("You are the Leave Approver for this record. Please Update the 'Status' and Save"));29 cur_frm.toggle_enable("status", true);30 } else {31 cur_frm.set_intro(__("This Leave Application is pending approval. Only the Leave Approver can update status."))32 cur_frm.toggle_enable("status", false);33 if(!doc.__islocal) {34 cur_frm.frm_head.appframe.set_title_right("");35 }36 }37 } else {38 if(doc.status=="Approved") {39 cur_frm.set_intro(__("Leave application has been approved."));40 if(cur_frm.doc.docstatus==0) {41 cur_frm.set_intro(__("Please submit to update Leave Balance."));42 }43 } else if(doc.status=="Rejected") {44 cur_frm.set_intro(__("Leave application has been rejected."));45 }46 }47 }48}49cur_frm.cscript.employee = function (doc, dt, dn){50 cur_frm.cscript.get_leave_balance(doc, dt, dn);51}52cur_frm.cscript.fiscal_year = function (doc, dt, dn){53 cur_frm.cscript.get_leave_balance(doc, dt, dn);54}55cur_frm.cscript.leave_type = function (doc, dt, dn){56 cur_frm.cscript.get_leave_balance(doc, dt, dn);57}58cur_frm.cscript.half_day = function(doc, dt, dn) {59 if(doc.from_date) {60 set_multiple(dt,dn,{to_date:doc.from_date});61 cur_frm.cscript.calculate_total_days(doc, dt, dn);62 }63}64cur_frm.cscript.from_date = function(doc, dt, dn) {65 if(cint(doc.half_day) == 1){66 set_multiple(dt,dn,{to_date:doc.from_date});67 }68 cur_frm.cscript.calculate_total_days(doc, dt, dn);69}70cur_frm.cscript.to_date = function(doc, dt, dn) {71 if(cint(doc.half_day) == 1 && cstr(doc.from_date) && doc.from_date != doc.to_date){72 msgprint(__("To Date should be same as From Date for Half Day leave"));73 set_multiple(dt,dn,{to_date:doc.from_date});74 }75 cur_frm.cscript.calculate_total_days(doc, dt, dn);76}77cur_frm.cscript.get_leave_balance = function(doc, dt, dn) {78 if(doc.docstatus==0 && doc.employee && doc.leave_type && doc.fiscal_year) {79 return cur_frm.call({80 method: "get_leave_balance",81 args: {82 employee: doc.employee,83 fiscal_year: doc.fiscal_year,84 leave_type: doc.leave_type85 }86 });87 }88}89cur_frm.cscript.calculate_total_days = function(doc, dt, dn) {90 if(doc.from_date && doc.to_date){91 if(cint(doc.half_day) == 1) set_multiple(dt,dn,{total_leave_days:0.5});92 else{93 // server call is done to include holidays in leave days calculations94 return frappe.call({95 method: 'erpnext.hr.doctype.leave_application.leave_application.get_total_leave_days',96 args: {leave_app: doc},97 callback: function(response) {98 if (response && response.message) {99 cur_frm.set_value('total_leave_days', response.message.total_leave_days);100 }101 }102 });103 }104 }105}106cur_frm.fields_dict.employee.get_query = erpnext.queries.employee;107frappe.ui.form.on("Leave Application", "leave_approver", function(frm) {108 frappe.call({109 "method": "frappe.client.get",110 args: {111 doctype: "User",112 name: frm.doc.leave_approver113 },114 callback: function (data) {115 frappe.model.set_value(frm.doctype, frm.docname, "leave_approver_name",116 data.message.first_name117 + (data.message.last_name ? (" " + data.message.last_name) : ""))118 }119 })...

Full Screen

Full Screen

map.js

Source:map.js Github

copy

Full Screen

1function(doc) {2//chw_dashboard3//returns an array of key: chw_username: [count, last_pact_id, last_xmlns, received_on]4 function bw_array_sort(a, b) {5 //doing reverse date order6 var datea = parse_date(a['test_date']);7 var dateb = parse_date(b['test_date']);8 if (datea > dateb) {9 return -1;10 } else if (datea < dateb) {11 return 1;12 } else {13 return 0;14 }15 }16 function get_encounter_date(xform_doc) {17 function get_date_string(xform_doc) {18 // check some expected places for a date19 if (xform_doc.encounter_date) return xform_doc.encounter_date;20 if (xform_doc.note && xform_doc.note.encounter_date) return xform_doc.note.encounter_date;21 if (xform_doc.Meta && xform_doc.Meta.TimeEnd) return xform_doc.Meta.TimeEnd;22 if (xform_doc.Meta && xform_doc.Meta.TimeStart) return xform_doc.Meta.TimeStart;23 return null;24 }25 return parse_date(get_date_string(xform_doc));26 }27 function get_user_id(xform_doc) {28 if (xform_doc.Meta && xform_doc.Meta.username) return xform_doc.Meta.username;29 if (xform_doc.Meta && xform_doc.Meta.chw_id) return xform_doc.Meta.chw_id;30 }31 //Parse the encounter date string.32 //note, that the dates are in 1 indexed months, so NO additions here.33 function parse_date(date_string) {34 if (!date_string) return new Date(1970, 1, 1);35 // hat tip: http://stackoverflow.com/questions/2587345/javascript-date-parse36 var parts = date_string.match(/(\d+)/g);37 // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])38 return new Date(parts[0], parts[1] - 1, parts[2]); // months are 0-based39 }40 if (doc.doc_type == "XFormInstance" && doc.xmlns != "http://code.javarosa.org/devicereport") {41 //map 1: XForm Information regarding bloodwork and submission counts42 if (doc.form.encounter_date) {43 var edate = parse_date(doc.form.encounter_date);44 } else if (doc.form.note && doc.form.note.encounter_date) {45 var edate = parse_date(doc.form.note.encounter_date);46 }47 //return it in regular months, not zero indexed.48 if (doc.form.pact_id) {49 var pact_id = doc.form.pact_id;50 } else if (doc.form.note && doc.form.note.pact_id) {51 var pact_id = doc.form.note.pact_id;52 }53 var ret_dict = {};54 ret_dict['count'] = 1;55 ret_dict['encounter_date'] = get_encounter_date(doc.form);56 ret_dict['doc_id'] = doc._id;57 ret_dict['pact_id'] = pact_id;58 ret_dict['last_xmlns'] = doc.xmlns;59 ret_dict['last_received'] = doc.received_on;60 emit(get_user_id(doc.form), ret_dict);61 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2describe('Array', function() {3 describe('#indexOf()', function() {4 it('should return -1 when the value is not present', function() {5 assert.equal(-1, [1,2,3].indexOf(4));6 });7 });8});9 #indexOf()101 passing (7ms)11var assert = require('assert');12describe('Array', function() {13 describe('#indexOf()', function() {14 it('should return -1 when the value is not present', function() {15 assert.ok(-1, [1,2,3].indexOf(4));16 });17 });18});19 #indexOf()201 passing (7ms)21var assert = require('assert');22describe('Array', function() {23 describe('#indexOf()', function() {24 it('should return -1 when the value is not present', function() {25 assert.notEqual(-1, [1,2,3].indexOf(4));26 });27 });28});29 #indexOf()301 passing (7ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Array', function() {2 describe('#indexOf()', function() {3 it('should return -1 when the value is not present', function() {4 assert.equal(-1, [1,2,3].indexOf(4));5 });6 });7});8 #indexOf()9 1 passing (5ms)10 #indexOf()11 1 passing (5ms)12 #indexOf()13 1 passing (5ms)14 #indexOf()15 1 passing (5ms)16# indexOf()17{18 "stats": {19 },20 {21 "fullTitle": "Array #indexOf() should return -1 when the value is not present",

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const MarioChar = require('../models/mariochar');3describe('Saving records', function(){4 it('Saves a record to the database', function(done){5 var char = new MarioChar({6 });7 char.save().then(function(){8 assert(char.isNew === false);9 done();10 });11 });12});

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const MarioChar = require('../models/mariochar');3describe('Finding records', function(){4 var char;5 beforeEach(function(done){6 char = new MarioChar({7 });8 char.save().then(function(){9 assert(char.isNew === false);10 done();11 });12 });13 it('Finds one record from the database', function(done){14 MarioChar.findOne({name: 'Mario'}).then(function(result){15 assert(result.name === 'Mario');16 done();17 });18 });19 it('Finds one record by ID from the database', function(done){20 MarioChar.findOne({_id: char._id}).then(function(result){21 assert(result._id.toString() === char._id.toString());22 done();23 });24 });25});26const mongoose = require('mongoose');27const Schema = mongoose.Schema;28const MarioCharSchema = new Schema({29});30const MarioChar = mongoose.model('mariochar', MarioCharSchema);31module.exports = MarioChar;32{33 "scripts": {34 },35 "dependencies": {36 },37 "devDependencies": {38 }39}40const express = require('express');41const bodyParser = require('body-parser');42const mongoose = require('mongoose');43const app = express();44mongoose.Promise = global.Promise;45app.use(bodyParser.json());46app.use('/api', require('./routes/api'));47app.use(function(err, req, res, next){48 res.status(422).send({error: err.message});49});

Full Screen

Using AI Code Generation

copy

Full Screen

1var expect = require('chai').expect;2var add = require('../add.js');3describe('add', function() {4 it('returns the sum of two numbers', function() {5 var result = add(1, 2);6 expect(result).to.equal(3);7 });8});9var add = function (x, y) {10 return x + y;11};12module.exports = add;13 1 passing (7ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var request = require('supertest');3var app = require('../app.js');4describe('GET /', function() {5 it('returns the homepage', function(done) {6 request(app)7 .get('/')8 .expect('Content-Type', /html/)9 .expect(200, done);10 });11});12describe('GET /about', function() {13 it('returns the about page', function(done) {14 request(app)15 .get('/about')16 .expect('Content-Type', /html/)17 .expect(200, done);18 });19});20describe('GET /contact', function() {21 it('returns the contact page', function(done) {22 request(app)23 .get('/contact')24 .expect('Content-Type', /html/)25 .expect(200, done);26 });27});28describe('GET /random', function() {29 it('returns 404', function(done) {30 request(app)31 .get('/random')32 .expect(404, done);33 });34});35describe('POST /contact', function() {36 it('returns 200', function(done) {37 request(app)38 .post('/contact')39 .expect(200, done);40 });41});42describe('GET /api', function() {43 it('returns the api page', function(done) {44 request(app)45 .get('/api')46 .expect('Content-Type', /html/)47 .expect(200, done);48 });49});50describe('GET /api/1', function() {51 it('returns the api page with id 1', function(done) {52 request(app)53 .get('/api/1')54 .expect('Content-Type', /html/)55 .expect(200, done);56 });57});58describe('GET /api/2', function() {59 it('returns the api page with id 2', function(done) {60 request(app)61 .get('/api/2')62 .expect('Content-Type', /html/)63 .expect(200, done);64 });65});66describe('GET /api/3', function() {67 it('returns the api page with id 3', function(done) {68 request(app)69 .get('/api/3')70 .expect('Content-Type', /html/)71 .expect(200, done);72 });73});74describe('GET /api/4', function

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var expect = require('chai').expect;3var should = require('chai').should();4var request = require('request');5var fs = require('fs');6var path = require('path');7var cheerio = require('cheerio');8describe('index', function() {9 describe('GET /', function() {10 it('should return 200', function(done) {11 request(url, function(error, response, body) {12 expect(response.statusCode).to.equal(200);13 done();14 });15 });16 });17});18var assert = require('assert');19var expect = require('chai').expect;20var should = require('chai').should();21var request = require('request');22var fs = require('fs');23var path = require('path');24var cheerio = require('cheerio');25var functions = require('./functions');26var assert = require('assert');27var expect = require('chai').expect;28var should = require('chai').should();29var request = require('request');30var fs = require('fs');31var path = require('path');32var cheerio = require('cheerio');33var functions = function() {};34functions.prototype.getHTML = function(url, cb) {35 request(url, function(error, response, body) {36 if (error) {37 cb(error);38 } else {39 cb(null, body);

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should be true', function() {3 expect(true).to.be.true;4 });5});6 <script>mocha.run();</script>

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const app = require('../app');3sayHiResult = app.addNum(5,5);4describe('App', function(){5 it('addNum should return 10', function(){6 assert.equal(sayHiResult, 10);7 });8});9sayHiResult = app.sayHi('John');10describe('App', function(){11 it('sayHi should return hello', function(){12 assert.equal(sayHiResult, 'hello');13 });14});15addNumResult = app.addNum(5,5);16describe('App', function(){17 it('addNum should return type number', function(){18 assert.typeOf(addNumResult, 'number');19 });20});21addNumResult = app.addNum(5,5);22describe('App', function(){23 it('addNum should return type number', function(){24 assert.typeOf(addNumResult, 'number');25 });26});27addNumResult = app.addNum(5,5);28describe('App', function(){29 it('addNum should return type number', function(){30 assert.typeOf(addNumResult, 'number');31 });32});33addNumResult = app.addNum(5,5);34describe('App', function(){35 it('addNum should return type number', function(){36 assert.typeOf(addNumResult, 'number');37 });38});39addNumResult = app.addNum(5,5);40describe('App', function(){41 it('addNum should return type number', function(){42 assert.typeOf(addNumResult, 'number');43 });44});45addNumResult = app.addNum(5,5);46describe('App', function(){47 it('addNum should return type number', function(){48 assert.typeOf(addNumResult, 'number');49 });50});51addNumResult = app.addNum(5

Full Screen

Using AI Code Generation

copy

Full Screen

1const { describe, it } = require('mocha');2const { expect } = require('chai');3const { doc } = require('../src/doc');4describe('Doc', () => {5 it('should return the doc string of a function', () => {6 const docString = 'this is a doc string';7 const fn = () => {8 return true;9 };10 expect(doc(fn)).to.equal(docString);11 });12});13const doc = fn => {14 return docString ? docString[1].trim() : '';15};16module.exports = { doc };17{18 "scripts": {19 },20 "devDependencies": {21 }22}23const doc = fn => {24 return docString ? docString[1].trim() : '';25};26module.exports = { doc };27const { describe, it } = require('mocha');28const { expect } = require('chai');29const { doc } = require('../src/doc');30describe('Doc', () => {31 it('should return the doc string of a function', () => {32 const docString = 'this is a doc string';33 const fn = () => {34 return true;35 };36 expect(doc(fn)).to.equal(docString);37 });38});39{40 "scripts": {41 },42 "devDependencies": {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mocha automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful